#!/bin/bash
# EmmaVPN privileged helper — installed as /usr/lib/emmavpn/emmavpn-helper
# and run through pkexec (polkit action com.emmavpn.vpn.helper), so the
# logged-in user can connect / disconnect without typing a password.
#
#   connect [ks-on|ks-off]   OpenVPN. stdin: line 1 = username,
#                            line 2 = password, rest = .ovpn config.
#                            ks-on arms the kill switch.
#   connect-wireguard [ks-on|ks-off]
#                            WireGuard (wg-quick). stdin: the .conf text.
#   connect-ikev2 [ks-on|ks-off]
#                            IKEv2 (strongSwan swanctl). stdin: line 1 =
#                            server host name, line 2 = username, line 3 =
#                            password, rest = the server's root CA (PEM).
#   disconnect               stop whichever tunnel is up (an armed kill
#                            switch keeps blocking internet until
#                            killswitch-off)
#   killswitch-on            block all traffic except the VPN tunnel
#   killswitch-off           remove the block
#   killswitch-restore       re-apply an armed kill switch (run at boot by
#                            emmavpn-killswitch.service, before the network)
#   monitor                  internal: runs as the emmavpn-tunnel service
#                            for WireGuard / IKEv2 and writes their status
#
# Secrets always arrive on stdin, never as arguments (visible in ps).
# Every connect first stops whatever tunnel (any protocol) is running.
#
# Status for the app (no root needed to read, no secrets inside):
#   /run/emmavpn/protocol       openvpn | wireguard | ikev2 while a tunnel is up
#   /run/emmavpn/openvpn.pid + openvpn.log   (OpenVPN)
#   /run/emmavpn/tunnel.status  (WireGuard / IKEv2, rewritten every 2 s):
#       protocol <p> / state connecting|up|stale|down / handshake <epoch>
#       rx <bytes> / tx <bytes> / updated <epoch>
#
# WireGuard: interface "emmavpn" from /run/emmavpn/wg/emmavpn.conf (0600,
# dir 0700). The config is rebuilt from an allow-list of keys — PreUp /
# PostUp / PreDown / PostDown (shell commands run as root), SaveConfig,
# Table, FwMark ... are dropped. DNS = is taken out and applied through
# emmavpn-dns (wg-quick would need resolvconf, missing on many systems).
#
# IKEv2: strongSwan through swanctl / vici (charon-systemd). The connection
# "emmavpn" + its EAP secret go to <swanctl>/conf.d/emmavpn.conf and the CA
# to <swanctl>/x509ca/emmavpn-ca.pem (both 0600) — under the swanctl
# directory because AppArmor (Ubuntu) only lets swanctl read files there.
# Policy-based IPsec has no tunnel interface; for systemd-resolved a dummy
# link "emmavpn" carrying the virtual IP holds the VPN DNS servers.
#
# Kill switch = nftables table "inet emmavpn_ks": outbound traffic is dropped
# unless it goes through the tunnel (tun* / emmavpn, or an IPsec policy),
# to loopback, to a VPN server endpoint (so it can reconnect: OpenVPN any
# port, WireGuard its UDP port, IKEv2 UDP 500/4500 + ESP), or is DHCP / DNS
# / IPv6 neighbour discovery (so the machine keeps its address and can
# resolve VPN server names).
# Its state lives in /var/lib/emmavpn so it survives a reboot.
#
# IPv6 block = nftables table "inet emmavpn_v6", present only while connected.
# The VPN servers are IPv4-only, so without it a dual-stack network keeps
# sending IPv6 traffic outside the tunnel and websites see the real IPv6
# address ("IP not changing"). IPv6 is rejected at once (not dropped) so
# browsers fall back to IPv4 through the tunnel without a delay. Traffic over
# the tunnel itself, loopback, link-local and ICMPv6 (neighbour discovery)
# stay allowed. Same idea as the Windows app turning IPv6 off on adapters.
#
# The tunnel runs as a background daemon: it keeps protecting the machine
# after the EmmaVPN window is closed, until the user presses the power
# button (disconnect). With systemd it runs as its own system service
# (emmavpn-tunnel): desktops put every app in a cgroup scope and a plain
# child process stays in the app's scope, so closing the app or logging out
# could stop the VPN with it. State lives in /run/emmavpn (world-readable pid + log
# so the app can show status without root; credentials stay root-only).
#
# SECURITY: this runs as root without a password prompt, so the config is
# never passed to OpenVPN as-is. Only an allow-list of plain networking
# options and the inline <ca>/<tls-auth>/... blocks are kept. Anything that
# can run commands, read or write files, or change OpenVPN's own behaviour
# (up/down scripts, plugin, log, cd, config, management, file paths, ...)
# is dropped.

set -u
PATH=/usr/sbin:/usr/bin:/sbin:/bin

RUN_DIR=/run/emmavpn
PID_FILE="$RUN_DIR/openvpn.pid"
LOG_FILE="$RUN_DIR/openvpn.log"
CONF_FILE="$RUN_DIR/emmavpn.ovpn"
AUTH_FILE="$RUN_DIR/auth"
STATE_DIR=/var/lib/emmavpn
KS_FLAG="$STATE_DIR/killswitch"       # exists (0644) while the kill switch is armed
ENDPOINTS_FILE="$STATE_DIR/endpoints"  # "v4|v6|port <value>" lines, last servers used
KS_TABLE=emmavpn_ks
SWITCH_FLAG="$RUN_DIR/switch_block"  # kill-switch rules held only for a server switch
V6_TABLE=emmavpn_v6
IKE_TABLE=emmavpn_ike                 # IKEv2 MSS clamp + leak guard (while connected)
TUNNEL_UNIT=emmavpn-tunnel
DNS_HOOK=/usr/lib/emmavpn/emmavpn-dns
PROTO_FILE="$RUN_DIR/protocol"         # active protocol (0644)
STATUS_FILE="$RUN_DIR/tunnel.status"   # WireGuard / IKEv2 status (0644)
MONITOR_PID="$RUN_DIR/monitor.pid"
TUN_IF=emmavpn                         # WireGuard interface / IKEv2 DNS dummy link
WG_DIR="$RUN_DIR/wg"
WG_CONF="$WG_DIR/$TUN_IF.conf"
WG_LOG="$RUN_DIR/wireguard.log"        # wg-quick output (no keys)
IKE_NAME=emmavpn
IKE_LOG="$RUN_DIR/ikev2.log"           # swanctl output (root only)
SELF="$(readlink -f "$0" 2>/dev/null || echo "$0")"

