#!/bin/bash
set -euo pipefail

tailscale_bin=""
if command -v tailscale >/dev/null 2>&1; then
  tailscale_bin="$(command -v tailscale)"
elif [[ -x /Applications/Tailscale.app/Contents/MacOS/Tailscale ]]; then
  tailscale_bin="/Applications/Tailscale.app/Contents/MacOS/Tailscale"
fi

if [[ -z "$tailscale_bin" ]]; then
  echo "Tailscale is not installed. Opening the official macOS download page..."
  open 'https://tailscale.com/download/mac'
  read -r -p "Install Tailscale, then run this tool again. Press Enter to close"
  exit 0
fi

echo "Connecting to the Angox support network..."
echo "Your browser will open sso.angox.me. Only approved tailscale-support users can continue."
"$tailscale_bin" up --login-server=https://hs.angox.me --accept-dns=true
echo "Connected. Tailscale IPv4: $("$tailscale_bin" ip -4 | head -n 1)"
read -r -p "Press Enter to close"
