#!/bin/sh

. ~/.bin/_config

LIST="$(cat /etc/wireguard/vpnlist.txt)"
SEL="$(print "$LIST\ndeactivate\nhome" | cut -d'	' -f1 | $DMENU_CMD -l 20 -p "VPN")"

[ -z "$SEL" ] && exit 0

needs wireguard-tools--

if [ "$SEL" == "deactivate" ]
then
    ACTIVE=$(ifconfig | grep wg-quick | cut -d: -f3 | tr -d " ")
    if [ ! -z "$ACTIVE" ]
    then
        doas wg-quick down $ACTIVE && NOTIFY_CMD "VPN: disconnected"
        sleep 1
        doas ifconfig trunk0 inet6 autoconf
    fi
    exit 0
fi


HOST="$(echo "$LIST" | fgrep "$SEL" | cut -d'	' -f2)"

cat /etc/wireguard/template.conf | sed "s/XXXXXX/$HOST/g" > /tmp/vpn.conf

doas mv /tmp/vpn.conf /etc/wireguard/vpn.conf

ACTIVE=$(ifconfig | grep wg-quick | cut -d: -f3 | tr -d " ")
if [ ! -z "$ACTIVE" ]
then
    doas wg-quick down $ACTIVE && NOTIFY_CMD "VPN: disconnected"
    sleep 1
    doas ifconfig trunk0 inet6 autoconf
fi

doas ifconfig trunk0 -inet6
sleep 1
doas wg-quick up vpn && NOTIFY_CMD "VPN: $HOST"