die() { echo "emmavpn-helper: $*" >&2; exit 1; }
warn() { echo "emmavpn-helper: warning: $*" >&2; }

[ "$(id -u)" -eq 0 ] || die "must run as root (via pkexec)"

OPENVPN="$(command -v openvpn || true)"

have_systemd() { [ -d /run/systemd/system ] && command -v systemd-run >/dev/null && command -v systemctl >/dev/null; }

stop_tunnel() {
    if have_systemd && systemctl list-units --all --plain --no-legend "$TUNNEL_UNIT.service" 2>/dev/null | grep -q .; then
        systemctl stop "$TUNNEL_UNIT.service" >/dev/null 2>&1 || true
        systemctl reset-failed "$TUNNEL_UNIT.service" >/dev/null 2>&1 || true
    fi
    if [ -f "$PID_FILE" ]; then
        pid="$(cat "$PID_FILE" 2>/dev/null || true)"
        if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null \
            && grep -q openvpn "/proc/$pid/comm" 2>/dev/null; then
            kill -TERM "$pid" 2>/dev/null || true
            for _ in $(seq 1 30); do
                kill -0 "$pid" 2>/dev/null || break
                sleep 0.2
            done
            kill -0 "$pid" 2>/dev/null && kill -KILL "$pid" 2>/dev/null || true
        fi
        rm -f "$PID_FILE"
    fi
    stop_monitor
    stop_wireguard
    stop_ikev2
    [ -x "$DNS_HOOK" ] && "$DNS_HOOK" cleanup >/dev/null 2>&1 || true
    v6_block_off
    rm -f "$AUTH_FILE" "$CONF_FILE" "$PROTO_FILE" "$STATUS_FILE" "$STATUS_FILE.tmp"
}

stop_monitor() {
    local pid
    if [ -f "$MONITOR_PID" ]; then
        pid="$(cat "$MONITOR_PID" 2>/dev/null || true)"
        if [ -n "$pid" ] && grep -qa emmavpn-helper "/proc/$pid/cmdline" 2>/dev/null; then
            kill -TERM "$pid" 2>/dev/null || true
        fi
        rm -f "$MONITOR_PID"
    fi
}

link_kind() { ip -d -o link show dev "$1" 2>/dev/null | grep -oE ' (wireguard|dummy) ' | head -1 | tr -d ' '; }

stop_wireguard() {
    if [ -d "/sys/class/net/$TUN_IF" ] && [ "$(link_kind "$TUN_IF")" = wireguard ]; then
        if [ -f "$WG_CONF" ] && command -v wg-quick >/dev/null; then
            # Also removes wg-quick's routing rules and its nftables table.
            wg-quick down "$WG_CONF" >>"$WG_LOG" 2>&1                 || ip link delete dev "$TUN_IF" 2>/dev/null || true
        else
            ip link delete dev "$TUN_IF" 2>/dev/null || true
        fi
    fi
    rm -rf "$WG_DIR"
}

swanctl_dir() {
    local d
    # Debian / Ubuntu / Arch: /etc/swanctl. Fedora / RHEL: /etc/strongswan/swanctl.
    for d in /etc/swanctl /etc/strongswan/swanctl; do
        [ -d "$d" ] && { echo "$d"; return 0; }
    done
    return 1
}

# IKEv2 (policy-based, no tunnel interface) needs two things while it is up:
#  - MSS clamp: ESP / NAT-T adds ~70 bytes but TCP still announces an MSS for
#    a 1500-byte link, so the server's full-size segments come back too big
#    and are dropped (pages hang after the TLS hello). Windows does the same.
#  - Leak guard: the kernel only encrypts packets FROM the virtual IP. Anything
#    sent from the computer's own address (WebRTC binds every local address)
#    would leave unencrypted and show the real IP. Allow only what will be
#    encrypted, IKE/ESP to the server, DHCP and the local network; DNS only
#    when the DNS lock redirected it (emmavpn-dns then gives it the virtual
#    IP as source, so it is encrypted too).
ike_guard_on() {
    command -v nft >/dev/null || return 0
    local ike=""
    [ -f "$ENDPOINTS_FILE" ] && ike="$(awk '$1=="ike4"{print $2}' "$ENDPOINTS_FILE" | paste -sd, -)"
    nft delete table inet "$IKE_TABLE" 2>/dev/null || true
    local guard=yes
    # Needs nftables / kernel support for "rt ipsec"; without it the guard
    # would block the tunnel itself, so keep only the MSS clamp then.
    printf 'table inet emmavpn_probe {\n chain c {\n  type filter hook output priority 0; policy accept;\n  rt ipsec exists accept\n }\n}\n' \
        | nft -c -f - >/dev/null 2>&1 || guard=no
    {
        echo "table inet $IKE_TABLE {"
        echo "  chain mss {"
        echo "    type filter hook output priority mangle; policy accept;"
        echo "    meta nfproto ipv4 tcp flags syn / syn,rst tcp option maxseg size set 1300"
        echo "  }"
        if [ "$guard" = yes ]; then
            echo "  chain guard {"
            echo "    type filter hook output priority filter; policy accept;"
            echo "    meta nfproto != ipv4 accept"
            echo "    oifname \"lo\" accept"
            echo "    rt ipsec exists accept"
            echo "    ct status dnat meta l4proto { udp, tcp } th dport 53 accept"
            if [ -n "$ike" ]; then
                echo "    ip daddr { $ike } udp dport { 500, 4500 } accept"
                echo "    ip daddr { $ike } meta l4proto esp accept"
            fi
            echo "    udp dport { 67, 68 } accept"
            echo "    meta l4proto { udp, tcp } th dport { 53, 853 } reject"
            echo "    ip daddr { 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 169.254.0.0/16, 100.64.0.0/10, 224.0.0.0/4, 255.255.255.255 } accept"
            echo "    meta l4proto tcp reject with tcp reset"
            echo "    reject"
            echo "  }"
        fi
        echo "}"
    } | nft -f - 2>/dev/null || warn "could not apply the IKEv2 leak guard"
    [ "$guard" = yes ] || warn "nftables has no 'rt ipsec' support; IKEv2 leak guard not applied"
}

