#!/bin/bash
# vless-autostart — decides whether this network needs the tunnel.
#
# A network "needs" it when a few well-known sites fail to load directly. That
# covers campus/office filtering without hard-coding any one school's name, and
# it turns the tunnel off again on a normal connection.
#
# Called by the LaunchAgent on network changes, on login, and every 5 minutes.
set -u

VLESS=/usr/local/libexec/vless/vless
STATE="$HOME/.vless"
# no link configured (public build): stay silent instead of logging a failure every 5 minutes
SUB="${VLESS_SUB:-/usr/local/libexec/vless/subscription}"
[ -s "$SUB" ] || [ -s "$STATE/subscription" ] || exit 0
LOG="$HOME/Library/Logs/vless-autostart.log"
LOCK="$STATE/.autostart.lock"
mkdir -p "$STATE" "$(dirname "$LOG")" 2>/dev/null

log() { printf '%s %s\n' "$(date '+%F %T')" "$*" >>"$LOG"; }
up() { "$VLESS" status 2>/dev/null | grep -q 'tunnel=up'; }

probe() {  # $1 = url -> 0 if reachable directly
    curl -s -o /dev/null -w '%{http_code}' --max-time 7 --noproxy '*' "$1" 2>/dev/null | grep -q -E '^[23]'
}

# --- do we need it here? --------------------------------------------------
dom=$(ipconfig getoption en0 domain_name 2>/dev/null || true)
need=0
reason="network allows the sites we test"
case "${dom:-}" in
    *islandschool*) need=1; reason="school domain $dom" ;;
esac

if [ "$need" = 0 ]; then
    fails=0
    for u in https://www.youtube.com/ https://www.instagram.com/ https://discord.com/; do
        probe "$u" || fails=$((fails + 1))
    done
    if [ "$fails" -ge 2 ]; then
        need=1
        reason="direct access blocked ($fails/3 sites)"
    fi
fi

if [ "${1:-}" = "--dry-run" ]; then
    echo "need=$need dom=${dom:-none} reason=\"$reason\" tunnel=$(up && echo up || echo down)"
    exit 0
fi

# --- one run at a time ----------------------------------------------------
if ! mkdir "$LOCK" 2>/dev/null; then
    log "another run in progress; skipping"
    exit 0
fi
trap 'rmdir "$LOCK" 2>/dev/null' EXIT

if [ "$need" = 1 ]; then
    if up; then
        log "needs tunnel ($reason); already up"
        exit 0
    fi
    log "needs tunnel ($reason); starting"
    if "$VLESS" on >>"$LOG" 2>&1; then
        log "tunnel up"
    else
        log "tunnel failed; system proxy untouched"
    fi
else
    if up; then
        if [ -f "$STATE/keep" ]; then
            log "not needed here but keep flag set; leaving up"
        else
            log "not needed here ($reason); taking tunnel down"
            "$VLESS" off >>"$LOG" 2>&1
        fi
    fi
fi
