#!/bin/sh

# Source function library
. /etc/init.d/functions

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DESC=WireGuard

WG_DIR=/etc/wireguard
IFACE=wg0
PORT=51820

if [ -e /etc/default/wireguard0 ];then
	source /etc/default/wireguard0
fi;

create_key() {
	if [ ! -e ${WG_DIR}/${1}.key ];then
		if [ -e ${WG_DIR}/${1}.pub ];then
			rm ${WG_DIR}/${1}.pub
		fi
		umask 0377
		/usr/bin/wg genkey >${WG_DIR}/${1}.key
	fi;
	if [ ! -e ${WG_DIR}/${1}.pub ];then
		umask 0133
		cat ${WG_DIR}/${1}.key |/usr/bin/wg pubkey > ${WG_DIR}/${1}.pub
	fi;
}

create_conf() {
	if [ ! -e ${WG_DIR}/${1}.key ] || [ ! -e ${WG_DIR}/${1}.pub ];then
		create_key ${1}
	fi;

	/usr/bin/wg set wg0 listen-port ${2} private-key ${WG_DIR}/${1}.key
	umask 0177
	/usr/bin/wg showconf ${1} > ${WG_DIR}/${1}.conf
}

create_psk() {
	if [ ! -e ${WG_DIR}/${1}.psk ];then
		umask 0377
		/usr/bin/wg genpsk > ${WG_DIR}/${1}.psk
	fi;
}

if [ ! -d ${WG_DIR} ];then
	mkdir ${WG_DIR}
fi;

set -e

case $1 in
        start)
		echo "Starting ${DESC}"
		if [ ! -d /sys/class/net/${IFACE} ];then
			/sbin/ip link add ${IFACE} type wireguard
			if [ "${WG0_ENABLE}" == "1" ];then
				/sbin/ip link set dev ${IFACE} up
			fi;
		fi;

		if [ -n "${WG0_IP}" ];then
			for newip in ${WG0_IP};do
				ip addr add ${newip} dev wg0
			done;
		fi;

		if [ -n "${WG0_ROUTE}" ] && [ "${WG0_ENABLE}" == "1" ];then
			for newrt in ${WG0_ROUTE};do
				ip route add ${newrt} dev wg0
			done;
		fi;

		if [ ! -e ${WG_DIR}/${IFACE}.conf ];then
			create_conf ${IFACE} ${PORT}
		else
			/usr/bin/wg setconf ${IFACE} ${WG_DIR}/${IFACE}.conf
		fi;
		if [ "${WG0_ENABLE}" == "1" ];then
			iptables -A FIREWALL -j ACCEPT -p udp --dport=$(wg show wg0 listen-port)
			if [ -n "${WG0_PEER}" ] && [ -n "${WG0_DNS}" ] && [ -n "${WG0_PORT}" ];then
				wg set wg0 peer ${WG0_PEER} endpoint ${WG0_DNS}:${WG0_PORT}
			fi;
		fi;
	;;
	stop)
		echo "Stoping ${DESC}"
		iptables -D FIREWALL -j ACCEPT -p udp --dport=$(wg show wg0 listen-port) >/dev/null 2>&1 ||:
		if [ -d /sys/class/net/${IFACE} ];then
			umask 0377
			/usr/bin/wg showconf ${IFACE} > ${WG_DIR}/${IFACE}.conf
			/sbin/ip link set dev ${IFACE} down
			/sbin/ip link del ${IFACE}
		fi;
		if [ -d /sys/module/wireguard ];then
			rmmod wireguard
		fi;
	;;
esac

exit 0
