#!/bin/sh

# PROVIDE: fwireguard
# REQUIRE: NETWORKING
# KEYWORD: shutdown

# @(#)%%SIMPLEVERSIONTAG%%

#
# fwireguard_enable (bool):    Set to "YES" to enable wireguard (default: "NO")
# fwireguard_wait (str):       wait (sleep) this time before calling post-start
#                              when configuring an interface (default: 2s)
# fwireguard_configdir (str):  Where fwireguard finds its configuration
#                              (default: %%PREFIX%%/etc/fwireguard)
# fwireguard_interfaces (str): Set to "AUTO" (default) to automatically handle
#                              all wireguard interfaces or provide a list of
#                              wireguard interfaces to be handled
#
# NOTE: All wireguard interfaces must be mentioned fist in "cloned_interfaces".
#

# shellcheck disable=SC2034,SC2129,SC2223,SC3037

# shellcheck disable=SC1094     # parsing fails: rc.subr contains unknown features
. /etc/rc.subr

name=fwireguard
desc="Wireguard startup helper"
rcvar=fwireguard_enable
extra_commands="reload status"

start_cmd="${name}_start"
stop_cmd="${name}_stop"
reload_cmd="${name}_reload"
status_cmd="${name}_status"

load_rc_config $name

: ${fwireguard_enable:="NO"}
: ${fwireguard_wait="2s"}
: ${fwireguard_configdir:="%%FWIREGUARD_ETCDIR%%"}
: ${fwireguard_interfaces="AUTO"}


# Automatically expand to the  interface names if needed
[ "${fwireguard_interfaces}" = "AUTO" ] && fwireguard_interfaces="$(/sbin/ifconfig -g wg)"


fwireguard_start()
{
    local _f _if

    if [ ! -d "${fwireguard_configdir}" ]; then
        mkdir "${fwireguard_configdir}"
    fi
    for _if in ${fwireguard_interfaces}; do

        _f="${fwireguard_configdir}/${_if}.key"
        if [ ! -f "${_f}" ]; then
            echo "Generating secret key for ${_if} in ${_f}"
            (umask 0077; /usr/bin/wg genkey > "${_f}")
        fi

        _f="${fwireguard_configdir}/${_if}.pub"
        if [ ! -f "${_f}" ]; then
            echo "Generating public key for ${_if} in ${_f}"
            /usr/bin/wg pubkey < "${fwireguard_configdir}/${_if}.key" > "${_f}"
        fi

        _f="${fwireguard_configdir}/${_if}.conf"
        if [ ! -f "${_f}" ]; then
            echo "Generating minimal config for ${_if} in ${_f}"
            umask 0077
            echo "[Interface]"                                  >  "${_f}"
            /usr/bin/printf 'PrivateKey\t\t= '                  >> "${_f}"
            /bin/cat "${fwireguard_configdir}/${_if}.key"       >> "${_f}"
            echo -e "#ListenPort\t\t= 51820"                    >> "${_f}"
            echo -e "#FwMark\t\t\t= 0x12345678\n"               >> "${_f}"
            echo "#[Peer]"                                      >> "${_f}"
            echo -e "#PublicKey\t\t= BlAbLABlA/EtCeTcEtc="      >> "${_f}"
            echo -e "#AllowedIPs\t\t= 10.X.X.1/32, 10.X.X.2/32" >> "${_f}"
            echo -e "#PresharedKey\t\t= BlAbLABlA/EtCeTcEtc="   >> "${_f}"
            echo -e "#Endpoint\t\t= [2001:db8::1]:51820"        >> "${_f}"
            echo -e "#PersistentKeepalive\t= 30"                >> "${_f}"
        fi

        /sbin/ifconfig "${_if}" destroy
        /sbin/ifconfig "${_if}" create    # will take ifconfig_wgX="inet values" from /etc/rc.conf
        /usr/bin/wg setconf "${_if}" "${_f}"
        if [ -x "${fwireguard_configdir}/${_if}.post-start" ]; then
            if [ -n "${fwireguard_wait}" ]; then
                /bin/sleep "${fwireguard_wait}"
            fi
            "${fwireguard_configdir}/${_if}.post-start"
        fi
#       /usr/bin/wg syncconf ${_if} ${_f}
    done
}


fwireguard_stop()
{
    local _if

    for _if in ${fwireguard_interfaces}; do
        if [ -x "${fwireguard_configdir}/${_if}.pre-stop" ]; then
            "${fwireguard_configdir}/${_if}.pre-stop"
        fi
        /sbin/ifconfig "${_if}" down
    done
}


fwireguard_reload()
{
    fwireguard_start
}


fwireguard_status()
{
    local _if

    for _if in ${fwireguard_interfaces}; do
        /usr/bin/wg show "${_if}"
    done
}


run_rc_command "$1"
