#!/usr/bin/env bash
# Sends a desktop notification whenever a VPN connects or disconnects.
# Covers WireGuard/tun interfaces (NetworkManager, wg-quick, Proton, OpenVPN)
# and Tailscale (whose tailscale0 interface stays up even when stopped).
#
# NetworkManager WireGuard connections go stale when the underlying network
# changes (wifi -> ethernet, wifi -> wifi), so when that happens any that were
# up get restarted, checked, retried if needed, and reported as reconnected.

INTERVAL=2
RETRIES=5

# NetworkManager connection types that are a real network to be on. A list of
# what counts rather than what doesn't, since VPN clients add their own extras:
# ProtonVPN's kill switch / IPv6 leak protection are "dummy" connections that
# come and go with the tunnel, and would otherwise look like a network switch.
PHYSICAL_TYPES='^(802-3-ethernet|802-11-wireless|gsm|cdma|bluetooth|pppoe|adsl|infiniband)$'

ICON_ON=/usr/share/icons/hicolor/scalable/apps/nm-vpn-active-lock-symbolic.svg
ICON_OFF=/usr/share/icons/hicolor/scalable/apps/nm-vpn-standalone-lock-symbolic.svg

# Provider logos: Papirus has Mullvad's and Proton's; Tailscale's and UniFi's
# live in this repo (.local/share/vpn-notify).
PAPIRUS_APPS=/usr/share/icons/Papirus/64x64/apps
LOCAL_ICONS=$HOME/.local/share/vpn-notify

# Friendly name for an interface: NetworkManager connection name if it has one
vpn_name() {
    local name
    name=$(nmcli -g GENERAL.CONNECTION device show "$1" 2>/dev/null)
    echo "${name:-$1}"
}

# Logo for a VPN by its name (as vpn_name/active_vpns give it), or $2 if
# it's not one of the known providers or the logo is missing
vpn_icon() {
    local icon
    case "${1,,}" in
        *mullvad*) icon=$PAPIRUS_APPS/mullvad-vpn.svg ;;
        *proton*) icon=$PAPIRUS_APPS/protonvpn-logo.svg ;;
        tailscale) icon=$LOCAL_ICONS/tailscale.svg ;;
        *unifi*) icon=$LOCAL_ICONS/unifi.svg ;;
    esac
    [[ -n $icon && -f $icon ]] && echo "$icon" || echo "$2"
}

active_vpns() {
    ip -d -o link show up 2>/dev/null \
        | awk -F': ' '/ (wireguard|tun) / { sub(/@.*/, "", $2); print $2 }' \
        | grep -vx tailscale0 \
        | while read -r iface; do vpn_name "$iface"; done

    if command -v tailscale >/dev/null &&
        [[ $(tailscale status --json 2>/dev/null | jq -r .BackendState) == Running ]]; then
        echo Tailscale
    fi
}

# Active NetworkManager connections, as UUID:TYPE:NAME
nm_active() {
    nmcli -t -f UUID,TYPE,NAME connection show --active 2>/dev/null
}

# UUIDs of the physical networks we're on (wifi, ethernet, tethering, ...)
underlying_networks() {
    nm_active | awk -F: -v t="$PHYSICAL_TYPES" '$2 ~ t { print $1 }' | sort
}

# UUIDs of active NetworkManager WireGuard connections
nm_wireguard() {
    nm_active | awk -F: '$2 == "wireguard" { print $1 }' | sort
}

current_network_name() {
    nm_active | awk -F: -v t="$PHYSICAL_TYPES" '$2 ~ t { sub(/^[^:]*:[^:]*:/, ""); print; exit }'
}

notify() {
    notify-send -a "VPN" -i "$2" "${@:4}" "$1" "$3"
}

# Confirm traffic flows through the tunnel by pinging its DNS server
tunnel_works() {
    local uuid=$1 iface target
    iface=$(nmcli -g connection.interface-name connection show "$uuid" 2>/dev/null)
    target=$(nmcli -g ipv4.dns connection show "$uuid" 2>/dev/null | cut -d, -f1)
    [[ -z $target ]] && return 0
    ping -c 3 -W 2 -I "$iface" "$target" >/dev/null 2>&1
}

reconnect() {
    local uuid=$1 name attempt
    name=$(nmcli -g connection.id connection show "$uuid" 2>/dev/null)

    for ((attempt = 1; attempt <= RETRIES; attempt++)); do
        nmcli connection down "$uuid" >/dev/null 2>&1
        if nmcli -w 20 connection up "$uuid" >/dev/null 2>&1 && sleep 2 && tunnel_works "$uuid"; then
            notify "🔄 VPN reconnected" "$(vpn_icon "$name" "$ICON_ON")" \
                "“$name” was reconnected after switching to “$(current_network_name)”."
            return 0
        fi
        sleep $((attempt * 3))
    done

    notify "⚠️ VPN reconnect failed" "$(vpn_icon "$name" "$ICON_OFF")" \
        "Couldn't reconnect “$name” after $RETRIES attempts." -u critical
    return 1
}

prev=$(active_vpns | sort)
prev_net=$(underlying_networks)
prev_wg=$(nm_wireguard)
pending=""

while sleep "$INTERVAL"; do
    cur_net=$(underlying_networks)
    cur_wg=$(nm_wireguard)

    # Network changed: queue WireGuard connections that were up for a restart
    if [[ $cur_net != "$prev_net" ]]; then
        pending=$(printf '%s\n%s\n' "$pending" "$prev_wg" | grep -v '^$' | sort -u)
    fi

    # Drop any the user switched off themselves while waiting for a network
    if [[ -n $pending && $cur_net == "$prev_net" ]]; then
        switched_off=$(comm -23 <(echo "$prev_wg") <(echo "$cur_wg"))
        pending=$(comm -23 <(echo "$pending") <(echo "$switched_off") | grep -v '^$')
    fi

    # Reconnect once we're on a network again (give DHCP/routes a moment)
    if [[ -n $pending && -n $cur_net ]]; then
        sleep 3
        while read -r uuid; do
            # Skip any deleted since (ProtonVPN removes its connection on
            # disconnect) — that's the tunnel going away, not going stale.
            [[ -n $uuid ]] && nmcli connection show "$uuid" &>/dev/null && reconnect "$uuid"
        done <<<"$pending"
        pending=""
        # prev is left alone, so the usual diff below still reports anything
        # else that changed meanwhile (e.g. Tailscale coming up).
        cur_net=$(underlying_networks)
        cur_wg=$(nm_wireguard)
    fi

    prev_net=$cur_net
    prev_wg=$cur_wg

    cur=$(active_vpns | sort)
    [[ $cur == "$prev" ]] && continue

    while read -r vpn; do
        [[ -n $vpn ]] && notify "🔒 VPN connected" "$(vpn_icon "$vpn" "$ICON_ON")" "You are now connected to “$vpn”."
    done < <(comm -13 <(echo "$prev") <(echo "$cur"))

    while read -r vpn; do
        [[ -n $vpn ]] && notify "🔓 VPN disconnected" "$(vpn_icon "$vpn" "$ICON_OFF")" "“$vpn” has been disconnected."
    done < <(comm -23 <(echo "$prev") <(echo "$cur"))

    prev=$cur
done
