#!/bin/sh
# quinn-phone-bootstrap — one-shot end-to-end setup for a phone (or tablet) to
# reach the home LAN via the wg1 mesh, with .local resolution.
#
# What it runs (in order):
#   1. wg-dns-sync on apricot       — installs/updates dnsmasq wg-mesh.conf,
#                                     so the phone resolves *.apricot.local etc.
#                                     Requires interactive sudo on apricot
#                                     (uses ssh -t to forward your tty).
#   2. wg-phone-add (locally)       — generates or reuses the device's keypair,
#                                     adds peer to quinn-vps wg1 hub, prints QR.
#
# Idempotent: re-runs are no-ops where possible. Use --device to onboard a new
# device (default: phone-quinn).
#
# Usage:
#   quinn-phone-bootstrap                       # full setup, default device
#   quinn-phone-bootstrap -d ipad-quinn         # onboard a new device
#   quinn-phone-bootstrap --skip-dns            # skip the apricot dnsmasq step
#   quinn-phone-bootstrap --show -d phone-quinn # just re-render the QR
#
# Run interactively (so apricot's sudo can prompt):
#   ! quinn-phone-bootstrap

set -eu

device="phone-quinn"
skip_dns=0
show_only=0

while [ $# -gt 0 ]; do
    case $1 in
        -d) device=$2; shift 2 ;;
        --skip-dns) skip_dns=1; shift ;;
        --show) show_only=1; shift ;;
        -h|--help) sed -n '2,21p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
        *) echo "unknown arg: $1" >&2; exit 1 ;;
    esac
done

script_dir=$(cd "$(dirname "$0")" && pwd)

if [ "$show_only" -eq 0 ] && [ "$skip_dns" -eq 0 ]; then
    echo "===== step 1/2: sync dnsmasq on apricot ====="
    # ssh -t so apricot's sudo can prompt against the user's tty.
    ssh -t apricot 'cd /var/home/lilith/Code/@scripts/session-tools && sudo bin/wg-dns-sync'
    echo
fi

echo "===== step $([ "$show_only" -eq 1 ] && echo "1/1" || echo "2/2"): phone WireGuard peer ====="
if [ "$show_only" -eq 1 ]; then
    "$script_dir/wg-phone-add" -d "$device" --show
else
    "$script_dir/wg-phone-add" -d "$device"
fi

echo
echo "Bootstrap complete."
echo "If the QR was already imported on the phone before, scanning again is harmless"
echo "(WireGuard iOS will refuse to import a duplicate)."
