#!/bin/sh
	
ROOT_UID=0   # Root has $UID 0.

if [ "$UID" -eq "$ROOT_UID" ] ; # Will the real "root" please stand up?
then
echo "Root OK"
else
echo "You are just an ordinary user (you must be root to run this script)."
exit 0
fi

echo "Enter the path and filename to your apache"
echo -n "ssl conf file [ default /usr/local/apache2/conf/ssl.conf ] : "
read SSLCONF
if [ -z $SSLCONF ] ; then
# http.conf in apache 1.3x and ssl.conf in apache 2.0
SSLCONF=/usr/local/apache2/conf/ssl.conf
fi
if [ ! -f $SSLCONF ]
then

echo "This file [ $SSLCONF ] does not exist please rerun and type in correct location"
exit 0
fi
echo $SSLCONF
echo "Enter the path you want to place the..."
echo -n "ssl/ssl.crt and ssl/ssl.key dirs in [ /usr/local/apache2/conf ] : "
read SSLDIR
if [ -z $SSLDIR ] ; then
SSLDIR=/usr/local/apache2/conf
fi
if [ ! -d $SSLDIR ]
then
echo "this directory [ $SSLDIR ] doesn't exist please rerun script and put a correct entry in"
exit 0
else
echo $SSLDIR
mkdir -p $SSLDIR/ssl/ssl.crt
mkdir -p $SSLDIR/ssl/ssl.key
fi
HOSTNAME=`hostname`
HOSTNAME="www.jamesmcdonald.id.au"
# try to get path to openssl by searching path...
OPENSSL=`which openssl 2> /dev/null` # | /path/to/openssl
if [ -z $OPENSSL ]
then
echo -n "Please enter the path to openssl binary [/usr/local/openssl]: "
read OPENSSL
if [ ! -e $OPENSSL ] ; then
echo "Incorrect Path Please restart script and enter correct path to openssl"
exit 0
else
# only needs setting when it aint in path
export PATH=$PATH:$OPENSSL
fi
fi
				
cd ~/
echo making key directory
mkdir certmake 2> /dev/null
cd certmake
rm -rf *
openssl genrsa 1024 > ${HOSTNAME}.key
openssl req -new -key ${HOSTNAME}.key -out ${HOSTNAME}.csr
openssl req -x509 -key ${HOSTNAME}.key -in ${HOSTNAME}.csr -out ${HOSTNAME}.crt -days 365
cp ${HOSTNAME}.key ${SSLDIR}/ssl/ssl.key/ssl.key
cp ${HOSTNAME}.crt ${SSLDIR}/ssl/ssl.crt/ssl.crt
echo $SSLDIR/ssl/
chmod 400 ${SSLDIR}/ssl -Rv

cp ${SSLCONF} "${SSLCONF}.`date`.ca-install-BACKUP" # make backup copy
CONFIGTMP=/tmp/configtmp$$
CRTCONFIG=${SSLDIR}/ssl/ssl.crt/ssl.crt
KEYCONFIG=${SSLDIR}/ssl/ssl.key/ssl.key
# normally sed uses s/rexep/replacement text/ 
# but because CRT & KEY vars have / we use ";" as the delimiter
sed -e "s;^SSLCertificateFile.*;SSLCertificateFile $CRTCONFIG;" < ${SSLCONF} > $CONFIGTMP
sed -e "s;^SSLCertificateKeyFile.*;SSLCertificateKeyFile $KEYCONFIG;" < $CONFIGTMP > ${SSLCONF}
	


