:

# This uses the AWS Secrets Manager using the AWS CLI

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

DIR="$1"

# File containing the passphrased encrypted with the PIV_SLOT's public key
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

	TIME=$(date '+%s')
	# The directory/time combination is unique
	HASH=$(echo -n "$DIR$TIME" | sha1sum | awk '{print $1}')
	AWS_SECRET_ID="Postgres-passphrase-$HASH"

	RANDKEY=$(openssl rand -hex 32 | xxd -plain -cols 999)

	# Passing the secret on the command line could be insecure.
	aws secretsmanager create-secret \
		--name "$AWS_SECRET_ID" \
		--description 'Used for Postgres cluster file encryption' \
		--secret-string "$RANDKEY" \
		--output text > /dev/null
	[ "$?" -ne 0 ] && exit 1

	echo "$AWS_SECRET_ID" > "$AWS_ID_FILE"
fi

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

exit 0
