#!/bin/bash
# Use KMS + OpenSSL to encrypt data files from a directory and upload to S3

function kms_encrypt() {
  key_alias=$1
  data_directory=$2
  mkdir -p output
  mkdir -p tmp
  mkdir -p ${data_directory}
  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

  openssl rand -base64 128 -out tmp/${key_alias}.key # Generate a random key

  # Encrypt files using the random ssl key
  for fullname in ${data_directory}/* ; do
    if [ "${fullname}" = "${data_directory}/*" ] ; then
      echo "No files found in ${data_directory} directory... exiting" >&2
      exit 1
    fi
    filename=$(basename "${fullname}")
    openssl enc -aes-256-cbc -salt -in ${data_directory}/${filename} -out output/${filename}.enc -pass file:./tmp/${key_alias}.key
  done

  keyblob=`cat tmp/${key_alias}.key`
  aws kms encrypt --key-id alias/${key_alias} --plaintext "${keyblob}" --query CiphertextBlob --output text ${aws_options} | base64 --decode > output/${key_alias}.kmsenc
  rm -f tmp/${key_alias}.key # Toss the random key for security

  # Copy encrypted files to S3
  aws s3 cp output s3://tw-kmsenc/${key_alias} --recursive --exclude "*" --include "*.kmsenc" --include "*.enc" ${aws_options}
}


AWS_PROFILE_NAME=""
DATA_DIRECTORY=${DATA_DIRECTORY:-input}
function usage() {
  echo "Encrypt a directory of files using KMS+openssl and upload them to S3" >&2
  echo "kms-encrypt.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 with files to encrypt (default: input)" >&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 ":ha:d:p:" opt; do
  case $opt in
    h)
      usage
      exit 0
      ;;
    a)
      echo "Saving encrypted files for: $OPTARG" >&2
      KEY_ALIAS=${OPTARG}
      ;;
    d)
      echo "Encrypting files in 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_encrypt "${KEY_ALIAS}" "${DATA_DIRECTORY}"
exit 0

