#!/bin/bash -e

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

function usage {
  echo 'Usage:' $(basename "$0") '-a <alias> -p <plaintext>'
  echo '   or: echo <plaintext> |' $(basename "$0") '-a <alias>'
}

while getopts a:p:h FLAG; do
  case $FLAG in
    a)
      alias=$OPTARG
      ;;
    p)
      plaintext=$OPTARG
      ;;
    h)
      usage
      exit
      ;;
    ?)
      echo
      usage
      exit 1
      ;;
  esac
done

shift "$((OPTIND - 1))"

[ "$alias" == "" ] && {
  (>&2 echo 'Error: Missing KMS Key Alias');
  echo;
  usage;
  exit 1;
}

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

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

aws kms encrypt --key-id "$alias" --plaintext "$plaintext" --query CiphertextBlob --output text
