#! /bin/sh -

# SPDX-License-Identifier: BSD-2-Clause
#
# Copyright (c) 2020-2026 Mateusz Piotrowski <0mp@FreeBSD.org>
#

# PROVIDE: fahclient
# REQUIRE: DAEMON LOGIN NETWORKING linux

#
# Refer to to the fahclient(8) manual page for the configuration instructions.
#

. /etc/rc.subr

name='fahclient'
rcvar='fahclient_enable'

load_rc_config 'fahclient'

# Default settings.
: "${fahclient_enable:=NO}"
: "${fahclient_user:=fahclient}"
# The program is going to create a lot of files in its working directory,
# so make sure that they all land in a sensible place.
: "${fahclient_chdir:=/var/db/fahclient}"
: "${fahclient_svcj_options:=net_basic}"

: "${fahclient_donor=Anonymous}"
: "${fahclient_team=11743}"

: "${fahclient_pidfile:=/var/db/fahclient/fahclient.pid}"
: "${fahclient_config:=/usr/local/etc/fahclient/config.xml}"
: "${fahclient_logfile:=/var/db/fahclient/log.txt}"

pidfile="${fahclient_pidfile}"
procname="/usr/local/bin/fah-client"
command="/usr/sbin/daemon"
command_args="-p ${pidfile} -- ${procname}"
# Some notes on the specified options:
# - --user sets the donor work units are attributed to (config file takes
#   precedence).
# - --team sets the team work units are attributed to (cfg file takes
#   precedence).
# - --config is necessary to point the program to the correct configuration
#   file.
# - fahclient_extra_flags are passed in after all other options.
_fahclient_command_args=
_fahclient_command_args="${_fahclient_command_args} ${fahclient_donor:+--user=${fahclient_donor}}"
_fahclient_command_args="${_fahclient_command_args} ${fahclient_team:+--team=${fahclient_team}}"
_fahclient_command_args="${_fahclient_command_args} --config=${fahclient_config}"
_fahclient_command_args="${_fahclient_command_args} --log=${fahclient_logfile}"
_fahclient_command_args="${_fahclient_command_args} --log-rotate-dir=$(dirname "${fahclient_logfile}")"
_fahclient_command_args="${_fahclient_command_args} --log-to-screen=false"
_fahclient_command_args="${_fahclient_command_args} ${fahclient_extra_flags}"
command_args="${command_args} ${_fahclient_command_args}"
extra_commands="log showconfig"
log_cmd="tail -F -- ${fahclient_logfile}"
showconfig_cmd="${procname} ${_fahclient_command_args} --log-to-screen=true --print"
if [ -n "$fahclient_user" ]; then
	showconfig_cmd="su -m $fahclient_user -c 'sh -c \"$showconfig_cmd\"'"
fi
required_modules='linprocfs linsysfs linux64:linux64elf'

run_rc_command "$1"
