#!/bin/sh -e
# 2024-10-28
PATH=/usr/pkg/bin:$PATH

# Expects to find wireguard-go config in /etc/wireguard.tun*.conf
# Config should include a comment of the form #localip=172.16.2.4
# to configure the local IP address

extract_conf()
{
    conf_file="$1"
    conf_localip=$( awk '/localip=/{gsub(".*=","");print}' "$conf_file")
    if [ -z "$conf_localip" ]; then
        fail "Unable to extract localip from $conf_file"
    fi
    conf_nets=$(awk '/^ *AllowedIPs *= */{gsub(".*= *","");gsub("#.*","");if(!/\/32$/){print}}' "$conf_file")
    if [ -z "$conf_nets" ]; then
        fail "Unable to extract allowed nets from $conf_file"
    fi

    conf_tun="$(echo $conf_file | sed -e 's:.*wireguard.::' -e 's:.conf$::')"
    case "$conf_tun" in
        tun*) ;;
        *) fail "Unable to extract tun from $conf_file ($conf_tun)" ;;
    esac

    # echo conf_localip=$conf_localip
    # echo conf_nets=$conf_nets
    # echo conf_tun=$conf_tun
}

fail()
{
    echo "**** $@"
    exit 1
}

start()
{
    ifconfig $conf_tun create $conf_localip
    for net in $conf_nets ; do
        route add -net $net $conf_localip
    done
    wireguard-go $conf_tun
    wg setconf $conf_tun $conf_file
    wg show $conf_tun | grep interface | sed 's/^/wg /'
}

stop()
{
    while pgrep -fq "wireguard-go $conf_tun" ; do
        echo "Kill wireguard-go $conf_tun"
        pkill -9 -f "wireguard-go $conf_tun"
        sleep 0.1
    done
    if ifconfig $conf_tun > /dev/null 2>&1 ; then
        echo "Destroy $conf_tun"
        ifconfig $conf_tun destroy
    fi
}

if [ $(id -u) != 0 ]; then
    exec doas $0 "$@"
fi

for conf in /etc/wireguard.*.conf ; do
    extract_conf $conf

    case "$1" in
      stop) stop ;;
      status) pgrep -lf "wireguard-go $conf_tun";;
      start | restart | '') stop; start ;;
      * ) echo "Unknown option: $1"; exit ;;
    esac

done

