#!/bin/bash
# Use KMS + OpenSSL to decrypt data files from a directory on S3
set -e

function kms_decrypt() {
  DOWNLOAD_DIR=~/kmsdownload
  TMP_DIR=~/tmp
  key_alias=$1
  data_directory=$2
  mkdir -p ${DOWNLOAD_DIR}
  mkdir -p ${data_directory}
  mkdir -p ${TMP_DIR}
  aws_options=""
  if [ -n "${AWS_PROFILE_NAME}" ] ; then
    aws_options=" --profile ${AWS_PROFILE_NAME} "
  fi
  if [ -n "${AWS_DEFAULT_REGION}" ] ; then
    aws_options="${aws_options} --region ${AWS_DEFAULT_REGION}"
  fi

  if [ -z "${AWS_DEFAULT_REGION}" ] ; then
    AWS_METADATA_HOST="169.254.169.254"
    AWS_DEFAULT_REGION=$(curl -s http://${AWS_METADATA_HOST}/latest/dynamic/instance-identity/document | grep region | awk -F\" '{print $4}')
  fi

  # Download the kms encrypted key and any files encrypted with it
  aws s3 cp "s3://tw-kmsenc/${key_alias}/" ${DOWNLOAD_DIR} --recursive --exclude '*' --include '*.kmsenc' --include '*.enc' ${aws_options}

  aws kms decrypt --ciphertext-blob fileb://${DOWNLOAD_DIR}/${key_alias}.kmsenc --query Plaintext --output text ${aws_options} | base64 --decode > ${TMP_DIR}/${key_alias}.key

  # Use the ssl key to decrypt the original file
  for fullname in ${DOWNLOAD_DIR}/* ; do
    if [ "${fullname}" = "download/*" ] ; then
      echo "No files found in download directory... exiting" >&2
      exit 1
    fi
    filename=$(basename "$fullname")
    extension="${filename##*.}"
    decfilename="${filename%.*}"
    if [ "${extension}" != "enc" ] ; then
      continue;
    fi
    openssl enc -d -aes-256-cbc -in ${DOWNLOAD_DIR}/${filename} -out ${data_directory}/${decfilename} -pass file:${TMP_DIR}/${key_alias}.key
  done

  # Remove the key used to decrypt the file
  rm -f ${TMP_DIR}/${key_alias}.key
}


AWS_PROFILE_NAME=""
DATA_DIRECTORY=${DATA_DIRECTORY:-decrypted}
function usage() {
  echo "Decrypt a directory of files from S3 using KMS/openss" >&2
  echo "kms-decrypt.sh -a OWNER-REPO-ENVIRONMENT -d DATA_DIRECTORY" >&2
  echo "-a OWNER-REPO-ENVIRONMENT       This is the name of the owner, repo, and environment with dashes between" >&2
  echo "-d DATA_DIRECTORY               This is the path to a data directory to store the files (default: decrypted)" >&2
  echo "-p AWS_PROFILE_NAME             This is the name of an AWS profile to use (instead of env vars)" >&2
  echo "-h                              Help menu" >&2
}
while getopts ":hp:a:d:" opt; do
  case $opt in
    h)
      usage
      exit 0
      ;;
    a)
      echo "Decrypting files for: $OPTARG" >&2
      KEY_ALIAS=${OPTARG}
      ;;
    d)
      echo "Decrypting files into directory: $OPTARG" >&2
      DATA_DIRECTORY=${OPTARG}
      ;;
    p)
      echo "Using AWS profile named: $OPTARG" >&2
      AWS_PROFILE_NAME=${OPTARG}
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      ;;
  esac
done
if [ -z $KEY_ALIAS ] ; then
  echo "Missing the OWNER-REPO-ENVIRONMENT setting" >&2
  usage
  exit 1
fi
kms_decrypt "${KEY_ALIAS}" "${DATA_DIRECTORY}"
exit 0
