#!/sbin/openrc-run

# Uppercase variables are for backward compatibility (Alpine <3.21).
: ${capabilities="^cap_net_admin,cap_net_raw"}
: ${command_user:="root:tailscale"}
: ${logfile="${TAILSCALED_LOGFILE:-"/var/log/tailscaled.log"}"}
: ${no_logs_no_support:=no}
: ${port:="${TAILSCALED_PORT:-41641}"}
: ${socket:="/run/tailscale/tailscaled.sock"}
: ${statedir:="/var/lib/tailscale"}
: ${supervisor="supervise-daemon"}
: ${verbose:=0}

command="/usr/sbin/tailscaled"
command_args="--socket=$socket --state=$statedir/tailscaled.state --port=$port --verbose=$verbose $TAILSCALED_OPTS $command_args"
command_background=yes
pidfile="/run/$RC_SVCNAME.pid"

output_log="$logfile"
error_log="$logfile"

# Alpine uses the nf_tables backend by default (see #14058). The "auto"
# heuristic doesn't work correctly, it prefers iptables (and fails due to
# missing modules) even when nftables are in use.
# See https://tailscale.com/kb/1294/firewall-mode
export TS_DEBUG_FIREWALL_MODE="${firewall_mode:-"nftables"}"

depend() {
	need net
	after firewall
	use logger
}

start_pre() {
	yesno "$no_logs_no_support" && command_args="$command_args --no-logs-no-support"

	if [ -e /usr/sbin/resolvconf ] && command -v doas >/dev/null; then
		# The purpose of this is to make tailscaled use our resolvconf wrapper that
		# executes /usr/sbin/resolvconf via doas.
		export PATH="/usr/libexec/tailscale:$PATH"
	fi

	checkpath -f -m 0640 -o "$command_user" "$logfile" || return 1
	checkpath -d -m 0755 -o "$command_user" "${socket%/*}"
}
