#!/bin/sh
# Remote debugging switch: starts or stops sshd from the flag the launcher
# writes (Settings > System). Runs as root:
#   sf-remote-debug          the flag changed (sf-remote-debug.path)
#   sf-remote-debug boot     at boot (sf-remote-debug-boot.service)
#   sf-remote-debug expire   the time limit is up (transient timer)
#
# The flag holds "on" or "off". On real hardware ssh never stays on for long:
# it turns off after LIMIT and on every boot. In a VM it stays on without a
# flag and has no limit, because the dev tools (tools/vm) need ssh.
FLAG=/var/lib/smartfox/remote-debug
LIMIT=1h
TIMER=sf-remote-debug-off

vm() { systemd-detect-virt -q; }

stop_timer() {
    systemctl stop "$TIMER.timer" 2>/dev/null
    systemctl reset-failed "$TIMER.timer" "$TIMER.service" 2>/dev/null
}

off() {
    stop_timer
    exec systemctl --no-block stop ssh.service
}

case "${1:-}" in
    boot | expire)
        # Missing flag = off; tv owns the folder and can write it again.
        vm && [ "$1" = boot ] || rm -f "$FLAG"
        ;;
esac

if [ -f "$FLAG" ]; then
    state=$(cat "$FLAG")
elif vm; then
    state=on
else
    state=off
fi

[ "$state" = on ] || off

stop_timer
if ! vm; then
    systemd-run --quiet --unit="$TIMER" --on-active="$LIMIT" --timer-property=AccuracySec=1s \
        /usr/bin/sf-remote-debug expire
fi
exec systemctl --no-block start ssh.service
