#!/bin/bash
set -euo pipefail

source "${HOME}/bin/script_framework.sh"

keyname=${1:-}

[ -z "${keyname}" ] && fail "Key name not provided"

if [ ! -e "/tmp/${keyname}" ]; then
	vault read -field=private "/secret/ssh-key/${keyname}" >"/tmp/${keyname}"
	chmod 0600 \
		"/tmp/${keyname}"
fi

function cleanup() {
	rm -f \
		"/tmp/${keyname}"
}
trap cleanup EXIT

OLDPASS=$(vault read -field=passphrase "/secret/ssh-key/${keyname}") || fail "Unable to retrieve old passphrase"
NEWPASS=$(password get -l 64) || fail "Unable to generate a new passphrase"

[ -z "${NEWPASS}" ] && fail "Unable to generate a new passphrase"

ssh-keygen -p -P "${OLDPASS}" -N "${NEWPASS}" -f "/tmp/${keyname}" || fail "Was not able to modify key with new passphrase"
vault-patch --log-level=warn "/secret/ssh-key/${keyname}" \
	passphrase="${NEWPASS}" \
	private=@/tmp/${keyname} \
	passphrase_changed=$(date +%Y-%m-%dT%H:%M:%S%z)

echo "Everything was fine, key has been changed."