#!/bin/bash
# Delete a vantage point and remove its keys

set -e -o pipefail -u

VP=$1

if [ "${VP}" = "" ] ;then
  echo "Usage: $0 vantage-point-name"
  echo "  Example: $0 san8-us"
  exit 1
fi

if echo "${VP}" | grep -Eqv "^[a-z_][a-z0-9_-]{0,31}$"; then
  echo "ERROR: Vantage point name $VP must be usable as a username" 1>&2
  echo "(lower case ascii letters, numbers, underscores, hyphens)" 1>&2
  echo "  Example: san8-us" 1>&2
  exit 1
fi

cd /opt/natp-ssh/etc || exit 1

PORT=$(oidc_query \
            --token-file /etc/ark/.arkmon-offline.token \
            arkmon-offline \
            "https://api.arkmon.caida.org/monitors/${VP}" \
            2>/dev/null \
            | jq ".natpport")

if [ -z "$PORT" ]; then
  echo "ERROR: Failed to query dory for natpport" 1>&2
  exit 1
fi

if [ "$PORT" == "null" ]; then
  echo "ERROR: ${VP} does not have a port defined in dory" 1>&2
  exit 1
fi

PERSISTENTNAME="natp-${PORT}"

if getent passwd "$PERSISTENTNAME" > /dev/null; then
    ACTUALNAME=$PERSISTENTNAME
elif getent passwd "$VP" > /dev/null; then
    ACTUALNAME=$VP
else
    echo "ERROR: no account matching ${PERSISTENTNAME} or ${VP}" 1>&2
    exit 1
fi

userdel "$ACTUALNAME"
R=$?
if [ "${R}" != "0" ] ;then
  echo "ERROR: userdel ${ACTUALNAME} failed with ${R}."
  exit 1
fi

rm private-keys/"${ACTUALNAME}"
rm authorized_keys/"${ACTUALNAME}"
rm deb/natp-ssh-"${VP}"-*.deb

../bin/regenerate-sshd-config

echo "${VP} deleted"
exit 0
