#!/bin/bash

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

# If we can list the environments there is no need to unlock the database
if (awsenv list >/dev/null 2>&1); then
  echo "Database already unlocked."
  exit 0
fi

# Retrieve key from LastPass
PWD=$(vault read -field=passphrase "/secret/private/awsenv")

# In case Vault exitted non-zero we have no password
if ! [ $? -eq 0 ]; then
  echo "Unable to get password. Not trying to unlock."
  exit 1
fi

# Fill password to ssh-add utility
expect <<EOF >/dev/null
spawn -ignore HUP awsenv unlock
expect "Password: "
send "$PWD\n"
expect "Database unlocked."
expect eof
EOF

# Check whether awsenv was unlocked
if (awsenv list >/dev/null 2>&1); then
  echo "Database unlocked successfully"
  exit 0
else
  echo "Found passphrase but could not unlock database."
  exit 1
fi