#!/bin/bash
# automate letsencrypt certificate generation and authentication
# Copyright (C) 1993-2993 Hugo Mangeart

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

set -ve
trap "cp /tmp/{mediaserver-msuser.conf,skyreach.conf,msmonitor.conf} /etc/nginx/sites-available/; nginx -t && service nginx reload; exit 255" ERR
source /root/envsetup/global-conf.sh
LE_DIR="/etc/letsencrypt/live/"

# GET LETSENCRYPT
sudo apt-get update
sudo apt-get install software-properties-common
sudo add-apt-repository ppa:certbot/certbot -y
sudo apt-get update
sudo apt-get install python-certbot-nginx

cd /etc/nginx/sites-available/

# BACKUP
cp mediaserver-msuser.conf skyreach.conf msmonitor.conf /tmp/

# PREPARE LETSENCRYPT REQUEST STRING
# ALTER NGINX CONF TO ACCEPT CLEAR HTTP
# (DEACTIVATE errexit BECAUSE USING FAILING COMMANDS)
set +e
DOMAIN_STRING="${MS_SERVER_NAME}" && \
	sed -i s/rewrite/#rewrite/ mediaserver-msuser.conf
[ -n "${CM_SERVER_NAME}" ] && \
	DOMAIN_STRING="${DOMAIN_STRING},${CM_SERVER_NAME}" && \
	sed -i s/rewrite/#rewrite/ skyreach.conf
[ -n "${MONITOR_SERVER_NAME}" ] && \
	DOMAIN_STRING="${DOMAIN_STRING},${MONITOR_SERVER_NAME}" && \
	sed -i s/rewrite/#rewrite/ msmonitor.conf

set -e
nginx -t && \
	service nginx reload

# ASKS FOR CERTS TO LETSENCRYPT
mkdir -p /tmp/letsencrypt
certbot certonly \
	--webroot --webroot-path /tmp/letsencrypt \
	--domains "${DOMAIN_STRING}" \
	--email "${EMAIL_ADMINS}" \
	--rsa-key-size 4096

# RE-REDIRECT HTTP to HTTPS
sed -i s/#rewrite/rewrite/ mediaserver-msuser.conf skyreach.conf msmonitor.conf

# CHECK CERTS PRESENCE & EDIT NGINX CONFIG
# (DEACTIVATE errexit BECAUSE USING FAILING COMMANDS)
set +e
[ -f ${LE_DIR}/${MS_SERVER_NAME}/fullchain.pem ] && \
	sed -i s/#ssl_certificate/ssl_certificate/g mediaserver-msuser.conf

[ -f ${LE_DIR}/${CM_SERVER_NAME}/fullchain.pem ] && \
	sed -i s/#ssl_certificate/ssl_certificate/g skyreach.conf

[ -f ${LE_DIR}/${MONITOR_SERVER_NAME}/fullchain.pem ] && \
	sed -i s/#ssl_certificate/ssl_certificate/g msmonitor.conf

# RELOAD NGINX IF CONF IS CORRECT
nginx -t && \
	service nginx reload
rm /tmp/{mediaserver-msuser.conf,skyreach.conf,msmonitor.conf}
cd -