stop_ikev2() {
    local sw
    nft delete table inet "$IKE_TABLE" 2>/dev/null || true
    sw="$(swanctl_dir || true)"
    if [ -n "$sw" ] && [ -f "$sw/conf.d/$IKE_NAME.conf" ]; then
        if command -v swanctl >/dev/null; then
            swanctl --terminate --ike "$IKE_NAME" --timeout 5 >/dev/null 2>&1 || true
        fi
        rm -f "$sw/conf.d/$IKE_NAME.conf" "$sw/x509ca/$IKE_NAME-ca.pem"
        # Re-load from the files: our connection, CA and EAP secret are no
        # longer there, so swanctl unloads them (other connections stay).
        if command -v swanctl >/dev/null; then
            swanctl --load-all --noprompt >/dev/null 2>&1 || true
        fi
    fi
    if [ -d "/sys/class/net/$TUN_IF" ] && [ "$(link_kind "$TUN_IF")" = dummy ]; then
        ip link delete dev "$TUN_IF" 2>/dev/null || true
    fi
}

v6_block_on() {
    command -v nft >/dev/null || return 0
    nft delete table inet "$V6_TABLE" 2>/dev/null || true
    {
        echo "table inet $V6_TABLE {"
        echo "  chain output {"
        echo "    type filter hook output priority filter; policy accept;"
        echo "    meta nfproto ipv6 oifname \"lo\" accept"
        echo "    meta nfproto ipv6 oifname \"tun*\" accept"
        echo "    meta nfproto ipv6 oifname \"$TUN_IF\" accept"
        echo "    meta l4proto ipv6-icmp accept"
        echo "    ip6 daddr { fe80::/10, ff00::/8 } accept"
        echo "    meta nfproto ipv6 meta l4proto tcp reject with tcp reset"
        echo "    meta nfproto ipv6 reject with icmpv6 type admin-prohibited"
        echo "  }"
        echo "}"
    } | nft -f - 2>/dev/null || echo "emmavpn-helper: warning: could not block IPv6" >&2
}

v6_block_off() {
    command -v nft >/dev/null || return 0
    nft delete table inet "$V6_TABLE" 2>/dev/null || true
}

# Keep only safe directives. Inline blocks are copied verbatim.
sanitize_config() {
    awk '
    BEGIN {
        n = split("client dev dev-type proto remote remote-random resolv-retry nobind " \
                  "persist-key persist-tun tun-mtu mssfix fragment ping ping-restart ping-exit keepalive " \
                  "reneg-sec remote-cert-tls verify-x509-name ns-cert-type cipher data-ciphers " \
                  "data-ciphers-fallback ncp-ciphers auth key-direction tls-client tls-version-min " \
                  "tls-cipher tls-ciphersuites comp-lzo compress allow-compression float " \
                  "explicit-exit-notify connect-retry connect-retry-max connect-timeout " \
                  "server-poll-timeout hand-window sndbuf rcvbuf auth-nocache pull " \
                  "redirect-gateway route route-ipv6 route-delay dhcp-option block-ipv6 " \
                  "mute mute-replay-warnings verb topology", ok, " ");
        for (i = 1; i <= n; i++) allow[ok[i]] = 1;
        nb = split("ca cert key tls-auth tls-crypt tls-crypt-v2 extra-certs", bl, " ");
        for (i = 1; i <= nb; i++) blocks[bl[i]] = 1;
        inblock = "";
    }
    {
        sub(/\r$/, "");
        line = $0;
        if (inblock != "") {
            print line;
            if (line ~ "^[ \t]*</" inblock ">[ \t]*$") inblock = "";
            next;
        }
        t = line; sub(/^[ \t]+/, "", t);
        if (t == "" || t ~ /^[#;]/) next;
        if (match(t, /^<[a-z0-9-]+>$/)) {
            tag = substr(t, 2, length(t) - 2);
            if (tag in blocks) { inblock = tag; print t; }
            else { skipping = tag; }
            next;
        }
        if (skipping != "") {
            if (t == "</" skipping ">") skipping = "";
            next;
        }
        split(t, w, /[ \t]+/);
        key = tolower(w[1]);
        if (!(key in allow)) next;
        # No file paths anywhere: options may only carry plain values.
        if (t ~ /\//) {
            if (key != "route" && key != "route-ipv6" && key != "dhcp-option") next;
        }
        print t;
    }'
}

# ── Kill switch ─────────────────────────────────────────────────────────

# Remember the servers of this config so the kill switch lets reconnects out.
save_endpoints() {
    local clean="$1" host port ip
    install -d -m 0755 -o root -g root "$STATE_DIR"
    : > "$ENDPOINTS_FILE.new"
    while read -r _ host port _; do
        [ -n "$host" ] || continue
        echo "port ${port:-1194}" >> "$ENDPOINTS_FILE.new"
        for ip in $(getent ahostsv4 "$host" 2>/dev/null | awk '{print $1}' | sort -u); do
            echo "v4 $ip" >> "$ENDPOINTS_FILE.new"
        done
        for ip in $(getent ahostsv6 "$host" 2>/dev/null | awk '{print $1}' | grep ':' | sort -u); do
            echo "v6 $ip" >> "$ENDPOINTS_FILE.new"
        done
        # A literal IP address in the config.
        if [[ "$host" =~ ^[0-9.]+$ ]]; then echo "v4 $host" >> "$ENDPOINTS_FILE.new"; fi
    done < <(grep '^remote ' <<< "$clean")
    sort -u "$ENDPOINTS_FILE.new" > "$ENDPOINTS_FILE"
    rm -f "$ENDPOINTS_FILE.new"
    chmod 0644 "$ENDPOINTS_FILE"
}

# Replace server host names with their IPv4 addresses (looked up now, while
# normal DNS works). After a network drop OpenVPN keeps the tunnel and the
# VPN's DNS in place while it reconnects, so looking the name up again would
# go through the dead tunnel, hang forever, and leave the machine offline.
pin_remotes() {
    local line host rest ips ip
    while IFS= read -r line; do
        if [[ "$line" =~ ^remote[[:space:]]+([^[:space:]]+)(.*)$ ]]; then
            host="${BASH_REMATCH[1]}"; rest="${BASH_REMATCH[2]}"
            if [[ ! "$host" =~ ^[0-9.]+$ && ! "$host" =~ : ]]; then
                ips="$(getent ahostsv4 "$host" 2>/dev/null | awk '{print $1}' | awk '!seen[$0]++' | head -4)"
                if [ -n "$ips" ]; then
                    for ip in $ips; do printf 'remote %s%s\n' "$ip" "$rest"; done
                    continue
                fi
            fi
        fi
        printf '%s\n' "$line"
    done
}

# Endpoint lines (all written by this helper):
#   v4|v6 <ip>              OpenVPN server: any traffic to it
#   wg4|wg6 <ip> <port>     WireGuard endpoint: UDP to that port only
#   ike4 <ip>               IKEv2 server: UDP 500 / 4500 and ESP only
#   port <n>                (OpenVPN, informational)
ks_rules() {
    local with_ipsec="$1" v4="" v6="" ike4=""
    if [ -f "$ENDPOINTS_FILE" ]; then
        v4="$(awk '$1=="v4"{print $2}' "$ENDPOINTS_FILE" | paste -sd, -)"
        v6="$(awk '$1=="v6"{print $2}' "$ENDPOINTS_FILE" | paste -sd, -)"
        ike4="$(awk '$1=="ike4"{print $2}' "$ENDPOINTS_FILE" | paste -sd, -)"
    fi
    echo "table inet $KS_TABLE {"
    echo "  chain output {"
    echo "    type filter hook output priority filter; policy drop;"
    echo "    oifname \"lo\" accept"
    echo "    oifname \"tun*\" accept"
    echo "    oifname \"$TUN_IF\" accept"
    # IKEv2 is policy-based (no tunnel interface): let through what the
    # kernel is about to encrypt; the ESP result is allowed below.
    [ "$with_ipsec" = yes ] && [ -n "$ike4" ] && echo "    rt ipsec exists accept"
    echo "    meta l4proto ipv6-icmp accept"
    echo "    udp dport { 67, 68, 546, 547 } accept"
    echo "    meta l4proto { tcp, udp } th dport 53 accept"
    [ -n "$v4" ] && echo "    ip daddr { $v4 } accept"
    [ -n "$v6" ] && echo "    ip6 daddr { $v6 } accept"
    if [ -f "$ENDPOINTS_FILE" ]; then
        awk '$1=="wg4" && $3 ~ /^[0-9]+$/ {print "    ip daddr " $2 " udp dport " $3 " accept"}
             $1=="wg6" && $3 ~ /^[0-9]+$/ {print "    ip6 daddr " $2 " udp dport " $3 " accept"}' "$ENDPOINTS_FILE"
    fi
    if [ -n "$ike4" ]; then
        echo "    ip daddr { $ike4 } udp dport { 500, 4500 } accept"
        echo "    ip daddr { $ike4 } meta l4proto 50 accept"
    fi
    echo "  }"
    echo "}"
}

ks_apply() {
    command -v nft >/dev/null || die "nftables is not installed (sudo apt install nftables)"
    nft delete table inet "$KS_TABLE" 2>/dev/null || true
    if ! ks_rules yes | nft -f - 2>/dev/null; then
        # Old nftables / kernel without "rt ipsec": keep blocking, IKEv2
        # traffic will not get through the kill switch.
        nft delete table inet "$KS_TABLE" 2>/dev/null || true
        ks_rules no | nft -f - || die "could not apply kill switch rules"
        warn "nftables has no 'rt ipsec' support; IKEv2 is blocked while the kill switch is on"
    fi
}

ks_mode_apply() {
    case "$1" in
        ks-on)  ks_on ;;
        ks-off) ks_off_unless_switching ;;
        *)      [ -f "$KS_FLAG" ] && ks_apply ;;
    esac
    return 0
}

