#!/bin/sh

# SPDX-FileCopyrightText: 2022 unman <unman@thirdeyesecurity.org>
# SPDX-FileCopyrightText: 2023 - 2024 Benjamin Grande M. S. <ben.grande.b@gmail.com>
#
# SPDX-License-Identifier: AGPL-3.0-or-later

set -eu

test "$(id -u)" = "0" || exec sudo "$0" "$@"
qube="${1:-"sys-wireguard"}"

if ! qvm-check -q "$qube" >/dev/null 2>&1; then
  echo "Qube '$qube' doesn't exist" >&2
  exit 1
fi

qvm-run "$qube" -- test -f /home/user/wireguard.conf || {
  echo "File /home/user/wireguard.conf was not found" >&2
  exit 1
}

## TOFU
# shellcheck disable=SC2016
endpoint="$(qvm-run -p "$qube" -- awk '/Endpoint/{print $3}' /home/user/wireguard.conf)"
ip="$(echo "$endpoint" | cut -d ":" -f 1)"
port="$(echo "$endpoint" | cut -d ":" -f 2)"
if test -z "$ip" || test -z "$port";then
  echo "Endpoint (IP:Port) not found in /home/user/wireguard.conf" >&2
  exit 1
fi

if qvm-check -q --running "$qube" >/dev/null 2>&1; then
  qvm-pause --verbose "$qube"
fi

echo "Firewalling $qube"
qvm-firewall --verbose "$qube" reset
qvm-firewall --verbose "$qube" del --rule-no 0
qvm-firewall --verbose "$qube" add accept dsthost="$ip" dstports="$port" proto=udp
qvm-firewall --verbose "$qube" add accept dsthost="$ip" dstports="$port" proto=tcp
qvm-firewall --verbose "$qube" add drop

if qvm-check -q --paused "$qube" >/dev/null 2>&1; then
  qvm-unpause --verbose "$qube"
fi
