#!/bin/sh /etc/rc.common
# vim: set noexpandtab tabstop=4 shiftwidth=4 softtabstop=4 :
# Copyright (C) 2015 ovh.com
# Copyright (C) 2017-2020 Ycarus (Yannick Chabanois) <ycarus@zugaina.org>

START=90
STOP=10

USE_PROCD=1
PROG_NAME=glorytun-udp
PROG=/usr/sbin/${PROG_NAME}

_log() {
	logger -p daemon.info -t ${PROG_NAME} "$@"
}

_err() {
	logger -p daemon.err -t ${PROG_NAME} "$@"
}

validate_section() {
	uci_validate_section glorytun-udp glorytun-udp "${1}" \
		'enable:bool:0'            \
		'mode:string'              \
		'key:string'               \
		'host:host'                \
		'port:port'                \
		'mtuauto:bool:0'           \
		'chacha:bool:0'            \
		'persist:bool:1'           \
		'kxtimeout:string:7d'      \
		'timetolerance:string:10m' \
		'keepalive:string:25s'     \
		'localip:string'           \
		'remoteip:string'          \
		'dev:string'
}

start_instance() {
	local enable key host port listener proto mtuauto chacha dev mode
	local persist kxtimeout timetolerance keepalive localip remoteip
	local key_dir="/var/run/${PROG_NAME}"
	local key_file="${key_dir}/${1}.key"

	validate_section "${1}" || {
		_err "validation failed"
		return 1
	}

	[ "${enable}" = "1" ] || return 1

	[ -n "${key}" ] || return 1
	[ "${key}" != "secretkey" ] || return 1
	[ -n "${port}" ] || return 1
	[ -n "${dev}" ] || return 1
	[ -n "${mode}" ] || return 1

	mkdir -p "$key_dir"
	chmod 0700 "$key_dir"
	( umask 077; printf '%s\n' "$key" > "$key_file" ) || {
		_err "can't create key file"
		return 1
	}
	key=""

	# a bare "uci commit" flushed every package's pending changes
	if [ -n "$(uci -q get network.omrvpn)" ] && [ "$(uci -q get network.omrvpn.device)" != "$dev" ]; then
		uci -q set network.omrvpn.device=$dev
		uci -q commit network
	fi

	_log "starting ${PROG_NAME} ${1} instance $*"

	# One address: resolveip prints all of them, which split into extra
	# arguments, and none on failure, both respawned broken forever
	local addr
	addr="$(resolveip -4 -t 5 "$host" | head -n1)"
	[ -n "$addr" ] || addr="$(resolveip -6 -t 5 "$host" | head -n1)"
	[ -n "$addr" ] || {
		_err "can't resolve $host"
		return 1
	}
	host="$addr"

	if [ "$mode" = "to" ]; then
		bind="bind from addr :: port 5000 to addr $host port $port"
	else
		bind="bind from addr $host port $port to addr :: port 5000"
	fi
	procd_open_instance

	procd_set_param command ${PROG} \
		${bind} \
		${dev:+dev "$dev"} \
		keyfile "$key_file"

	# LuCI's "Persist" was ignored: the device was always kept. Unset still
	# means kept, as before
	[ "${persist}" = "1" ] && procd_append_param command persist
	[ "${chacha}" = "1" ] && procd_append_param command chacha

	procd_set_param respawn 0 30 0
	procd_set_param nice 10
	procd_set_param file "$key_file"

	procd_set_param stdout 1
	procd_set_param stderr 1

	procd_close_instance

	# kxtimeout, timetolerance, keepalive and the tunnel addresses are not
	# bind arguments: only the ifup hotplug set them, and a restart that
	# keeps the device raises no ifup, nor does a change of them alone
	# (procd keeps the instance). Set them once the tunnel answers (ifconfig
	# leaves unchanged addresses alone); the delay leaves procd the time to
	# replace an instance it restarts. fd 1000 is procd.sh's service lock:
	# kept open, it would block every other glorytun-udp init call meanwhile
	(
		sleep 2
		count=0
		while ! ${PROG} list 2>/dev/null | grep -qxF "$dev"; do
			count=$((count + 1))
			[ "$count" -gt 10 ] && exit 0
			sleep 1
		done
		[ -n "$localip" ] && [ -n "$remoteip" ] &&
			ifconfig "$dev" "$localip" pointopoint "$remoteip" up
		${PROG} set dev "$dev" kxtimeout "$kxtimeout" timetolerance "$timetolerance" keepalive "$keepalive"
	) </dev/null >/dev/null 2>&1 1000>&- &

	#tc qdisc replace dev ${dev} root cake

	#ip link set $dev txqlen 100
	#config_load network
	#config_foreach add_glorytun_path interface

}

add_glorytun_path() {
	case "$1" in
		loopback|lan|if0|*tun*|ifb*) return ;;
	esac
	local multipath
	network_get_ipaddr ipaddr "$1"
	config_get multipath "$1" multipath "off"
	case "$multipath" in
		master|on) glorytun-udp path "$ipaddr" dev $dev up ;;
		backup) glorytun-udp path "$ipaddr" dev $dev backup ;;
		*) glorytun-udp path "$ipaddr" dev $dev down ;;
	esac
}

start_service() {
	local dev
	config_load glorytun-udp
	config_foreach start_instance glorytun-udp
}

# No reload_service: stop;start there restarted the tunnel on every network
# config change. The default (start) lets procd restart only an instance whose
# command or key file changed; kxtimeout, timetolerance, keepalive and the
# tunnel addresses are applied by start_instance either way.
service_triggers() {
	procd_add_reload_trigger glorytun-udp network
}
