#!/bin/bash

set -e -o pipefail

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

. ${NDIR}/conf

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

echo "# WARNING: generated by $0" > ${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 $0" > ${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}
  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)"'
)

# rename temp files, overwriting the old versions of the config files
mv ${SSHDCONF}.$$ ${SSHDCONF}
mv ${INCL}.$$ ${INCL}

systemctl restart natp-sshd

exit 0
