#!/bin/bash
# Add a vantage point and generate its keys

set -e -o pipefail -u

VP=$1

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

if [ "${VP}" = "" ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
  echo "Usage: $0 vantage-point-name" 1>&2
  echo "  Example: $0 san8-us" 1>&2
  echo "The node should already exist in dory with a natpport." 1>&2
  exit 1
fi

# we're a lot more flexible about node names now, only requirement
# is that it is able to be used as a sensible username and file name
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

# get the port number from the sole source of truth, the dory database
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

# use the port number as the username, so that if we rename a node and then
# later try to generate the natp-ssh packages for the new ark name none of
# the config will need to change
PERSISTENTNAME="natp-${PORT}"

# if the name already exists then just reuse the existing configuration
if getent passwd "${PERSISTENTNAME}" > /dev/null; then
  echo "WARNING: user ${PERSISTENTNAME} already exists in /etc/passwd" 1>&2
  ../bin/natp-dpkg "${VP}"
  exit 0
fi

# if this is an older node with a user named after the node itself then at
# this stage I think we still want to just reuse the existing configuration
if getent passwd "${VP}" > /dev/null; then
  echo "WARNING: user ${VP} already exists in /etc/passwd" 1>&2
  ../bin/natp-dpkg "${VP}"
  exit 0
fi

useradd --comment "NAT reverse tunnel" \
        --uid "${PORT}" \
        --gid natp-ssh \
        --home-dir /opt/natp-ssh \
        --no-create-home \
        --no-user-group \
        --shell /bin/false \
        --password '*' \
        "${PERSISTENTNAME}"
R=$?
if [ "${R}" != "0" ]; then
  echo "ERROR: useradd ${VP} (${PERSISTENTNAME}) failed with ${R}." 1>&2
  exit 1
fi

ssh-keygen -q \
           -t ed25519 \
           -N "" \
           -C "${PERSISTENTNAME}" \
           -f "private-keys/${PERSISTENTNAME}"
mv "private-keys/${PERSISTENTNAME}.pub" "authorized_keys/${PERSISTENTNAME}"

../bin/regenerate-sshd-config
../bin/natp-dpkg "${VP}"

echo "Created new credentials for ${VP} on port ${PORT}" 1>&2

exit 0
