#!/usr/bin/bash

##
# @file
# @ingroup ngcbGenSshKeys
# @copyright
#   SPDX-FileCopyrightText: 2026 European Southern Observatory (ESO)
#   SPDX-License-Identifier: LGPL-3.0-only
#

#************************************************************************
#   NAME
#     ngcbGenSshKeys - generate ssh keys for NGC
#
#   SYNOPSIS
#     ngcbGenSshKeys [-d] [-t <tag>] [-h]
#
#   DESCRIPTION
#     Generates a pair of ssh keys of type DSA in $HOME/.ssh.
#     It also adds the public key to $HOME/.ssh/authorized_keys.
#     In case keys are already present, they will not be regenerated unless
#     the -d option is specified.
#
#   OPTIONS
#     -d       - Delete old files if they exist
#
#     -t <tag> - Tag to be appended to the comment in the public key file.
#
#     -h       - Show quick help.
#
#   FILES
#     ngc_key
#     ngc_key.pub
#     authorized_keys
#
#------------------------------------------------------------------------
#

USAGE="usage: `basename $0` [-d] [-t <tag>] [-h]"
DELETE_OLD=false
COMMENT="NGC_key"
SSH_DIR=$HOME/.ssh
KEYS_OK=false

# Parse command line options
while getopts hdt: OPTION ; do
  case "$OPTION" in
    h) echo $USAGE ; exit 0 ;;
    d) DELETE_OLD=true ;;
    t) COMMENT+="_$OPTARG";;
    \?) echo $USAGE ; exit 1 ;;
  esac
done

echo "SSH key generator ($COMMENT)"
if [ $DELETE_OLD == "false" ]
then
    echo "checking for existing keys"
    if [ -f $SSH_DIR/ngc_key ] && [ -f $SSH_DIR/ngc_key.pub ]
    then
        KEYS_OK=true
    else
        KEYS_OK=false
        echo "key files missing"
    fi
fi

if [ $DELETE_OLD == "true" ] || [ $KEYS_OK == false ]
then
    echo "removing old files"
    rm -f $SSH_DIR/ngc_key
    rm -f $SSH_DIR/ngc_key.pub
    
    echo "generating keys in directory $SSH_DIR"
    ssh-keygen -t rsa -f $SSH_DIR/ngc_key -N "" -C $COMMENT
fi

if [ -f $SSH_DIR/authorized_keys ]
then
    echo "updating file $SSH_DIR/authorized_keys"

    # Remove line with NGC key
    sed -i '/NGC_key/d' $SSH_DIR/authorized_keys
	
    # Append the new NGC key
    cat $SSH_DIR/ngc_key.pub >> $SSH_DIR/authorized_keys
else
    echo "creating file $SSH_DIR/authorized_keys"
    cp $SSH_DIR/ngc_key.pub $SSH_DIR/authorized_keys
fi

# Make sure the file has the correct permissions
chmod 600 $SSH_DIR/authorized_keys

#
# ___oOo___
