#!/bin/sh

# This uses the AWS Secrets Manager using the AWS CLI and OpenSSL.

[ "$#" -ne 1 ] && echo "cluster_key_command usage: $0 \"%d\"" 1>&2 && exit 1
# No need for %R or -R since we are not prompting

DIR="$1"
[ ! -e "$DIR" ] && echo "$DIR does not exist" 1>&2 && exit 1
[ ! -d "$DIR" ] && echo "$DIR is not a directory" 1>&2 && exit 1

# File containing the id of the AWS secret
AWS_ID_FILE="$DIR/aws-secret.id"


# ----------------------------------------------------------------------


# Create an AWS Secrets Manager secret?
if [ ! -e "$AWS_ID_FILE" ]
then	# The 'postgres' operating system user must have permission to
	# access the AWS CLI

	# The epoch-time/directory/hostname combination is unique
	HASH=$(echo -n "$(date '+%s')$DIR$(hostname)" | sha1sum | cut -d' ' -f1)
	AWS_SECRET_ID="Postgres-cluster-key-$HASH"

	# Use stdin to avoid passing the secret on the command line
	openssl rand -hex 32 |
	aws secretsmanager create-secret \
		--name "$AWS_SECRET_ID" \
		--description 'Used for Postgres cluster file encryption' \
		--secret-string 'file:///dev/stdin' \
		--output text > /dev/null
	if [ "$?" -ne 0 ]
	then	echo 'cluster key generation failed' 1>&2
		exit 1
	fi

	echo "$AWS_SECRET_ID" > "$AWS_ID_FILE"
fi

if ! aws secretsmanager get-secret-value \
	--secret-id "$(cat "$AWS_ID_FILE")" \
	--output text
then	echo 'cluster key retrieval failed' 1>&2
	exit 1
fi | awk -F'\t' 'NR == 1 {print $4}'

exit 0
