#!/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 secrets/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)/secrets/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")

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

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

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

# EOF
