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

# -------- Inputs (from environment) ------------------------------------------
OUT_DIR="${OUT_DIR:-/config}"              # mount your shared volume here
INSTANCE="${INSTANCE:-default}"            # for traceability (comment only)
LAN_INTERFACE="${LAN_INTERFACE:-eth0}"     # comment only (for reference)
VPN_INTERFACE="${VPN_INTERFACE:-wg0}"      # output filename: /out/<VPN_INTERFACE>.conf

PRIVATE_KEY="${PRIVATE_KEY:-}"             # REQUIRED (client private key)
# REQUIRED (server public key) — use either PEER_PUBLIC_KEY or PUBLIC_KEY
PEER_PUBLIC_KEY="${PEER_PUBLIC_KEY:-${PUBLIC_KEY:-}}"

PEER_ENDPOINT="${PEER_ENDPOINT:-}"         # REQUIRED (host:port)
PEER_ALLOWED_IPS="${PEER_ALLOWED_IPS:-}"             # REQUIRED (e.g. "0.0.0.0/0, ::/0" or "10.10.0.0/16")
VPN_IPV4="${VPN_IPV4:-}"                   # OPTIONAL (e.g. "10.7.0.2/32")

# Optional tuning
MTU="${MTU:-1420}"
PERSISTENT_KEEPALIVE="${PERSISTENT_KEEPALIVE:-25}"
DNS="${DNS:-}"                             # OPTIONAL (e.g. "10.7.0.1")

# Also create a compatibility symlink to wg0.conf?
CREATE_WG0_SYMLINK="${CREATE_WG0_SYMLINK:-true}"

# -------- Validation ----------------------------------------------------------
missing=()
[[ -n "$PRIVATE_KEY"     ]] || missing+=("PRIVATE_KEY")
[[ -n "$PEER_PUBLIC_KEY" ]] || missing+=("PEER_PUBLIC_KEY (or PUBLIC_KEY)")
[[ -n "$PEER_ENDPOINT"   ]] || missing+=("PEER_ENDPOINT")
[[ -n "$PEER_ALLOWED_IPS"     ]] || missing+=("PEER_ALLOWED_IPS")

if [[ "${#missing[@]}" -gt 0 ]]; then
  printf 'ERROR: missing required env vars: %s\n' "$(IFS=', '; echo "${missing[*]}")" >&2
  exit 1
fi

# -------- Prepare output dir --------------------------------------------------
mkdir -p "$OUT_DIR"
chmod 700 "$OUT_DIR" || true

CONF_PATH="${OUT_DIR}/${VPN_INTERFACE}.conf"

# -------- Write wg config -----------------------------------------------------
# NOTE: do not echo secrets to logs.
umask 077
{
  echo "# Autogenerated by setup-wg.sh ($(date -u +'%Y-%m-%dT%H:%M:%SZ'))"
  echo "# Instance: ${INSTANCE} | LAN_IF: ${LAN_INTERFACE} | VPN_IF: ${VPN_INTERFACE}"
  echo

  echo "[Interface]"
  echo "PrivateKey = ${PRIVATE_KEY}"
  if [[ -n "$VPN_IPV4" ]]; then
    echo "Address = ${VPN_IPV4}"
  fi
  echo "MTU = ${MTU}"
  if [[ -n "$DNS" ]]; then
    echo "DNS = ${DNS}"
  fi
  echo
  echo "[Peer]"
  echo "PublicKey = ${PEER_PUBLIC_KEY}"
  # Remove whitespace around commas in AllowedIPs
  echo "AllowedIPs = ${PEER_ALLOWED_IPS//, /,}"
  echo "Endpoint = ${PEER_ENDPOINT}"
  echo "PersistentKeepalive = ${PERSISTENT_KEEPALIVE}"
} >"$CONF_PATH"

chmod 600 "$CONF_PATH"

# Optionally create a wg0.conf symlink for containers expecting the default name
if [[ "$CREATE_WG0_SYMLINK" == "true" && "$VPN_INTERFACE" != "wg0" ]]; then
  ln -sfn "${VPN_INTERFACE}.conf" "${OUT_DIR}/wg0.conf"
fi

# -------- Summary (no secrets) ------------------------------------------------
echo "[ok] wrote ${CONF_PATH}"
[[ -L "${OUT_DIR}/wg0.conf" ]] && echo "[ok] symlink ${OUT_DIR}/wg0.conf -> ${VPN_INTERFACE}.conf"
