#**********PARABLU INC**********
# Whenever a User saves the certificates 
# The script will copy the Certificates from /var/lib/parablusys/conf/ location to /etc/ssl Paths(Private and Certs)
# The script will also modify and provide the correct path in "default-ssl.conf" to enable the Certificates

mainCRTFile="$1"
keyFile="$2"
dnsname="$3"

if [ ! -z "$4" ]; then
        chainCRTFile="$4"
        chaincrtflag=true

fi
curr_dir=$(pwd)

CONF_PATH="/var/lib/parablusys/conf/"
MAINCRTPATH="SSLCertificateFile /etc/ssl/certs/$mainCRTFile"
if [[ $chaincrtflag == "true" ]]; then
	CHAINFILEPATH="SSLCertificateChainFile /etc/ssl/certs/$chainCRTFile"
fi
KEYFILEPATH="SSLCertificateKeyFile /etc/ssl/private/$keyFile"

enablesite_conf="/etc/apache2/sites-enabled/default-ssl.conf"
cert_path="/etc/ssl/certs"
priv_keypath="/etc/ssl/private"

#This path is for testing
#Comment or Remove the below 3 lines and enable the above lines
#enablesite_conf="$curr_dir"/"default-ssl.conf"
#cert_path="$curr_dir/certs"
#priv_keypath="$curr_dir/private"
SSL_EXEC_FILE="/var/lib/parablusys/conf/ssh_install.sh"

if [ -f $SSL_EXEC_FILE ]; then

	#COPY CERT File
	cp $CONF_PATH/$mainCRTFile $cert_path
	if [[ $chaincrtflag == "true" ]]; then
		cp $CONF_PATH/$chainCRTFile $cert_path
	fi


	#COPY KEY File
	cp $CONF_PATH/$keyFile $priv_keypath



	sed -i '/ServerName/d' $enablesite_conf
	sed -i "/ServerAdmin support@parablu.com/a ServerName $dnsname" $enablesite_conf



	#Remove SSL temporary lines
	sed -i '/SSLCertificate/d' $enablesite_conf

	#Append the certificate Paths in default-ssl.conf file
	if [[ $chaincrtflag == "true" ]]; then
		sed -i "/SSLEngine on/a $CHAINFILEPATH" $enablesite_conf
	fi
	sed -i "/SSLEngine on/a $KEYFILEPATH" $enablesite_conf
	sed -i "/SSLEngine on/a $MAINCRTPATH" $enablesite_conf

	#Restart apache2###
	service apache2 restart

	mv $SSL_EXEC_FILE $SSL_EXEC_FILE-old
fi




