# stdin: endpoint lines (format above). Replaces the saved endpoints.
write_endpoints() {
    install -d -m 0755 -o root -g root "$STATE_DIR"
    sort -u > "$ENDPOINTS_FILE.new"
    mv -f "$ENDPOINTS_FILE.new" "$ENDPOINTS_FILE"
    chmod 0644 "$ENDPOINTS_FILE"
}

# IPv4 addresses for a host name (or the literal address), at most 4.
resolve_v4() {
    if [[ "$1" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then echo "$1"; return 0; fi
    getent ahostsv4 "$1" 2>/dev/null | awk '{print $1}' | awk '!seen[$0]++' | head -4
}

valid_ip() { [[ "$1" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ || "$1" =~ ^[0-9A-Fa-f:]+$ ]]; }

use_resolved() {
    command -v resolvectl >/dev/null 2>&1 && systemctl is-active --quiet systemd-resolved 2>/dev/null
}

set_protocol() {
    install -d -m 0755 -o root -g root "$RUN_DIR"
    printf '%s\n' "$1" > "$PROTO_FILE"
    chmod 0644 "$PROTO_FILE"
}

# Status file for the app (atomic replace, world-readable, no secrets).
write_status() {   # <protocol> <state> [handshake] [rx] [tx]
    local tmp="$STATUS_FILE.tmp"
    {
        echo "protocol $1"
        echo "state $2"
        echo "handshake ${3:-0}"
        echo "rx ${4:-0}"
        echo "tx ${5:-0}"
        echo "updated $(date +%s)"
    } > "$tmp" && chmod 0644 "$tmp" && mv -f "$tmp" "$STATUS_FILE"
}

# Background monitor for WireGuard / IKEv2 (OpenVPN has its own daemon + log).
start_monitor() {
    if have_systemd; then
        systemctl reset-failed "$TUNNEL_UNIT.service" >/dev/null 2>&1 || true
        systemd-run --quiet --collect --unit="$TUNNEL_UNIT"             --description="EmmaVPN tunnel monitor"             -p Type=simple "$SELF" monitor             || warn "could not start the status monitor"
    else
        setsid "$SELF" monitor </dev/null >/dev/null 2>&1 &
    fi
}

ks_on() {
    install -d -m 0755 -o root -g root "$STATE_DIR"
    ks_apply
    date -u +%FT%TZ > "$KS_FLAG"
    chmod 0644 "$KS_FLAG"
}

ks_off() {
    nft delete table inet "$KS_TABLE" 2>/dev/null || true
    rm -f "$KS_FLAG" "$SWITCH_FLAG"
}

# -- Switch block --------------------------------------------------------------
# A connect that replaces a live tunnel while the kill switch is off (server
# change, rotation, multi-hop) takes the old tunnel down before the new one
# is up; without a block the real IP shows for those seconds. The kill
# switch rules are held for that window only and released as soon as the new
# tunnel is up (WireGuard / IKEv2 right after DNS is set, OpenVPN from its
# route-up hook), or after 60 s at the latest.
switch_block_begin() {
    [ -f "$KS_FLAG" ] && return 0          # an armed kill switch already blocks
    [ -f "$PROTO_FILE" ] || return 0       # nothing connected: a plain connect
    command -v nft >/dev/null || return 0
    install -d -m 0755 -o root -g root "$RUN_DIR"
    ks_apply || return 0
    local stamp; stamp="$(date +%s%N)"
    echo "$stamp" > "$SWITCH_FLAG"
    if have_systemd; then
        systemd-run --quiet --collect --on-active=60 \
            --unit="emmavpn-switch-release-${stamp: -9}" \
            "$SELF" switch-release "$stamp" >/dev/null 2>&1 || true
    else
        ( sleep 60; "$SELF" switch-release "$stamp" ) >/dev/null 2>&1 &
    fi
}

# Release the switch block (if any). With a stamp, only that switch's block
# (a late safety timer must not cut a newer switch short).
switch_release() {
    [ -f "$SWITCH_FLAG" ] || return 0
    if [ -n "${1:-}" ] && [ "$(cat "$SWITCH_FLAG" 2>/dev/null)" != "$1" ]; then
        return 0
    fi
    rm -f "$SWITCH_FLAG"
    [ -f "$KS_FLAG" ] || nft delete table inet "$KS_TABLE" 2>/dev/null || true
}

# ks-off while a switch block is held: keep blocking (with the new server's
# endpoints allowed) until the new tunnel is up.
ks_off_unless_switching() {
    if [ -f "$SWITCH_FLAG" ]; then
        rm -f "$KS_FLAG"
        ks_apply
    else
        ks_off
    fi
}

do_connect() {
    local ks_mode="${1:-ks-keep}"

    [ -n "$OPENVPN" ] || die "openvpn is not installed (sudo apt install openvpn)"

    IFS= read -r user || die "missing username"
    IFS= read -r pass || die "missing password"
    raw="$(cat)"
    [ -n "$raw" ] || die "empty config"

    [ "$ks_mode" = ks-off ] && switch_block_begin
    stop_tunnel
    install -d -m 0755 -o root -g root "$RUN_DIR"

    umask 077
    printf '%s\n%s\n' "$user" "$pass" > "$AUTH_FILE"
    clean="$(printf '%s\n' "$raw" | sanitize_config)"
    grep -q '^remote ' <<< "$clean" || die "config has no server"

    # Let this server through an armed kill switch before connecting.
    save_endpoints "$clean"
    clean="$(printf '%s\n' "$clean" | pin_remotes)"
    case "$ks_mode" in
        ks-on)  ks_on ;;
        ks-off) ks_off_unless_switching ;;
        *)      [ -f "$KS_FLAG" ] && ks_apply ;;
    esac

    {
        printf '%s\n' "$clean"
        echo "auth-user-pass $AUTH_FILE"
        grep -q '^persist-tun' <<< "$clean" || echo "persist-tun"
        grep -q '^persist-key' <<< "$clean" || echo "persist-key"
        if ! grep -q '^redirect-gateway' <<< "$clean" && ! grep -q '^pull' <<< "$clean"; then
            echo "redirect-gateway def1 bypass-dhcp"
        fi
        # A server address that doesn't answer the handshake: move on to the
        # next one after 10 s instead of hanging (OpenVPN 2.5 waits ~60 s).
        echo "server-poll-timeout 10"
        # A handshake that stalls after the server answered: retry after 15 s
        # instead of OpenVPN's 60 s (seen with OpenVPN 2.5, e.g. Ubuntu 22.04).
        echo "hand-window 15"
        # Servers push the Windows-only "block-outside-dns"; OpenVPN on Linux
        # rejects it as an options error, so drop it on arrival.
        echo 'pull-filter ignore "block-outside-dns"'
        # Resolve DNS through the tunnel if the server does not push servers.
        grep -q '^dhcp-option DNS' <<< "$clean" || { echo "dhcp-option DNS 1.1.1.1"; echo "dhcp-option DNS 1.0.0.1"; }
    } > "$CONF_FILE"

    # Point system DNS at the VPN while connected (no leaks). Our own hook,
    # so it behaves the same on every distribution (Ubuntu, Fedora, Arch,
    # openSUSE, ...), with or without systemd-resolved.
    dns_args=(--script-security 2 --up "$DNS_HOOK" --down "$DNS_HOOK" --down-pre
              --route-up "$SELF switch-release")

    umask 022
    : > "$LOG_FILE"
    chmod 0644 "$LOG_FILE"

    ovpn_args=(--config "$CONF_FILE" --daemon emmavpn --writepid "$PID_FILE"
               --log "$LOG_FILE" --connect-retry 3 "${dns_args[@]}")
    if have_systemd; then
        # Own service, outside the app's cgroup: survives closing the app,
        # logging out, and the desktop cleaning up the app's scope.
        systemctl reset-failed "$TUNNEL_UNIT.service" >/dev/null 2>&1 || true
        systemd-run --quiet --collect --unit="$TUNNEL_UNIT" \
            --description="EmmaVPN tunnel" \
            -p Type=forking -p PIDFile="$PID_FILE" -p KillMode=mixed \
            "$OPENVPN" "${ovpn_args[@]}" \
            || die "openvpn failed to start (see $LOG_FILE)"
    else
        "$OPENVPN" "${ovpn_args[@]}" || die "openvpn failed to start (see $LOG_FILE)"
    fi

    chmod 0644 "$PID_FILE" 2>/dev/null || true
    set_protocol openvpn
    v6_block_on
    echo "started"
}

