#!/usr/bin/env bash
set -euo pipefail

URL_BASE="https://wireguard.admin.dmknet.de/config.php"
IFACE="DMK"
DEST="/etc/wireguard/${IFACE}.conf"

if [[ $EUID -ne 0 ]]; then
  echo "run as root" >&2
  exit 1
fi

export DEBIAN_FRONTEND=noninteractive
apt-get update -y
apt-get install -y wireguard wireguard-tools curl

read -r -p "Basic-Auth User: " AUTH_USER
read -r -s -p "Basic-Auth Passwort: " AUTH_PASS; echo
read -r -p "Clientname (AWX Hostname): " CLIENT; echo

if [[ ! "$CLIENT" =~ ^[a-zA-Z0-9._-]{1,64}$ ]]; then
  echo "invalid client name" >&2
  exit 1
fi

TMP="$(mktemp)"
umask 077

curl -fsSL -u "${AUTH_USER}:${AUTH_PASS}" \
  "${URL_BASE}?client=${CLIENT}" \
  -o "$TMP"

grep -q "^\[Interface\]" "$TMP"
grep -q "^\[Peer\]" "$TMP"

install -m 600 -o root -g root "$TMP" "$DEST"
rm -f "$TMP"

systemctl enable --now "wg-quick@${IFACE}"

echo "OK: ${DEST} installiert und wg-quick@${IFACE} aktiv."
