#!/bin/bash

hash aws &>/dev/null || {
  (>&2 echo 'Error: AWS CLI not found on PATH');
  exit 1;
}

function usage {
  echo 'Usage:' $(basename "$0") '-s <secret>'
  echo '   or: echo <secret> |' $(basename "$0")
}

while getopts s:h FLAG; do
  case $FLAG in
    s)
      secret_base64=$OPTARG
      ;;
    h)
      usage
      exit
      ;;
    ?)
      echo
      usage
      exit 1
      ;;
  esac
done

shift "$((OPTIND - 1))"

# if no <secret> is passed as an argument, try getting it from stdin if we're
# not interactive
[ "$secret_base64" == "" ] && [ ! -t 0 ] && {
  secret_base64=$(cat -);
}

[ "$secret_base64" == "" ] && {
  (>&2 echo 'Error: Missing Secret');
  echo;
  usage;
  exit 1;
}

aws kms decrypt --profile sysmail --ciphertext-blob fileb://<(echo -n "$secret_base64" | base64 --decode) --query Plaintext --output text
