#!/bin/bash

KEY_NAME="${1:?need a SSHKey name from /me}"
KEY_DIR="${HOME}/.ssh/keys.d"

# check if sshkey exists locally
if [ -e "${KEY_DIR}/${KEY_NAME}" ] ; then
  echo "SSH Key ${KEY_DIR}/${KEY_NAME} already exists locally"
else
  echo "SSH Key ${KEY_DIR}/${KEY_NAME} not found locally"
  echo ">>> Creating it ..."
  ssh-keygen -t ed25519 -f "${KEY_DIR}/${KEY_NAME}" -C "OVH_${KEY_NAME}" -q -N ""
  ./delSSHKey "${KEY_NAME}"
fi
PUBKEY="$( cat "${KEY_DIR}/${KEY_NAME}.pub" )"

# check if KEY_NAME exists into OVH User Account /me
# remote_keyname = "string or empty"
remote_keyname=$( ./ovh-bash get "me/sshKey" | jq --arg v "${KEY_NAME}" -r '.|to_entries[]|select(.value == $v ).value' )

# if remote_keyname exists check if pubkey is matching.
remote_pubkey=$( ./ovh-bash get "me/sshKey/${KEY_NAME}" | jq -r '.key' )
  
# if remote_keyname does not match KEY_NAME = this KEY_NAME is not already uploaded into OVH Account
if [ -z "${remote_keyname}" ] || [ "${remote_pubkey}" != "${PUBKEY}" ] ; then
  echo "SSH Keys does not exists remotely"
  echo ">>> Uploading ${KEY_DIR}/${KEY_NAME} to OVH account"
  HTTP_PAYLOAD='{ "key": "'${PUBKEY}'", "keyName": "'${KEY_NAME}'" }'

  ./ovh-bash post "me/sshKey" "${HTTP_PAYLOAD}" | jq -r 'select(. != null)'

else
  echo "SSH Keys are up-to-date"
fi

exit $?