# deploy
### If there is a wireguard vpn script
for file in $( find "/docker/$service" -name "wgns-*.sh") ; do
	section "Managing wg interface $(basename "$file")"
    if [ -x "$file" ] ; then
        wgif="$(basename "$file")"
        wgif="${wgif:5:-3}"
		if [ -z "$wgif" ] ; then
			echo "No wireguard name for $file"
			returncode=1
			continue
		fi
        "$file" $wgif > "/etc/wireguard/$wgif.conf"
		if "$deploy" ; then
        	#run systemctl enable "wg-quick@$wgif"
        	run managewg.sh start "$wgif"
			[ "$?" -ne 0 ] && echo "Erreur wireguard" && returncode=1
		else
        	run managewg.sh stop "$wgif"
		fi
    fi
done

### If there is a wireguard vpn template
for file in $( find "/docker/$service" -name "wg-*.sh") ; do
	section "Creating wg iface $(basename "$file")"
    if [ -x "$file" ] ; then
        wgif="$(basename "$file")"
        wgif="${wgif:3:-3}"
		if [ -z "$wgif" ] ; then
			echo "No wireguard name for $file"
			returncode=1
			continue
		fi
		#run template.sh "/docker/$service/.env" < "$file" > "/etc/wireguard/$wgif.conf"
        "$file" $wgif > "/etc/wireguard/$wgif.conf"

		if "$deploy" ; then
        	run systemctl enable "wg-quick@$wgif"
        	run startwg.sh start "$wgif"
			[ "$?" -ne 0 ] && echo "Erreur wireguard" && returncode=1
		else
        	run managewg.sh stop "$wgif"
		fi
    fi
done

## start
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")
}