#!/bin/sh
set -eu

if [ "$(id -u)" -ne 0 ]; then
  echo "Run this command as root on the VPN hub." >&2
  exit 1
fi

site_name="${VIMIFY_VPN_SITE_NAME:-}"
site_public_key="${VIMIFY_VPN_SITE_PUBLIC_KEY:-}"
site_address="${VIMIFY_VPN_SITE_ADDRESS:-}"
case "$site_name" in *[!a-zA-Z0-9_.-]*|'') echo "VIMIFY_VPN_SITE_NAME is invalid." >&2; exit 1 ;; esac
case "$site_public_key" in *[!a-zA-Z0-9+/=]*|'') echo "VIMIFY_VPN_SITE_PUBLIC_KEY is invalid." >&2; exit 1 ;; esac
case "$site_address" in *[!0-9./]*|'') echo "VIMIFY_VPN_SITE_ADDRESS is invalid." >&2; exit 1 ;; esac
case "$site_address" in *.*.*.*'/32') ;; *) echo "VIMIFY_VPN_SITE_ADDRESS must be a unique IPv4 /32 address." >&2; exit 1 ;; esac

interface_name="wg-vimify"
if ! wg show "$interface_name" >/dev/null 2>&1; then
  echo "The Vimify VPN hub is not running." >&2
  exit 1
fi

wg set "$interface_name" peer "$site_public_key" allowed-ips "$site_address"
wg-quick save "$interface_name"
install -d -m 0700 /etc/vimify-vpn
printf '%s\t%s\t%s\n' "$site_name" "$site_address" "$site_public_key" >> /etc/vimify-vpn/peers.tsv
chmod 0600 /etc/vimify-vpn/peers.tsv
printf 'Registered %s at %s.\n' "$site_name" "$site_address"
