#!/bin/bash
#
# Purpose : NetworkManager runs this as root when the network's connectivity
#           changes (configure tailscale installs it in dispatcher.d).
#           On a network with a sign-in page (a captive portal: hotels,
#           airports, trains), a Tailscale exit node sends the sign-in page
#           into a tunnel the network is still blocking, so the sign-in page
#           never loads. Stop using the exit node until you've signed
#           in, then use it again.

# For the tests
PAUSED="${CAPTIVE_PORTAL_STATE:-/run/federated-connector-exit-node-paused}"

[ "$2" = connectivity-change ] || exit 0
command -v tailscale > /dev/null || exit 0

case "$CONNECTIVITY_STATE" in
  PORTAL)
    [ -e "$PAUSED" ] && exit 0
    # The exit node's Tailscale address, without its /32
    node="$(tailscale status --json 2> /dev/null | jq -r '.ExitNodeStatus.TailscaleIPs[0] // empty')"
    node="${node%/*}"
    [ -n "$node" ] || exit 0
    echo "$node" > "$PAUSED"
    if tailscale set --exit-node=; then
      logger -t federated-connector "Signing in to a captive portal: stopped using exit node $node until online"
    else
      rm -f "$PAUSED"
    fi
    ;;
  FULL)
    [ -s "$PAUSED" ] || exit 0
    node="$(< "$PAUSED")"
    # Leave it if you picked another exit node meanwhile
    if [ -z "$(tailscale status --json 2> /dev/null | jq -r '.ExitNodeStatus // empty')" ]; then
      tailscale set --exit-node="$node" \
        && logger -t federated-connector "Online again: using exit node $node again"
    fi
    rm -f "$PAUSED"
    ;;
esac
exit 0
