#!/bin/sh
#
# $FreeBSD: head/security/tinc-devel/files/tincd.in 531850 2020-04-16 14:49:59Z dinoex $
#
# PROVIDE: tincd
# REQUIRE: ipfilter FILESYSTEMS sysctl netif
# BEFORE:  SERVERS routing
# KEYWORD: shutdown
#
# Define these tincd_* variables in one of these files:
#	/etc/rc.conf
#	/etc/rc.conf.local
#	/etc/rc.conf.d/tincd
#
# tincd_enable (bool):	Set to "NO" by default.
#			Set it to "YES" to enable tincd.
# tincd_cfg (str):	Set to "" by default.
#			Set it to NETNAMEs to use (ex.: "vpn1 vpn2").
# tincd_flags (str):	Set to "" by default.
#			Set it to flags to use (ex.: "-d 1 --logfile").
#
# DO NOT CHANGE THESE DEFAULT VALUES HERE

. /etc/rc.subr

name="tincd"
desc="Tinc VPN Daemon"
rcvar="tincd_enable"

load_rc_config $name

: ${tincd_enable:="NO"}
command="%%PREFIX%%/sbin/tinc"
start_cmd="tincd_start"
stop_cmd="tincd_stop"
reload_cmd="tincd_reload"
status_cmd="tincd_status"
extra_commands="reload"
procname=${command:-tincd}
ldconfig_command="/sbin/ldconfig"

tincd_start()
{
	${ldconfig_command} -elf -m %%LOCALBASE%%/lib
	if test -z "${tincd_cfg}"
	then
		echo "Starting tincd"
		$command start
	else
		for cfg in ${tincd_cfg}
		do
			echo "Starting tincd for: ${cfg}"
			$command -n $cfg start $tincd_flags
		done
	fi
	# code deliberately borrowed from /etc/rc.d/netif
	if [ -f /etc/rc.d/ipfilter ] ; then
		# Resync ipfilter
		/etc/rc.d/ipfilter quietresync
	fi
}

tincd_stop()
{
	if test -z "${tincd_cfg}"
	then
		echo "Stopping tincd"
		$command stop
	else
		for cfg in $tincd_cfg
		do
			echo "Stopping tincd for: ${cfg}"
			$command -n $cfg stop
		done
	fi
	wait_for_pids $rc_pid
}

tincd_reload()
{
	if test -z "${tincd_cfg}"
	then
		echo "Sending reload to tincd"
		$command reload
	else
		for cfg in $tincd_cfg
		do
			echo "Sending reload to tincd for: ${cfg}"
			$command -n $cfg reload
		done
	fi
}

tincd_status_network()
{
	if [ -n "$rc_pid" ]; then
		echo "${name} for ${cfg} is running as pid $rc_pid."
	else
		echo "${name} for ${cfg} is not running."
		return 1
	fi
}

tincd_status()
{
	if test -z "${tincd_cfg}"
	then
		cfg="."
		rc_pid=$($command pid)
		tincd_status_network
	else
		for cfg in $tincd_cfg
		do
			rc_pid=$($command -n $cfg pid)
			tincd_status_network
		done
	fi
}

run_rc_command "$1"