#!/usr/bin/env bash
# Tailscale install with on-screen password prompt (pkexec)
set -euo pipefail
export DEBIAN_FRONTEND=noninteractive
LOG=/tmp/texano_tailscale_install.log
exec > >(tee -a "$LOG") 2>&1
echo "=== $(date) Texano Tailscale setup ==="

if ! command -v tailscale >/dev/null 2>&1; then
  echo "Downloading Tailscale install script…"
  curl -fsSL https://tailscale.com/install.sh -o /tmp/tailscale_install.sh
  chmod +x /tmp/tailscale_install.sh
  echo "Need admin password in the popup…"
  pkexec env DEBIAN_FRONTEND=noninteractive bash /tmp/tailscale_install.sh
fi

echo "Enabling tailscaled…"
pkexec systemctl enable --now tailscaled

echo "Bringing Tailscale up (browser login may open)…"
# tailscale up often needs root for tun
pkexec tailscale up --accept-dns=false || sudo tailscale up --accept-dns=false

echo
echo "=== DONE ==="
echo "Tailscale IPv4:"
tailscale ip -4 || true
echo "Status:"
tailscale status || true
echo
IP4=$(tailscale ip -4 2>/dev/null | head -1 || true)
if [ -n "$IP4" ]; then
  echo "On phone: install Tailscale app → same account → open:"
  echo "  http://${IP4}:8765/EXEC_DESK_MOCK.html"
  echo "Then Add to Home screen."
fi
# ensure desk bridge is up on all interfaces
DIR="$(cd "$(dirname "$0")" && pwd)"
if ! ss -ltn | grep -q ':8765 '; then
  python3 "$DIR/serve_last_click.py" >/tmp/last_click_serve.log 2>&1 &
  sleep 0.4
fi
echo "Desk bridge should answer on :8765 (LAN + Tailscale)."
