#!/usr/bin/bash
#
# Generate repeatable ssh host keys using the system authseed
#

KEYDIR=/etc/ssh
KEYTYPES=(
  #dsa:1024
  rsa:2048
  ecdsa:NIST256p
  ed25519:256
)

# Make sure we can find mk-xxxxx-key
PATH=$PATH:/usr/libexec/ng-server-config

#  For each key type
for x in "${KEYTYPES[@]}"; do

	# Skip any commented key types
	[ "${x:0:1}" == "#" ] && continue

	# Split the entry into key type and size (or curve)
	TYPE=${x%%:*}
	SIZE=${x##*:}

	# Path to the private key file
	KEY="${KEYDIR}/ssh_host_${TYPE}_key"

	# Only generate if there is no key file, the key file is too small, or --force was passed
	if [ ! -s "${KEY}" ] || [[ -f "${KEY}" && $(stat -c %s ${KEY}) -le 100 ]] || [ "$1" == "--force" ]; then

		KEYGEN="ng-mk-${TYPE}-key"

		if command -v ${KEYGEN} >/dev/null; then

			# Generate Private Key
			touch ${KEY}
			chown root:ssh_keys ${KEY}
			chmod 0640 ${KEY}
			${KEYGEN} sshd::system::${TYPE}-${SIZE} ${SIZE} >${KEY}

			# Extract Public Key
			touch ${KEY}.pub
			chmod 0644 ${KEY}.pub
			ssh-keygen -f ${KEY} -y >${KEY}.pub

		fi
	fi

done

