#!/bin/bash

set -e -o pipefail

# save this now otherwise it could be relative to $NDIR later on
CMD=$(realpath "$0")

NDIR=/opt/natp-ssh/etc
cd ${NDIR}

. ${NDIR}/conf

SSHDCONF=${NDIR}/sshd_config
INCL=${NDIR}/ssh_config_include

echo "# WARNING: generated by $CMD" > ${SSHDCONF}.$$
echo "# Changes will be lost on next run." >> ${SSHDCONF}.$$
echo "# Edit ${SSHDCONF}.base instead." >> ${SSHDCONF}.$$
echo "" >> ${SSHDCONF}.$$

cat ${SSHDCONF}.base >> ${SSHDCONF}.$$

echo "# WARNING: generated by $CMD" > ${INCL}.$$
echo "# Changes will be lost on next run." >> ${INCL}.$$
echo "# Edit include.base instead." >> ${INCL}.$$
echo "" >> ${INCL}.$$

cat include.base >> ${INCL}.$$

# Note: the input filename that "read' consumes comes after the "done"
# matching this "while" all the way at the end of the script.
# That's just the way bash rolls.
while read -r LINE ;do
  IFS=',' read -r -a VALUES <<< "${LINE}"
  VP=${VALUES[0]}
  PORT=${VALUES[1]}
  THISSERVER=${SERVER}
  if [ "${PORTSERVER}" != "" ] ;then
    THISSERVER=${PORTSERVER}
  fi
  if [ "${THISSERVER}" != "${THISSERVER##.}" ] ;then
    # begins with "." so prepend the VP name
    THISSERVER=${VP}${THISSERVER}
  fi
  if [ -n "${PORT}" ] && [ "${PORT}" != "null" ]; then
cat <<EOM >> ${SSHDCONF}.$$
Match User ${VP},natp-${PORT}
  PermitListen ${PORT}

EOM
cat <<EOM >> ${INCL}.$$
Host ${VP}
  HostKeyAlias ${VP}:${PORT}
  HostName ${THISSERVER}
  Port ${PORT}
  KeepAlive yes
  ServerAliveInterval 90
  CheckHostIP no

EOM
  fi
done < <(
    oidc_query \
        --token-file /etc/ark/.arkmon-offline.token \
        arkmon-offline \
        "https://api.arkmon.caida.org/monitors/" \
        2>/dev/null \
        | jq -r '.[] | select(.hwtype != "Container") | "\(.node),\(.natpport)"'
)

# copy the temporary sshd_config over the existing config if they differ
if [ "$(cat ${SSHDCONF}.$$ | md5sum)" != "$(cat ${SSHDCONF} | md5sum)" ]; then
    mv ${SSHDCONF}.$$ ${SSHDCONF}
    systemctl restart natp-sshd
else
    rm ${SSHDCONF}.$$
fi

# TODO is it safe to remove the ssh client config include file now that the
# system is using the ark-ssh-aliases package to generate global ssh config?
if [ "$(cat ${INCL}.$$ | md5sum)" != "$(cat ${INCL} | md5sum)" ]; then
    mv ${INCL}.$$ ${INCL}
else
    rm ${INCL}.$$
fi

exit 0