# -- WireGuard --------------------------------------------------------------

# Rebuild a WireGuard config from an allow-list (stdin -> stdout). Anything
# wg-quick would run as a command (PreUp/PostUp/PreDown/PostDown) and every
# other key is dropped; values may only hold key / address characters.
# DNS servers go to the WG_DNS array instead of the config. Every [Peer]
# gets PersistentKeepalive = 25 unless it has one (keeps NAT mappings open,
# and makes the first handshake happen right away when the link comes up).
# Must run in the current shell (redirect, no pipe) so WG_DNS survives.
WG_DNS=()
sanitize_wg() {
    local line t key val section="" ka=1 d
    local re='^[][A-Za-z0-9+/=.:,_ -]+$'
    WG_DNS=()
    while IFS= read -r line || [ -n "$line" ]; do
        line="${line%$'\r'}"
        t="${line%%#*}"
        t="${t#"${t%%[![:space:]]*}"}"
        t="${t%"${t##*[![:space:]]}"}"
        [ -n "$t" ] || continue
        if [[ "$t" =~ ^\[([A-Za-z]+)\]$ ]]; then
            [ "$section" = peer ] && [ "$ka" -eq 0 ] && echo "PersistentKeepalive = 25"
            section="${BASH_REMATCH[1],,}"
            case "$section" in
                interface) echo "[Interface]" ;;
                peer)      echo; echo "[Peer]"; ka=0 ;;
                *)         section=skip ;;
            esac
            continue
        fi
        [[ "$t" =~ ^([A-Za-z]+)[[:space:]]*=[[:space:]]*(.*)$ ]] || continue
        key="${BASH_REMATCH[1],,}"
        val="${BASH_REMATCH[2]}"
        [[ "$val" =~ $re ]] || continue
        case "$section:$key" in
            interface:privatekey)   echo "PrivateKey = $val" ;;
            interface:address)      echo "Address = $val" ;;
            interface:mtu)          [[ "$val" =~ ^[0-9]{3,5}$ ]] && echo "MTU = $val" ;;
            interface:listenport)   [[ "$val" =~ ^[0-9]{1,5}$ ]] && echo "ListenPort = $val" ;;
            interface:dns)
                for d in ${val//,/ }; do valid_ip "$d" && WG_DNS+=("$d"); done ;;
            peer:publickey)         echo "PublicKey = $val" ;;
            peer:presharedkey)      echo "PresharedKey = $val" ;;
            peer:allowedips)        echo "AllowedIPs = $val" ;;
            peer:endpoint)          echo "Endpoint = $val" ;;
            peer:persistentkeepalive)
                [[ "$val" =~ ^[0-9]{1,5}$ ]] && { echo "PersistentKeepalive = $val"; ka=1; } ;;
        esac
    done
    [ "$section" = peer ] && [ "$ka" -eq 0 ] && echo "PersistentKeepalive = 25"
    return 0
}

