#! /bin/bash
#
# Compability script to create double encrypted key with 'openssl'.
# * NOTE * Should not be used for new installs
#
# Written by Markus Nass <generalstone@gmx.net>
# Modified by David Härdeman <david@hardeman.nu>

set -e

if [ ! -x /usr/bin/openssl ]; then
	echo "Please install the 'openssl' package."
	exit 1
fi

if [ -z "$1" ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
	echo "Usage: $0 <key> [<dsaparam>]"
	exit 1
fi

echo "*NOTE* This key setup should NOT be used for new installs *NOTE*"
echo -n "Are you sure you want to continue? (y/n): "
read -n1 REPLY
echo
if [ "$REPLY" != "y" ]; then
	exit 1
fi

if [ -n "$2" ]; then
	DSAPARAM="$2"
else
	DSAPARAM=$(tempfile)
	RAND=$(tempfile)
	dd if=/dev/urandom of="$RAND" bs=1M count=4
	openssl dsaparam -out "$DSAPARAM" -rand "$RAND" 4096
	rm -f "$RAND"
fi

rc=1
DSAKEY=$(tempfile)
RAND=$(tempfile)
dd if=/dev/urandom of="$RAND" bs=1M count=4
if openssl gendsa -aes256 -out "$DSAKEY" -rand "$RAND" "$DSAPARAM" && \
   openssl enc -aes256 -e -salt -in "$DSAKEY" -out "$1"; then
   	rc=0
fi
rm -f "$RAND"
rm -f "$DSAKEY"

if [ -z "$2" ]; then
	rm -f "$DSAPARAM"
fi

exit $rc
