#!/bin/bash

set -euo pipefail

if [ "$#" -ne 2 ] ; then
	echo "Usage: $0 <start|stop|reload|restart> <wgif>"
	exit 1
fi

action="$1"
wgif="$2"
# Command to exec in netns
run="ip netns exec $wgif"

start () {
	echo "Starting $wgif"

	# Create netns if needed
	if ! ip netns | grep -q "$wgif" ; then
		ip netns add "$wgif"
	fi
	
	# Create iface
	if ! ip link | grep -q "$wgif" ; then
		ip link add "$wgif" type wireguard
		ip link set "$wgif" netns "$wgif"
	fi

	#$run wg-quick up "$wgif"
	$run wg setconf "$wgif" "/etc/wireguard/$wgif.conf"
}

stop () {
	echo "Stoping $wgif"
	$run wg-quick down "$wgif" || true
}

reload () {
	echo "Reloading $wgif"
	$run wg syncconf "$wgif" <(wg-quick strip "$wgif")
}

case "$action" in
	start)
		if $run ip a | grep -q "$wgif" ; then
			reload
		else
			start
		fi
		;;
	stop)
		stop
		;;
	reload)
		reload
		;;
	restart)
		stop
		start
		;;
	*)
		echo "Invalid action $action"
		;;
esac