#!/usr/bin/env bash

# Scope: Create wireguard keys for all monitoringVPN hosts
# Parameters:
#   file: path to grid.nix of morph deployment
#
# Output: Key files for all monitoring VPN hosts in {private,public}-keys/monitoringvpn
#         relative to the grid.nix
#
# The server key will also be symlinked to server.{key,pub}.

set -euxo pipefail

umask 077

if [[ $# -ne 1 ]]; then
    echo "Illegal number of parameters. Expected: file (path of grid.nix)"
    exit 2
fi

SRC=$(dirname $0)
VPN_SECRETS=$(dirname $1)/private-keys/monitoringvpn
VPN_PUBLIC=$(dirname $1)/public-keys/monitoringvpn

CONFIG=$(nix-instantiate --strict --json --eval "${SRC}"/get-vpn-config.nix --arg pathToGrid "${1}")

MONITORING_IPS=$(echo $CONFIG | jp --unquoted "join(' ', clientIPs)")
VPNSERVER_IP=$(echo $CONFIG | jp --unquoted "serverIP")

mkdir -p "${VPN_SECRETS}"
mkdir -p "${VPN_PUBLIC}"

for i in $MONITORING_IPS $VPNSERVER_IP; do
  wg genkey | tee "${VPN_SECRETS}"/${i}.key | wg pubkey > "${VPN_PUBLIC}"/${i}.pub
done

wg genpsk > "${VPN_SECRETS}"/preshared.key

ln -fs $VPNSERVER_IP.key "${VPN_SECRETS}"/server.key
ln -fs $VPNSERVER_IP.pub "${VPN_PUBLIC}"/server.pub

# EOF