# Pin "Endpoint = host:port" to an IP address (looked up now, while normal
# DNS works) and record it for the kill switch. stdin -> stdout; endpoint
# lines for write_endpoints go to the file named in $1.
pin_wg_endpoints() {
    local out="$1" line host port ip
    : > "$out"
    while IFS= read -r line; do
        if [[ "$line" =~ ^Endpoint\ =\ \[([0-9A-Fa-f:]+)\]:([0-9]+)$ ]]; then
            echo "wg6 ${BASH_REMATCH[1]} ${BASH_REMATCH[2]}" >> "$out"
        elif [[ "$line" =~ ^Endpoint\ =\ ([A-Za-z0-9.-]+):([0-9]+)$ ]]; then
            host="${BASH_REMATCH[1]}"; port="${BASH_REMATCH[2]}"
            ip="$(resolve_v4 "$host" | head -1)"
            [ -n "$ip" ] || die "cannot resolve the WireGuard server $host"
            echo "wg4 $ip $port" >> "$out"
            line="Endpoint = $ip:$port"
        else
            [[ "$line" =~ ^Endpoint ]] && die "unsupported WireGuard endpoint"
        fi
        printf '%s\n' "$line"
    done
}

do_connect_wireguard() {
    local ks_mode="${1:-ks-keep}" raw clean_tmp eps_tmp
    command -v wg-quick >/dev/null && command -v wg >/dev/null \
        || die "WireGuard is not installed (Ubuntu/Debian: sudo apt install wireguard-tools; Fedora: sudo dnf install wireguard-tools; Arch: sudo pacman -S wireguard-tools)"
    command -v ip >/dev/null || die "iproute2 (ip) is not installed"

    raw="$(cat)"
    [ -n "$raw" ] || die "empty config"

    [ "$ks_mode" = ks-off ] && switch_block_begin
    stop_tunnel
    install -d -m 0755 -o root -g root "$RUN_DIR"
    install -d -m 0700 -o root -g root "$WG_DIR"
    umask 077
    clean_tmp="$WG_DIR/clean.tmp"
    eps_tmp="$WG_DIR/endpoints.tmp"
    trap 'rm -f "$WG_DIR/clean.tmp" "$WG_DIR/endpoints.tmp"' EXIT
    # Process substitution = pipe (a here-string may go through a temp file).
    sanitize_wg < <(printf '%s\n' "$raw") > "$clean_tmp"
    raw=""
    grep -q '^PrivateKey = ' "$clean_tmp" || { rm -f "$clean_tmp"; die "WireGuard config has no private key"; }
    grep -q '^PublicKey = ' "$clean_tmp" || { rm -f "$clean_tmp"; die "WireGuard config has no peer"; }
    grep -q '^Endpoint = ' "$clean_tmp" || { rm -f "$clean_tmp"; die "WireGuard config has no server"; }
    grep -q '^Address = ' "$clean_tmp" || { rm -f "$clean_tmp"; die "WireGuard config has no address"; }
    pin_wg_endpoints "$eps_tmp" < "$clean_tmp" > "$WG_CONF" || { rm -f "$clean_tmp" "$eps_tmp" "$WG_CONF"; exit 1; }
    rm -f "$clean_tmp"
    chmod 0600 "$WG_CONF"

    # Let this server through an armed kill switch before connecting.
    write_endpoints < "$eps_tmp"
    rm -f "$eps_tmp"
    ks_mode_apply "$ks_mode"

    set_protocol wireguard
    umask 022
    write_status wireguard connecting
    : > "$WG_LOG"; chmod 0644 "$WG_LOG"
    if ! wg-quick up "$WG_CONF" >>"$WG_LOG" 2>&1; then
        # wg-quick prints the commands it runs, never the keys.
        tail -n 3 "$WG_LOG" >&2
        stop_tunnel
        die "wg-quick failed to start the tunnel"
    fi

    # VPN DNS on the tunnel link (resolved) or in /etc/resolv.conf.
    "$DNS_HOOK" set "$TUN_IF" "${WG_DNS[@]}" >/dev/null 2>&1 || warn "could not set DNS"
    v6_block_on
    switch_release
    start_monitor
    echo "started"
}

wg_monitor_tick() {
    local hs rx tx now state
    [ -d "/sys/class/net/$TUN_IF" ] || { write_status wireguard down; return 1; }
    hs="$(wg show "$TUN_IF" latest-handshakes 2>/dev/null \
          | awk '{ if ($2 + 0 > m) m = $2 + 0 } END { printf "%.0f", m + 0 }')"
    read -r rx tx < <(wg show "$TUN_IF" transfer 2>/dev/null \
          | awk '{ r += $2; t += $3 } END { printf "%.0f %.0f\n", r + 0, t + 0 }')
    now="$(date +%s)"
    if [ "${hs:-0}" -eq 0 ]; then
        state=connecting
    elif [ $(( now - hs )) -gt 210 ]; then
        # No handshake for > 3.5 min although keepalives run every 25 s:
        # the server is not answering (WireGuard keeps retrying).
        state=stale
    else
        state=up
    fi
    write_status wireguard "$state" "${hs:-0}" "${rx:-0}" "${tx:-0}"
    return 0
}

# -- IKEv2 (strongSwan swanctl) ---------------------------------------------

