#!/bin/bash

# File locations in case you want to modify things
ASTERISK_CONF="/etc/asterisk/http.conf"
APACHE_CONF="/etc/apache2/vhosts.d/1111-default-ssl.conf"
CERTBOT_BIN="/usr/bin/certbot"
CERTBOT_DIR="/etc/certbot/"
CERTBOT_INI="$CERTBOT_DIR/cli.ini";
WEBDIR="/srv/www/htdocs/"



# File Checks
if [[ ! -x $CERTBOT_BIN ]]; then
	echo "  Certbot binary not installed at $CERTBOT_BIN"
	exit 1
fi
if [[ ! -f $CERTBOT_INI ]]; then
	echo "  Certbot config not found at $CERTBOT_INI"
	exit 1
fi
if [[ ! -d $WEBDIR ]]; then
	echo "  Web directory not found at $WEBDIR"
	exit 1
fi

echo
echo "ViciBox Certbot set-up script"
echo

# Make sure Apache is running before attempting certbot setup
service apache2 status >/dev/null 2>&1
if [[ $? -ne 0 ]]; then
	echo "  Apache is not running! Certbot will not work without a running web server."
	echo "  Please start Apache by running 'service apache2 start' and verify that you"
	echo "  can access ViciDial normally through the Fully Qualified Domain Name of this"
	echo "  server. Cerbot will not work until Apache and a FQDN are properly working on"
	echo "  this server. Until then there is no reason to run this script."
	echo
	exit 1
fi

echo
echo "  Please make sure you have a Fully Qualified Domain Name pointed at this server."
echo "  For example, if the FQDN of this server was 'vicibox.vicidial.com' and was"
echo "  properly directed at this server you should be able to log into vicidial at"
echo "  http://vicibox.vicidial.com"
echo
echo
echo -n "  What is your EMail address : "
read EMAIL
echo -n "  What is your Fully Qualified Domain Name (FQDN) : "
read FQDN

