#!/bin/sh /etc/rc.common
# Generated by `securqbitd install`. Edits are overwritten on reinstall.

# The tunnel pins the VPN node to whatever route reaches it today, so it
# cannot start until netifd has the WAN up. 95 is after everything that
# configures an interface; 10 is before anything tears one down.
START=95
STOP=10

USE_PROCD=1

PROG=/usr/sbin/securqbitd
PROG_ARGS='--config /etc/securqbit/config.yaml'
PIDFILE=/var/run/securqbit/securqbitd.pid
RUNDIR=/var/run/securqbit
STATEDIR=/etc/securqbit/state
LOGDIR=/var/log/securqbit

start_service() {
	mkdir -p "$RUNDIR" && chmod 0755 "$RUNDIR"
	# State is on the overlay rather than under /var, which on OpenWrt is a
	# symlink to tmpfs. Losing it would mint a new device id at every reboot.
	mkdir -p "$STATEDIR" && chmod 0700 "$STATEDIR"
	mkdir -p "$LOGDIR" && chmod 0750 "$LOGDIR"

	# /dev/net/tun comes from the kmod-tun package. Loading it here rather than
	# relying on the first connect means a missing module is reported by the
	# service that needs it instead of by a failed connect an hour later.
	[ -c /dev/net/tun ] || modprobe tun 2>/dev/null

	procd_open_instance
	# shellcheck disable=SC2086
	procd_set_param command "$PROG" $PROG_ARGS
	procd_set_param pidfile "$PIDFILE"
	# A VPN daemon that has failed a few times is not something to give up on:
	# on a router the usual cause is a WAN that is not up yet. The trailing 0
	# means "keep retrying", instead of procd's default of five and then never.
	procd_set_param respawn 3600 5 0
	# The daemon restores the routes and resolvers it replaced on the way out.
	# procd's default of five seconds is not enough to finish, and a router
	# that is cut short there comes back up with no way off the LAN.
	procd_set_param term_timeout 20
	# A proxy holds a file descriptor per connection, and every device on the
	# LAN is now behind this one.
	procd_set_param limits nofile="65535 65535"
	# Into syslog, which is what logread reads. The copy under $LOGDIR is on
	# tmpfs and does not survive a reboot.
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_close_instance
}

# procd sends SIGTERM and waits out term_timeout, which is all the daemon needs
# — it tears the tunnel down and restores the host's routing on that signal.
stop_service() {
	return 0
}

service_triggers() {
	# Deliberately empty. The obvious trigger would be a network reload, but
	# reacting to one would restart the daemon — and so drop the tunnel — every
	# time anything on the router touched an unrelated interface.
	return 0
}
