#!/bin/bash

#set -euo pipefail
# Pipefail will trigger annoying sigpipe on our greps
set -eu

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

action="$1"
wgif="$2"

start () {
	echo "Starting $wgif"
	wg-quick up "$wgif"
}

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

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

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