#!/bin/bash
# vless — campus/office tunnel over VLESS + WebSocket + TLS.
#
#   vless setup <link>  save the subscription link this copy will use
#   vless on        start tunnel, verify real traffic, then set the system proxy
#   vless off       stop tunnel and clear the proxy
#   vless status    what is running
#   vless uninstall remove everything (needs admin)
#
# Safety rule: the system proxy is set only AFTER traffic through the tunnel is
# proven, and a detached watcher clears it the moment the tunnel dies. Failure
# mode is "sites stop loading", never "no internet at all".
set -u

PREFIX="${VLESS_PREFIX:-/usr/local/libexec/vless}"
STATE="$HOME/.vless"
XRAY="$PREFIX/xray"
SUB="${VLESS_SUB:-$PREFIX/subscription}"
[ -r "$SUB" ] || SUB="$STATE/subscription"
HELPER="${VLESS_HELPER:-/usr/local/libexec/proxy-toggle}"
PORT="${VLESS_PORT:-1080}"
NO_PROXY="${VLESS_NO_PROXY:-0}"
mkdir -p "$STATE" 2>/dev/null

say() { printf '%s\n' "$*"; }
log() { printf '%s %s\n' "$(date '+%F %T')" "$*" >>"$STATE/vless.log"; }

pid_alive() {  # $1 = pidfile
    [ -f "$1" ] || return 1
    local p; p=$(cat "$1" 2>/dev/null)
    case "$p" in ''|*[!0-9]*) return 1 ;; esac
    kill -0 "$p" 2>/dev/null
}

urldecode() { printf '%s' "$1" | perl -pe 's/%([0-9A-Fa-f]{2})/chr(hex($1))/ge' 2>/dev/null; }

qp() {  # $1 = query string, $2 = key
    printf '%s' "$1" | tr '&' '\n' | sed -n "s/^$2=//p" | head -1
}

is_ip() { case "$1" in ''|*[!0-9a-fA-F.:]*) return 1 ;; *[0-9]*) return 0 ;; *) return 1 ;; esac; }

egress() {  # $1 = direct|proxy
    local out=""
    if [ "$1" = proxy ]; then
        out=$(curl -s --max-time 12 --socks5-hostname "127.0.0.1:$PORT" https://api.ipify.org 2>/dev/null)
        is_ip "$out" || out=$(curl -s --max-time 12 --socks5-hostname "127.0.0.1:$PORT" https://ifconfig.me/ip 2>/dev/null)
    else
        out=$(curl -s --max-time 8 --noproxy '*' https://api.ipify.org 2>/dev/null)
    fi
    is_ip "$out" && printf '%s' "$(printf '%s' "$out" | tr -d '[:space:]')"
}

fetch_links() {  # prints one vless:// link per line, 443 first
    [ -f "$SUB" ] || return 1
    local url body
    url=$(head -1 "$SUB" | tr -d '[:space:]')
    body=$(curl -s --noproxy '*' --max-time 25 "$url" 2>/dev/null)
    case "$body" in
        vless://*) : ;;
        "") return 1 ;;
        *) body=$(printf '%s' "$body" | base64 -D 2>/dev/null) ;;
    esac
    case "$body" in *vless://*) : ;; *) return 1 ;; esac
    printf '%s\n' "$body" | grep '^vless://' | grep -e ':443' -e '=443'
    printf '%s\n' "$body" | grep '^vless://' | grep -v -e ':443' -e '=443'
}

write_cfg() {  # $1 = link
    local rest userinfo hostport host port q id sni whost wpath
    rest="${1#vless://}"
    userinfo="${rest%%@*}"
    hostport="${rest#*@}"; hostport="${hostport%%\?*}"
    id=$(urldecode "$userinfo")
    host="${hostport%:*}"; port="${hostport##*:}"
    case "$port" in ''|*[!0-9]*) port=443 ;; esac
    q="${rest#*\?}"; [ "$q" = "$rest" ] && q=""
    sni=$(qp "$q" sni); [ -n "$sni" ] || sni=$(qp "$q" host); [ -n "$sni" ] || sni="$host"
    whost=$(qp "$q" host); [ -n "$whost" ] || whost="$sni"
    wpath=$(urldecode "$(qp "$q" path)"); [ -n "$wpath" ] || wpath="/"
    cat >"$STATE/cfg.json" <<JSON
{
  "log": {"loglevel": "warning"},
  "inbounds": [{"port": $PORT, "listen": "127.0.0.1", "protocol": "socks",
                "settings": {"udp": true, "auth": "noauth"}}],
  "outbounds": [{
    "protocol": "vless",
    "settings": {"vnext": [{"address": "$host", "port": $port,
                            "users": [{"id": "$id", "encryption": "none"}]}]},
    "streamSettings": {"network": "ws", "security": "tls",
      "tlsSettings": {"serverName": "$sni", "fingerprint": "chrome"},
      "wsSettings": {"path": "$wpath", "headers": {"Host": "$whost"}}}
  }]
}
JSON
    printf '%s:%s' "$host" "$port"
}

stop_all() {
    touch "$STATE/stop" 2>/dev/null
    local n
    for n in supervisor.pid xray.pid; do
        if pid_alive "$STATE/$n"; then kill "$(cat "$STATE/$n")" 2>/dev/null; fi
    done
    sleep 1
    rm -f "$STATE/xray.pid" "$STATE/supervisor.pid" "$STATE/status" "$STATE/cfg.json" "$STATE/stop" 2>/dev/null
}

