#!/usr/bin/env bash
# ==========================================================================
#     _   _ _ ____            ____          _____
#    | | | (_)  _ \ ___ _ __ / ___|___  _ _|_   _| __ __ _  ___ ___ _ __
#    | |_| | | |_) / _ \ '__| |   / _ \| '_ \| || '__/ _` |/ __/ _ \ '__|
#    |  _  | |  __/  __/ |  | |__| (_) | | | | || | | (_| | (_|  __/ |
#    |_| |_|_|_|   \___|_|   \____\___/|_| |_|_||_|  \__,_|\___\___|_|
#
#       ---  High-Performance Connectivity Tracer (HiPerConTracer)  ---
#                 https://www.nntb.no/~dreibh/hipercontracer/
# ==========================================================================
#
# High-Performance Connectivity Tracer (HiPerConTracer)
# Copyright (C) 2015-2026 by Thomas Dreibholz
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Contact: dreibh@simula.no

# Bash options:
set -euo pipefail


# ###### Usage ##############################################################
usage () {
   local exitCode="$1"
   echo >&2 "Usage: $0 node_id [-r|--remove-data] [-h|--help] [-v|--version]"
   exit "${exitCode}"
}


# ###### Version ############################################################
version () {
   echo "HiPerConTracer-Node-Removal @BUILD_MAJOR@.@BUILD_MINOR@.@BUILD_PATCH@"
   exit 0
}


# ###### Main program #######################################################

# ====== Handle arguments ===================================================
if (( BASH_VERSINFO[0] < 4 )) || (( (BASH_VERSINFO[0] == 4) && (BASH_VERSINFO[1] < 4) )) ; then
   echo "ERROR: Bash 4.4 or higher is required, but Bash ${BASH_VERSINFO[0]}.${BASH_VERSINFO[1]} is installed!"
   exit 1
fi
GETOPT="$(PATH="/usr/local/bin:${PATH}" command -v getopt)"
if "${GETOPT}" -T >/dev/null 2>&1 || [[ $? -ne 4 ]]; then
   echo >&2 "ERROR: Enhanced/GNU getopt is required!"
   exit 1
fi
options="$(${GETOPT} -o rhv --long remove-data,help,version -a -- "$@")"
# shellcheck disable=SC2181
if [[ $? -ne 0 ]] ; then
   usage 1
fi

REMOVE_DATA=0
eval set -- "${options}"
while [ $# -gt 0 ] ; do
   case "$1" in
      -r | --remove-data)
         REMOVE_DATA=1
         ;;
      -h | --help)
         usage 0
         ;;
      -v | --version)
         version
         ;;
      --)
         shift
         break
         ;;
      *)
         # This should not happen: wrong getopt parameters, or missing case?
         echo >&2 "INTERNAL ERROR: Unhandled option $1!"
         exit 1
         ;;
  esac
  shift
done
if [ $# -ne 1 ] ; then
   usage 1
fi

NODE_ID="$1"
if [[ ! "${NODE_ID}" =~ ^[0-9]+$ ]] ; then
   echo >&2 "ERROR: Invalid Node ID ${NODE_ID}!"
   exit 1
fi
if [ "${NODE_ID}" -lt 1 ] || [ "${NODE_ID}" -gt 9999 ] ; then
   echo >&2 "ERROR: Invalid number for Node ID: ${NODE_ID}!"
   exit 1
fi

# ====== Remove user ========================================================
user="node${NODE_ID}"
echo -e "\x1b[34m$(date +"%Y-%m-%d %H:%M:%S") Deleting user ${user} ...\x1b[0m"

if getent passwd "${user}" >/dev/null 2>&1; then
   echo "Deleting user ${user} ..."
   sudo userdel -r -f "${user}" || true
fi
if getent group "${user}" >/dev/null 2>&1; then
   echo "Deleting group ${user} ..."
   sudo groupdel "${user}" || true
fi
if [ ! -v SUDO_USER ] || [ "${SUDO_USER}" == "" ] ; then
   rm -f ~/keys/"${user}".pub ~/keys/"${user}".pub.new
else
   rm -f /home/"${SUDO_USER}"/keys/"${user}".pub \
         /home/"${SUDO_USER}"/keys/"${user}".pub.new
fi
if [ -d "/var/hipercontracer/data/${user}" ] ; then
   if [ ${REMOVE_DATA} -eq 1 ] ; then
      rm -rf "/var/hipercontracer/data/${user}"
   else
      echo "Keeping the data directory /var/hipercontracer/data/${user}, since data removal is not requested!"
      # The node user is not existing anymore; set ownership to "root" instead:
      sudo chown -R root:root "/var/hipercontracer/data/${user}"
   fi
fi

echo -e "\x1b[34m$(date +"%Y-%m-%d %H:%M:%S") Done.\x1b[0m"
