#!/bin/bash
get-state() {
    if systemctl is-active --quiet tailscaled.service && [[ $(tailscale status --peers=false --json=true | jq -r '.Self.Online') = "true" ]]; then
        current_state="online"
    else
        current_state="offline"
    fi
}
transition() {
    if [[ "$current_state" != "$prev_state" ]]; then
        if [[ "$current_state" = "online" ]]; then
            systemctl start tailscale-online.target
        else
            systemctl stop tailscale-online.target
        fi
        echo "$current_state" > /tmp/tailscale-state
    fi
}
check-state() {
    get-state
    if [[ -s /tmp/tailscale-state ]]; then
        prev_state=$(</tmp/tailscale-state)
    else
        prev_state="offline"
        # uncomment if state has to be written even if still offline on all invocations before first transition to online
        # touch /tmp/tailscale-state
        # echo "$current_state" > /tmp/tailscale-state
    fi
    transition
}

main() {
    check-state
}

main "$@"