# charon must be running with the vici socket (charon-systemd unit is
# "strongswan.service"; older Debian/Ubuntu call it strongswan-swanctl).
ensure_charon() {
    local u
    swanctl --stats >/dev/null 2>&1 && return 0
    if have_systemd; then
        for u in strongswan.service strongswan-swanctl.service; do
            systemctl start "$u" >/dev/null 2>&1 || continue
            for _ in $(seq 1 25); do
                swanctl --stats >/dev/null 2>&1 && return 0
                sleep 0.2
            done
        done
    fi
    return 1
}

# Virtual IP charon got from the server (route in its table 220).
ike_vip() {
    ip -4 route show table 220 2>/dev/null \
        | sed -n 's/.* src \([0-9][0-9.]*\).*/\1/p' | head -1
}

# DNS servers the IKEv2 server pushed (INTERNAL_IP4_DNS). charon logs them
# ("installing DNS server X") even when its own resolve plugin can't apply
# them. Empty -> emmavpn-dns falls back to 1.1.1.1 / 1.0.0.1 via the tunnel.
ike_pushed_dns() {
    sed -n 's/.*installing DNS server \([0-9][0-9.]*\).*/\1/p' "$IKE_LOG" 2>/dev/null \
        | awk '!seen[$0]++' \
        | while read -r d; do valid_ip "$d" && echo "$d"; done | head -3
}

# systemd-resolved needs a link with a routable address to hold the VPN DNS
# servers; policy-based IPsec has none, so use a dummy link with the VIP.
ike_dns_link() {
    local vip="$1"
    use_resolved || return 0
    [ -n "$vip" ] || return 1
    if [ ! -d "/sys/class/net/$TUN_IF" ]; then
        ip link add "$TUN_IF" type dummy 2>/dev/null || { warn "could not create the DNS link"; return 1; }
    fi
    [ "$(link_kind "$TUN_IF")" = dummy ] || return 1
    ip link set dev "$TUN_IF" up 2>/dev/null || true
    ip -4 addr flush dev "$TUN_IF" 2>/dev/null || true
    ip -4 addr add "$vip/32" dev "$TUN_IF" 2>/dev/null || true
    # shellcheck disable=SC2046  # one IP per word
    "$DNS_HOOK" set "$TUN_IF" $(ike_pushed_dns) >/dev/null 2>&1 || warn "could not set DNS"
}

# strongSwan string value: plain identity characters only.
valid_ident() { [[ "$1" =~ ^[A-Za-z0-9@._+=:/-]{1,255}$ ]]; }

do_connect_ikev2() {
    local ks_mode="${1:-ks-keep}" server user pass ca sw ips ip rc d
    command -v swanctl >/dev/null \
        || die "strongSwan is not installed (Ubuntu/Debian: sudo apt install strongswan-swanctl charon-systemd libcharon-extra-plugins; Fedora: sudo dnf install strongswan; Arch: sudo pacman -S strongswan)"
    command -v base64 >/dev/null || die "base64 (coreutils) is missing"

    IFS= read -r server || die "missing server"
    IFS= read -r user || die "missing username"
    IFS= read -r pass || die "missing password"
    ca="$(cat | tr -d '\r')"
    server="${server%$'\r'}"; user="${user%$'\r'}"; pass="${pass%$'\r'}"
    [[ "$server" =~ ^[A-Za-z0-9]([A-Za-z0-9.-]{0,252})$ ]] || die "bad server name"
    valid_ident "$user" || die "unsupported characters in the username"
    [ -n "$pass" ] || die "missing password"
    # Keep only the PEM certificate block(s).
    ca="$(printf '%s\n' "$ca" | awk '/-----BEGIN CERTIFICATE-----/{p=1} p{print} /-----END CERTIFICATE-----/{p=0}')"
    [ -n "$ca" ] || die "IKEv2 needs the server's root CA certificate (PEM)"
    if command -v openssl >/dev/null; then
        printf '%s\n' "$ca" | openssl x509 -noout 2>/dev/null || die "the IKEv2 CA certificate is not valid"
    fi

    sw="$(swanctl_dir)" || die "strongSwan swanctl directory not found (is strongswan-swanctl installed?)"

    [ "$ks_mode" = ks-off ] && switch_block_begin
    stop_tunnel
    install -d -m 0755 -o root -g root "$RUN_DIR"

    # Pin the server to IP addresses now (normal DNS still works), so a
    # reconnect never has to resolve through the dead tunnel, and let them
    # through an armed kill switch.
    ips="$(resolve_v4 "$server")"
    [ -n "$ips" ] || die "cannot resolve the IKEv2 server $server"
    for ip in $ips; do echo "ike4 $ip"; done | write_endpoints
    ks_mode_apply "$ks_mode"

    umask 077
    for d in "$sw/conf.d" "$sw/x509ca"; do
        [ -d "$d" ] || install -d -m 0750 -o root -g root "$d"
    done
    printf '%s\n' "$ca" > "$sw/x509ca/$IKE_NAME-ca.pem"
    chmod 0600 "$sw/x509ca/$IKE_NAME-ca.pem"
    # Identities are quoted (validated above); the secret is base64 ("0s"
    # prefix) so no character in it can break the file.
    {
        echo "# Written by EmmaVPN while connected. Removed on disconnect."
        echo "connections {"
        echo "  $IKE_NAME {"
        echo "    version = 2"
        echo "    remote_addrs = $(echo "$ips" | paste -sd, -)"
        echo "    vips = 0.0.0.0"
        echo "    encap = no"
        echo "    mobike = yes"
        echo "    fragmentation = yes"
        echo "    send_certreq = yes"
        echo "    dpd_delay = 30s"
        echo "    keyingtries = 0"
        echo "    unique = replace"
        # No trailing "default": in strongSwan 6 it adds dozens of algorithms
    # (incl. post-quantum key exchanges), pushing IKE_SA_INIT past 1500
    # bytes. That first message cannot use IKE fragmentation, so it goes out
    # as IP fragments, which NATs and many routers drop (no reply at all).
    echo "    proposals = aes256-sha256-modp2048,aes256gcm16-prfsha384-ecp384,aes256-sha256-ecp256,aes256-sha1-modp2048,aes256-sha256-modp1024,aes256-sha1-modp1024"
        echo "    local {"
        echo "      auth = eap-mschapv2"
        echo "      eap_id = \"$user\""
        echo "    }"
        echo "    remote {"
        echo "      auth = pubkey"
        echo "      id = \"$server\""
        echo "      cacerts = $IKE_NAME-ca.pem"
        echo "    }"
        echo "    children {"
        echo "      $IKE_NAME {"
        echo "        remote_ts = 0.0.0.0/0"
        echo "        esp_proposals = aes256gcm16,aes256-sha256,aes256-sha1,default"
        echo "        dpd_action = restart"
        echo "        start_action = none"
        echo "      }"
        echo "    }"
        echo "  }"
        echo "}"
        echo "secrets {"
        echo "  eap-$IKE_NAME {"
        echo "    id = \"$user\""
        echo "    secret = 0s$(printf '%s' "$pass" | base64 -w0)"
        echo "  }"
        echo "}"
    } > "$sw/conf.d/$IKE_NAME.conf"
    chmod 0600 "$sw/conf.d/$IKE_NAME.conf"
    pass=""

    set_protocol ikev2
    umask 022
    write_status ikev2 connecting
    umask 077
    : > "$IKE_LOG"
    if ! ensure_charon; then
        stop_tunnel
        die "the strongSwan daemon (charon-systemd) is not running (Ubuntu/Debian: sudo apt install charon-systemd)"
    fi
    if ! swanctl --stats 2>/dev/null | grep -qw 'eap-mschapv2'; then
        stop_tunnel
        die "strongSwan has no EAP-MSCHAPv2 plugin (Ubuntu/Debian: sudo apt install libcharon-extra-plugins libstrongswan-extra-plugins, then sudo systemctl restart strongswan)"
    fi
    # Loads every swanctl file (other connections of the user stay as they
    # are). A failure in someone else's file must not stop us, so check
    # that our connection made it in.
    swanctl --load-all --noprompt >>"$IKE_LOG" 2>&1 || true
    if ! swanctl --list-conns 2>/dev/null | grep -q "^$IKE_NAME:"; then
        stop_tunnel
        die "strongSwan rejected the IKEv2 configuration (see $IKE_LOG)"
    fi

    # Without systemd-resolved: point /etc/resolv.conf at the VPN DNS now,
    # so the backup is the user's own file (taken before charon's resolve
    # plugin, if loaded, adds its servers).
    use_resolved || "$DNS_HOOK" set "$TUN_IF" >/dev/null 2>&1 || warn "could not set DNS"

    swanctl --initiate --child "$IKE_NAME" --timeout 20 >>"$IKE_LOG" 2>&1
    rc=$?
    if [ "$rc" -ne 0 ]; then
        if grep -qiE 'AUTHENTICATION_FAILED|EAP_FAILURE|EAP method .* failed|MSCHAPV2.*fail' "$IKE_LOG"; then
            stop_tunnel; die "IKEv2 authentication failed"
        fi
        if grep -qiE 'constraint check failed|no trusted .* public key|no issuer certificate' "$IKE_LOG"; then
            stop_tunnel; die "IKEv2 server certificate could not be verified"
        fi
        stop_tunnel; die "IKEv2 connection failed (see $IKE_LOG)"
    fi

    umask 022
    ike_dns_link "$(ike_vip)" || true
    # Without systemd-resolved, swap the pre-connect fallback for the servers
    # the VPN pushed (if any).
    if ! use_resolved && [ -n "$(ike_pushed_dns)" ]; then
        # shellcheck disable=SC2046
        "$DNS_HOOK" set "$TUN_IF" $(ike_pushed_dns) >/dev/null 2>&1 || warn "could not set DNS"
    fi
    v6_block_on
    ike_guard_on
    switch_release
    start_monitor
    echo "started"
}

