#!/bin/bash
set -euo pipefail

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

if ! (which vault >/dev/null); then
  error "vault is required."
  exit 2
fi

# Require something to be passed to this command
if [ $# -eq 0 ]; then
  error "You need to specify a key name."
  exit 2
fi

# Create a helper script to send STDIN data to ssh-add
HELPER=$(mktemp)
chmod 0700 ${HELPER}
trap "rm ${HELPER}" EXIT

cat -s <<EOF >${HELPER}
#!/bin/bash -eu
export -n DISPLAY
vault read -field=private "secret/ssh-key/\$1" | exec ssh-add -t 3600 -
EOF

for KEY_NAME in $@; do
  fingerprint=$(vault read -field=public "/secret/ssh-key/$1" | ssh-keygen -l -f -)

  # If this key is already in the agent we don't need to do anything
  if (ssh-add -l | grep -q "${fingerprint}"); then
    info "[${KEY_NAME}] Key already present."
    continue
  fi

  # Retrieve key from LastPass
  PWD=$(vault read -field=passphrase "secret/ssh-key/${KEY_NAME}")
  # In case LastPass exitted non-zero we have no password
  if ! [ $? -eq 0 ]; then
    error "[${KEY_NAME}] Unable to get password. Not trying to unlock."
    continue
  fi

  # Fill password to ssh-add utility
  expect <<EOF >/dev/null
spawn ${HELPER} ${KEY_NAME}

expect "Enter passphrase"
send "$PWD\n"

expect "added:" {exit 0} timeout {exit 1}
EOF

  if [ $? -eq 0 ]; then
    info "[${KEY_NAME}] Should be loaded by now."
    vault-patch --log-level=warn secret/ssh-key/${KEY_NAME} last_used=$(date +%Y-%m-%dT%H:%M:%S%z)
  else
    error "[${KEY_NAME}] Was not added successfully."
  fi

done