#!/bin/sh
set -eu

# The daemon admits and renders this sole configuration; arbitrary wg-quick
# files, commands and configuration hooks are not part of this entry point.
if [ "$#" -ne 2 ] || [ "$2" != /run/northlink/private/wireguard/nlk0.conf ]; then
    echo "Northlink: unsupported WireGuard arguments" >&2
    exit 64
fi
case "$1" in
    up|down) ;;
    *) echo "Northlink: unsupported WireGuard operation" >&2; exit 64 ;;
esac

# A missing, disabled or complain-mode profile must never silently turn this
# confined entry point into an unconfined execution when AppArmor is enabled.
if [ -e /sys/module/apparmor/parameters/enabled ]; then
    if ! IFS= read -r apparmor_enabled </sys/module/apparmor/parameters/enabled; then
        echo "Northlink: cannot determine AppArmor state" >&2
        exit 77
    fi
    case "$apparmor_enabled" in
        Y|y|1)
            if ! IFS= read -r apparmor_label </proc/self/attr/current || [ "$apparmor_label" != 'northlink-wg-quick (enforce)' ]; then
                echo "Northlink: WireGuard AppArmor confinement is unavailable" >&2
                exit 77
            fi
            ;;
        N|n|0) ;;
        *) echo "Northlink: unknown AppArmor state" >&2; exit 77 ;;
    esac
fi

PATH=/usr/sbin:/usr/bin:/sbin:/bin
WG_QUICK_USERSPACE_IMPLEMENTATION=wireguard-go
export PATH WG_QUICK_USERSPACE_IMPLEMENTATION
exec /usr/bin/wg-quick "$@"
