#!/bin/sh

# /proc/cmdline parser (from Gentoo Wiki)
cmdline() {
    local value
    value=" $(cat /proc/cmdline) "
    value="${value#* $1=}"
    value="${value%% *}"
    [ "$value" != "" ] && echo "$value"
}

[ -f "/var/lib/adlin/wireguard/adlin.token" ] && WGTOKEN=$(cat /var/lib/adlin/wireguard/adlin.token)
[ -z "${WGTOKEN}" ] && WGTOKEN=$(cmdline adlin.token)
[ -z "${WGTOKEN}" ] && {
    echo -n "You didn't define your token to connect the network. Please copy it into /var/lib/adlin/wireguard/adlin.token and reboot."
    exit 1
}
[ -f "/var/lib/adlin/wireguard/adlin.conf" ] && WGPRVKEY=$(sed 's/^.*PrivateKey *= *//p;d' /var/lib/adlin/wireguard/adlin.conf)
[ -z "${WGPRVKEY}" ] && WGPRVKEY=$(/usr/bin/wg genkey)
WGPUBKEY=$(echo $WGPRVKEY | /usr/bin/wg pubkey)
while ! { echo -e "[Interface]\nPrivateKey = ${WGPRVKEY}"; /usr/bin/wget -O - --header "X-WG-pubkey: $WGPUBKEY" https://adlin.nemunai.re/api/wg/$(echo -n "$WGTOKEN" | /usr/bin/sha512sum | /usr/bin/cut -d ' ' -f 1); } > /var/lib/adlin/wireguard/adlin.conf
do
    exit 1
done
echo -n "${WGTOKEN}" > /var/lib/adlin/wireguard/adlin.token
/sbin/ip link add dev wg0 type wireguard
/usr/bin/wg setconf wg0 /var/lib/adlin/wireguard/adlin.conf
/sbin/ip address add dev wg0 $(sed 's/^.*MyIPv6=//p;d' /var/lib/adlin/wireguard/adlin.conf)
/sbin/ip link set up dev wg0
/sbin/ip -6 route del default
/sbin/ip -6 route add default via $(sed 's/^.*GWIPv6=//p;d' /var/lib/adlin/wireguard/adlin.conf) pref high
