#!/bin/bash

function prepcert() {
httpdconfdir=/etc/httpd/conf
if [ -e /etc/apache2 ]; then
httpdconfdir=/etc/apache2
fi
while true; do
if [ ! -z "$domainname" ]; then
break
fi
while true; do
if [ "$bit" != "1024" -a "$bit" != "2048" ]; then
echo "Normally certificates are created with a 1024 key, but you might"
echo "want to create a 2048 bit certificate, particularly for"
echo "GeoTrust EV certificates"
echo
echo -n "Key size for this certificate? [1024/2048] "
read bit
else
break
fi
done
echo "SSL Domain Name = ? "
read domainname
done

# confirm if this is a rapidssl cert
echo "will the cert be issued by RapidSSL? y/(n)"
read rapidssl
echo
echo
if [ -z "$rapidssl" ]; then
rapidssl=n
fi

# Create the private key and certificate signing request directories
mkdir -p $httpdconfdir/ssl.key/
mkdir -p $httpdconfdir/ssl.csr/
mkdir -p $httpdconfdir/ssl.crt/

# Create your private key file.  You need to make sure the noone gets a copy of this.
if [ ! -e $httpdconfdir/ssl.key/$domainname.key ]; then
    openssl genrsa -out $httpdconfdir/ssl.key/$domainname.key $bit
    chmod 0600 $httpdconfdir/ssl.key/$domainname.key
fi
# add a -des3 option to the above command if you want to use a password with your key

if [ ! -e $httpdconfdir/ssl.csr/$domainname.csr ]; then
    # Create your certificate signing request.  This is what you'll send out to get your certificate.
    openssl req -new -key $httpdconfdir/ssl.key/$domainname.key -out $httpdconfdir/ssl.csr/$domainname.csr
    # the 'common name' must match your domain name
    # Leave the challenge password blank (press Enter)
fi

# create a self signed certificate for now.  You will overwrite this
# certificate with the one your SSL provider issues you
if [ ! -e $httpdconfdir/ssl.crt/$domainname.crt ]; then
    openssl x509 -req -days 3650 -in $httpdconfdir/ssl.csr/$domainname.csr -signkey $httpdconfdir/ssl.key/$domainname.key -out $httpdconfdir/ssl.crt/$domainname.crt
fi

# Double check your input:
openssl req -noout -text -in $httpdconfdir/ssl.csr/$domainname.csr

# Download the RapidSSL CA Bundle
if [ ! -e $httpdconfdir/ssl.key/RapidSSL_CA_bundle.pem ] && [ "$rapidssl" = "y" ]; then
 wget -q -O - http://downloads.rimuhosting.com/RapidSSL_CA_bundle.pem >  $httpdconfdir/ssl.crt/RapidSSL_CA_bundle.pem
fi

# save the conf settings for when we get the cert
echo "
export domainname=$domainname
export httpdconfdir=$httpdconfdir
" > /root/sslorderdetails
cat $httpdconfdir/ssl.key/$domainname.key
cat $httpdconfdir/ssl.csr/$domainname.csr
echo Common Name = $domainname


echo "You will need to add this to your SSL-enabled VirtualHost:
SSLEngine On
SSLCertificateFile $httpdconfdir/ssl.crt/$domainname.crt
SSLCertificateKeyFile $httpdconfdir/ssl.key/$domainname.key"
if  [ "$rapidssl" = "y" ]; then
echo "SSLCACertificateFile $httpdconfdir/ssl.crt/RapidSSL_CA_bundle.pem"
fi
}
prepcert


