#!/bin/sh

DEADLINE_FILE=/var/run/vpn-support.deadline
WATCHDOG_INIT=/etc/init.d/vpn-support-watchdog

uptime_seconds() {
	local uptime
	read -r uptime _ < /proc/uptime || return 1
	printf '%s\n' "${uptime%%.*}"
}

valid_deadline() {
	case "$1" in
		''|*[!0-9]*) return 1 ;;
		*) return 0 ;;
	esac
}

expire_support_vpn() {
	if VPN_SUPPORT_FROM_WATCHDOG=1 /sbin/vpn-support stop >/dev/null 2>&1; then
		# Deliberately stop the procd instance after a normal expiry to prevent respawn.
		exec "$WATCHDOG_INIT" stop
	fi

	# Keep the procd-supervised watchdog alive until a failed stop can be retried.
	sleep 1
}

while :; do
	if [ ! -r "$DEADLINE_FILE" ]; then
		# The controlling wrapper stops this service after explicit stop cleanup.
		sleep 1
		continue
	fi

	if ! read -r deadline < "$DEADLINE_FILE" || ! valid_deadline "$deadline"; then
		expire_support_vpn
		continue
	fi
	now=$(uptime_seconds) || {
		expire_support_vpn
		continue
	}
	remaining=$((deadline - now))
	if [ "$remaining" -le 0 ]; then
		expire_support_vpn
		continue
	fi
	sleep "$remaining"
done
