#!/bin/sh /etc/rc.common
## Logrus tunnel client — procd init.

USE_PROCD=1
START=95
STOP=10

PROG=/usr/sbin/logrus-client
STATE_DIR=/etc/logrus

start_service() {
	config_load logrus

	local enabled
	config_get_bool enabled main enabled 0
	if [ "$enabled" -ne 1 ]; then
		return 0
	fi

	# A connect run with no session on disk would prompt interactively,
	# which procd silently turns into a respawn loop. Refuse early with a
	# loud error in syslog so the user knows where to look.
	if [ ! -s "$STATE_DIR/session.json" ]; then
		echo "logrus: no session at $STATE_DIR/session.json — run uci-defaults" \
			"or 'logrus-client login' before enabling the service" \
			| logger -t logrus -p daemon.err
		return 1
	fi

	local user_server server country city tun
	config_get user_server main user_server 'https://logrus.space/api'
	config_get server      main server ''
	config_get country     main country ''
	config_get city        main city ''
	config_get_bool tun    main tun 1

	procd_open_instance
	procd_set_param command "$PROG" connect --no-gui

	[ -n "$server" ]  && procd_append_param command --server  "$server"
	[ -n "$country" ] && procd_append_param command --country "$country"
	[ -n "$city" ]    && procd_append_param command --city    "$city"
	[ "$tun" -eq 1 ]  && procd_append_param command --tun

	procd_set_param env \
		LOGRUS_USER_SERVER="$user_server" \
		LOGRUS_CLIENT_HOME="$STATE_DIR"

	# respawn: 3600s threshold means a crash within an hour bumps the
	# retry counter; 5s timeout between restarts; 5 retries before procd
	# gives up. Tuned for "tunnel briefly flapped" rather than "binary
	# is broken" — a broken binary stops looping after ~25s.
	procd_set_param respawn 3600 5 5
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_set_param file /etc/config/logrus
	procd_close_instance
}

service_triggers() {
	procd_add_reload_trigger logrus
	procd_add_reload_interface_trigger wan
}

reload_service() {
	stop
	start
}