IKE_LAST_VIP=""
ike_monitor_tick() {
    local out state rx tx vip
    out="$(swanctl --list-sas --ike "$IKE_NAME" 2>/dev/null || true)"
    # An IKE rekey shows the old SA as REKEYING/REKEYED next to the new one;
    # the child SA stays INSTALLED, so that still counts as up.
    if grep -qE "^$IKE_NAME: #[0-9]+, (ESTABLISHED|REKEYING|REKEYED)" <<< "$out" && grep -q 'INSTALLED' <<< "$out"; then
        state=up
    elif grep -qE "^$IKE_NAME: #[0-9]+, (CONNECTING|CREATED)" <<< "$out"; then
        state=connecting
    else
        # SA gone (network drop / DPD): charon keeps re-initiating.
        state=stale
    fi
    # Child SA lines: "in  <spi>[ (marks)],  1234 bytes, ..." / "out ...".
    read -r rx tx < <(awk '
        $1 == "in" || $1 == "out" {
            for (i = 2; i <= NF; i++) if ($i ~ /^bytes,?$/) { v = $(i - 1); break }
            if ($1 == "in") r += v; else t += v
        }
        END { printf "%.0f %.0f\n", r + 0, t + 0 }' <<< "$out")
    write_status ikev2 "$state" 0 "${rx:-0}" "${tx:-0}"
    if [ "$state" = up ]; then
        vip="$(ike_vip)"
        if [ -n "$vip" ] && [ "$vip" != "$IKE_LAST_VIP" ]; then
            IKE_LAST_VIP="$vip"
            ike_dns_link "$vip" || true
        fi
    fi
    return 0
}

# -- Monitor (emmavpn-tunnel service for WireGuard / IKEv2) ------------------

do_monitor() {
    local proto
    umask 022
    proto="$(cat "$PROTO_FILE" 2>/dev/null || true)"
    case "$proto" in wireguard|ikev2) ;; *) exit 0 ;; esac
    echo "$$" > "$MONITOR_PID"
    trap 'rm -f "$MONITOR_PID"; exit 0' TERM INT
    while [ "$(cat "$PROTO_FILE" 2>/dev/null || true)" = "$proto" ]; do
        if [ "$proto" = wireguard ]; then
            wg_monitor_tick || break
        else
            ike_monitor_tick
        fi
        sleep 2
    done
    rm -f "$MONITOR_PID"
}

case "${1:-}" in
    connect)            do_connect "${2:-ks-keep}" ;;
    connect-wireguard)  do_connect_wireguard "${2:-ks-keep}" ;;
    connect-ikev2)      do_connect_ikev2 "${2:-ks-keep}" ;;
    monitor)            do_monitor ;;
    disconnect)         stop_tunnel; switch_release; echo "stopped" ;;
    switch-release)     switch_release "${2:-}"; echo "released" ;;
    killswitch-on)      ks_on; echo "kill switch on" ;;
    killswitch-off)     ks_off; echo "kill switch off" ;;
    killswitch-restore) if [ -f "$KS_FLAG" ]; then ks_apply; echo "kill switch restored"; fi ;;
    *)                  die "usage: emmavpn-helper connect|connect-wireguard|connect-ikev2 [ks-on|ks-off]|disconnect|killswitch-on|killswitch-off|killswitch-restore" ;;
esac