# Verify that the FQDN comes back to this server
SERVERIP=`dig +short $FQDN`
REMOTEIP=$(wget http://www.vicidial.org/yourip.php -q -O -)
if [[ "$SERVERIP" != "$REMOTEIP" ]]; then
	echo "  The Server IP ($SERVERIP) and the detected remote IP ($REMOTEIP)" 
	echo "  do not match! This will cause certbot and the SSL certificate to fail"
	echo "  authentication. Please double check that your FQDN matches your IP."
	echo
	echo "  Do you want to continue with the Certbot setup? (N/y) : "
	read PROMPT
	if [ "${PROMPT,,}" != "y" ]; then
		exit 1
	fi
fi

echo
echo
echo "   E-Mail : $EMAIL"
echo "     FQDN : $FQDN"
echo
echo -n "  Do you want to continue using the above settings? (N/y) : "
read PROMPT

if [ "${PROMPT,,}" == "y" ]; then
	echo -n "    Updating /etc/certbot/cli.ini... "
	sed -i "/email =/c\\email = $EMAIL" $CERTBOT_INI
	sed -i "/domains =/c\\domains = $FQDN" $CERTBOT_INI
	sed -i "s+# webroot-path = /srv/www/htdocs+webroot-path = $WEBDIR+" $CERTBOT_INI
	echo "done."
	echo
fi



echo -n "  Do you want to run certbot now to generate a certificate? (N/y) : "
read PROMPT
if [ "${PROMPT,,}" == "y" ]; then
	$CERTBOT_BIN --webroot certonly
	
	if [ $? != 0 ]; then
		echo
		echo "  CertBot was unable to verify your FQDN reaches this server and was unable"
		echo "  to generate a valid SSL certificate. Please check your firewall settings,"
		echo "  DNS entries, and Apache for any possible issues. You can either re-run this"
		echo "  script of run certbot --webroot certonly to test if the issue is resolved."
		exit 1;
	else
		echo
		echo "  Certbot successfully authenticated and generated an SSL certificate."
	fi
else
	echo
	echo "  Please run 'certbot --webroot certonly' and verify that you can successfully"
	echo "  generate an SSL certificate. Once an SSL certificate generated, you will need"
	echo "  to modify the following configs :"
	echo "    Apache   : $APACHE_CONF"
	echo "    Asterisk : $ASTERISK_CONF"
	exit
fi

# Check to see if we did the run on the staging server, and prompt to move to production if so
if [[ `cat /etc/certbot/cli.ini | grep -v '#' | grep 'server =' | grep 'staging'` ]]; then
	echo
	echo "  Certbot was able to successfully verify your FQDN and issue your SSL" 
	echo "  certificate but this was done on the STAGING server. This is used only for"
	echo "  testing your configuration and is unusable for production. "
	echo
	echo -n "  Do you want to enable the production SSL server? (N/y) : "
	read PROMPT
	
	if [ "${PROMPT,,}" == "y" ]; then
		echo
		echo -n "    Enabling production certbot server... "
		sed -i "s/acme-staging.api.letsencrypt.org/acme-v01.api.letsencrypt.org/" $CERTBOT_INI
		echo "done."
		echo
		echo -n "  Do you want to re-run certbot to generate the SSL certificate now? (N/y) : "
		read PROMPT
		
		if [ "${PROMPT,,}" == "y" ]; then
			echo "    Generating production SSL certificate... "
			rm -rf $WEBDIR/.well-known
			rm -rf $CERTBOT_DIR/account
			rm -rf $CERTBOT_DIR/keys
			rm -rf $CERTBOT_DIR/archive
			rm -rf $CERTBOT_DIR/live
			rm -rf $CERTBOT_DIR/renewal
			$CERTBOT_BIN --webroot certonly
			
			if [ $? != 0 ]; then
				echo "done."
				echo
				echo "  Certbot encountered an error generating a valid SSL certificate."
				echo "  Please check your firewall settings, DNS entries, Apache, and the"
				echo "  certboat logs for any possible issues."
				exit 1
			fi
			echo "  done."
		fi
	else
		echo
		echo "  Please enabled the production server by editing $CERTBOT_INI"
		echo "  Once this is done, you'll need to re-run certbot to generate the"
		echo "  production SSL certificate by running certbot --webroot certonly"
		echo
		exit 0
	fi
fi

# Tie apache to our certbot SSL if things went well-known
echo
echo -n "  Do you want to enable the new SSL certificate in Apache/Asterisk? (N/y) : "
read PROMPT

if [ "${PROMPT,,}" == "y" ]; then
	
	if [[ -f $ASTERISK_CONF ]]; then
		echo
		echo -n "    Enabling SSL certificate in Asterisk... "
		sed -i "/tlscertfile=/c\\tlscertfile=/etc/certbot/live/$FQDN/cert.pem" $ASTERISK_CONF
		sed -i "/tlsprivatekey=/c\\tlsprivatekey=/etc/certbot/live/$FQDN/privkey.pem" $ASTERISK_CONF
		echo "done."
		if [ `pgrep "^asterisk$" |wc -l` -gt 0 ]; then
			echo -n "    Reloading Asterisk http module... "
			/usr/sbin/rasterisk -x 'module reload http'
			echo "done."
		fi
	else
		echo "    Asterisk config file not found at $ASTERISK_CONF"
	fi
	
	if [[ -f $APACHE_CONF ]]; then
		echo -n "    Enabling SSL certificate in Apache... "
		sed -i "/SSLCertificateFile/c\\\tSSLCertificateFile /etc/certbot/live/$FQDN/cert.pem" $APACHE_CONF
		sed -i "/SSLCertificateKeyFile/c\\\tSSLCertificateKeyFile /etc/certbot/live/$FQDN/privkey.pem" $APACHE_CONF
		sed -i "/SSLCACertificateFile/c\\\tSSLCACertificateFile /etc/certbot/live/$FQDN/fullchain.pem" $APACHE_CONF
		echo "done."
		service apache2 status >/dev/null 2>&1
		if [[ $? -eq 0 ]]; then
			echo -n "    Reloading apache configuration... "
			/sbin/service apache2 restart
			echo "done."
		fi
	else
		echo "    Apache config file not found at $APACHE_CONF"
	fi
	
else
	echo
	echo "  You will need to enable the SSL certificates in the following files:"
	echo "    Apache   : $APACHE_CONF"
	echo "    Asterisk : $ASTERISK_CONF"
	echo
	echo "  done."
fi

echo
echo "  The SSL certificate is done. The SSL certificate is valid for up to 90"
echo "  days. After that time it will need to be re-generated by running :"
echo "    certbot --webroot renew"
echo

# Add certbot to the cron only if it's not already in there somewhere
if [[ `crontab -l | grep certbot | wc -l` -gt 0 ]]; then
	echo "  It is recommended to have the cert generation done weekly via a crontab"
	echo "  entry like this:"
	echo "    0 0 1 * * $CERTBOT_BIN -n --webroot renew >/dev/null 2>&1"
	echo "    10 0 * * 0 /usr/sbin/apache2ctl -k graceful >/dev/null 2>&1"
	echo '    11 0 * * 0 /usr/sbin/asterisk -rx "module reload http" >/dev/null 2>&1'
	echo
	echo -n "  Do you want to add this to the crontab now? (N/y) : "
	read PROMPT
	
	if [ "${PROMPT,,}" == "y" ]; then
		echo -n "    Adding Certbot to crontab... "
		crontab -l > /tmp/rootcronold
		sed -e '1,3d' < /tmp/rootcronold > /tmp/rootcron
		echo '' >> /tmp/rootcron
		echo '### Check letsencrypt.org and renew cert if needed and reload config' >> /tmp/rootcron
		echo "0 0 * * 0 $CERTBOT_BIN -n --webroot renew >/dev/null 2>&1" >> /tmp/rootcron
		echo '10 0 * * 0 /usr/sbin/apache2ctl -k graceful >/dev/null 2>&1' >> /tmp/rootcron
		echo '11 0 * * 0 /usr/sbin/asterisk -rx "module reload http" >/dev/null 2>&1' >> /tmp/rootcron
		crontab /tmp/rootcron
		echo "done."
	fi
fi

echo
echo "  The Certbot SSL set-up is complete!"
echo
echo "  If this is a telephony server you will need to modify the 'Web Socket URL'"
echo "  field for this server under the Admin --> Servers section. It will need to be"
echo "  changed to :"
echo "    wss://$FQDN:8089/ws"
echo
echo "  You will also need to modify the 'webRTC' template under the Admin --> Templates"
echo "  section. You want to change the following options under the "
echo "  'Template Contents' :"
echo "    dtlscertfile=/etc/certbot/live/$FQDN/cert.pem"
echo "    dtlsprivatekey=/etc/certbot/live/$FQDN/privkey.pem"
echo
echo "  If this is a web server, you can force all connections to SSL by editing"
echo "  /etc/apache2/vhosts.d/1111-default.conf and uncommenting the rewrite section."