cmd_on() {
    local keep=0
    [ "${1:-}" = "--keep" ] && keep=1
    if pid_alive "$STATE/xray.pid"; then
        say "already on: $(cat "$STATE/status" 2>/dev/null)"
        return 0
    fi
    # something else on the port would make the checks below test the wrong tunnel
    if lsof -nP -iTCP:"$PORT" -sTCP:LISTEN >/dev/null 2>&1; then
        say "FAILED: port $PORT is already in use by another program; nothing was changed"
        return 1
    fi
    if [ ! -s "$SUB" ]; then
        say "no subscription link saved yet."
        say "get the link from whoever sent you this installer, then run:  vless setup <link>"
        return 1
    fi
    rm -f "$STATE/stop"
    if [ "$keep" = 1 ]; then echo 1 >"$STATE/keep"; else rm -f "$STATE/keep"; fi

    local links direct
    links=$(fetch_links)
    if [ -z "$links" ]; then
        say "FAILED: could not fetch the subscription (network down, or the link is dead)"
        return 1
    fi
    direct=$(egress direct)
    say "direct egress=${direct:-unknown}  nodes=$(printf '%s\n' "$links" | wc -l | tr -d ' ')"

    local i=0 link node ip attempt
    while IFS= read -r link; do
        [ -n "$link" ] || continue
        i=$((i + 1)); [ "$i" -le 8 ] || break
        node=$(write_cfg "$link")
        nohup "$XRAY" run -c "$STATE/cfg.json" >"$STATE/xray.log" 2>&1 &
        echo $! >"$STATE/xray.pid"
        sleep 2
        ip=""
        attempt=0
        while [ "$attempt" -lt 3 ]; do
            attempt=$((attempt + 1))
            pid_alive "$STATE/xray.pid" || break
            ip=$(egress proxy)
            [ -n "$ip" ] && [ "$ip" != "$direct" ] && break
            ip=""
            sleep 2
        done
        if [ -n "$ip" ]; then
            say "node $i $node -> egress=$ip"
            if [ "$NO_PROXY" != 1 ]; then
                sudo -n "$HELPER" on >/dev/null 2>&1 || say "warning: could not set the system proxy (needs admin)"
            fi
            printf 'node=%s egress=%s direct=%s\n' "$node" "$ip" "${direct:-unknown}" >"$STATE/status"
            log "up node=$node egress=$ip"
            nohup "$0" __supervise "$(cat "$STATE/xray.pid")" >/dev/null 2>&1 &
            echo $! >"$STATE/supervisor.pid"
            say "ON  (proxy -> 127.0.0.1:$PORT)"
            return 0
        fi
        say "node $i $node no data"
        kill "$(cat "$STATE/xray.pid")" 2>/dev/null
        rm -f "$STATE/xray.pid"
    done <<EOF
$links
EOF
    say "FAILED: no node carried data; nothing was changed"
    log "failed: no working node"
    return 1
}

cmd_off() {
    stop_all
    if [ "$NO_PROXY" != 1 ]; then
        sudo -n "$HELPER" off 2>/dev/null || say "warning: could not clear the system proxy"
    fi
    log "down"
    say "OFF"
    return 0
}

cmd_supervise() {  # $1 = xray pid
    while kill -0 "$1" 2>/dev/null; do sleep 5; done
    [ "$NO_PROXY" = 1 ] || sudo -n "$HELPER" off >/dev/null 2>&1
    rm -f "$STATE/status" "$STATE/xray.pid" "$STATE/cfg.json" 2>/dev/null
    log "tunnel died; proxy cleared"
}

cmd_setup() {  # $1 = subscription link
    local url="${1:-}"
    if [ -z "$url" ]; then
        printf 'paste the subscription link: '
        read -r url
    fi
    case "$url" in
        http://*|https://*) ;;
        *) say "that is not a link (it must start with http:// or https://)"; return 1 ;;
    esac
    mkdir -p "$STATE"
    printf '%s\n' "$url" >"$STATE/subscription"
    chmod 600 "$STATE/subscription"
    SUB="$STATE/subscription"
    say "saved to $STATE/subscription"
    say "next: vless on"
    return 0
}

cmd_status() {
    local up=down
    pid_alive "$STATE/xray.pid" && up=up
    if [ -s "$SUB" ]; then say "subscription: saved"; else say "subscription: none (run: vless setup <link>)"; fi
    say "tunnel=$up $([ -f "$STATE/status" ] && cat "$STATE/status")"
    if [ "$NO_PROXY" != 1 ]; then
        say "proxy: $(sudo -n "$HELPER" status 2>/dev/null | tr '\n' ' ')"
    fi
    return 0
}

cmd_uninstall() {
    stop_all
    say "removing /usr/local/libexec/vless and its helpers (admin password needed)"
    exec sudo /bin/bash "$PREFIX/uninstall"
}

case "${1:-status}" in
    setup)       shift; cmd_setup "${1:-}" ;;
    on)          shift; cmd_on "${1:-}" ;;
    off)         cmd_off ;;
    status)      cmd_status ;;
    uninstall)   cmd_uninstall ;;
    __supervise) cmd_supervise "${2:-0}" ;;
    *)           say "usage: vless setup <link> | on [--keep] | off | status | uninstall"; exit 1 ;;
esac
