#!/bin/sh /etc/rc.common

START=95
USE_PROCD=1


get_config() {
	config_get_bool enabled $1 enabled 1
	config_get_bool acceptRoutes $1 acceptRoutes 0
	config_get loginServer $1 loginServer ""
	config_get authkey $1 authkey ""
	config_get hostname $1 hostname ""
	config_get advertiseRoutes $1 advertiseRoutes ""
}
start_service() {
	logger -t tailscaler 'start_service'
	config_load tailscaler
	config_foreach get_config settings
	if [ "$enabled" != 1 ]; then
		stop_service
		return 1
	fi
	local fw_mode="iptables"
	[ -x /sbin/fw4 ] && fw_mode="nftables"
	if ! [ "$(uci -q get tailscale.settings.fw_mode)" = "$fw_mode" ]; then
		uci -q set "tailscale.settings.fw_mode=$fw_mode"
		uci -q commit tailscale
		/etc/init.d/tailscale reload 2>/dev/null
	fi
	#
	logger -t tailscaler 'start tailscale'
	/etc/init.d/tailscale running || /etc/init.d/tailscale start
	logger -t tailscaler 'start tailscaler'
	# 
	procd_open_instance
	procd_set_param command /usr/sbin/tailscale up --reset
	if [ -n "$loginServer" ]; then
		procd_append_param command --login-server "$loginServer" 
	fi
	if [ -n "$authkey" ]; then
		procd_append_param command --authkey "$authkey" 
	fi
	if [ -n "$hostname" ]; then
		procd_append_param command --hostname "$hostname" 
	fi
	if [ "$acceptRoutes" = 1 ]; then
		procd_append_param command --accept-routes
	fi
	if [ -n "$advertiseRoutes" ];then
		procd_append_param command --advertise-routes "$advertiseRoutes"
	fi
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_close_instance
	logger -t tailscaler 'end tailscaler'
}
stop_service() {
	/etc/init.d/tailscale stop
	/etc/init.d/tailscale running && sleep 2
}
