:

FD="$1"
DIR="$2"

KEY_FILE="$DIR/yubipass.key"

MSG='Enter Yubikey PIN:'

stty -echo <&"$FD"

if [ ! -e "$KEY_FILE" ]
then	echo 1>&"$FD"
	echo -n "$MSG" 1>&"$FD"

	# The 'postgres' operating system user must have permission to
	# access the Yubikey device.
	# Use -passin file:PIN_FILE to supply the PIN from a file

	openssl rand -hex 32 |
	xxd -plain -cols 999 |
	openssl rsautl -engine pkcs11 -keyform engine -encrypt \
		-inkey 0:3 -passin fd:"$FD" -out "$KEY_FILE" 2>&1 |
	grep -v '^engine "pkcs11" set\.$'

	# Warn the user to save the passphrase in a safe place
	cat 1>&"$FD" <<END


WARNING:  The Yubikey can be locked and require a reset if too many pin
attempts fail.  It is recommended to run this command manually and save
the passphrase in a secure location for possible recovery.
END

fi

echo 1>&"$FD"
echo -n "$MSG" 1>&"$FD"

openssl rsautl -engine pkcs11 -keyform engine -decrypt \
		-inkey 0:3 -passin fd:"$FD" -in "$KEY_FILE" 2>&1 |
grep -v '^engine "pkcs11" set\.$'

stty echo <&"$FD"

exit 0
