#!/bin/bash

# Copyright (C) 2018 by Mike Gabriel <mike.gabriel@it-zukunft-schule.de>

# This script 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 2 of the License, or
# (at your option) any later version.
#
# This script 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, write to the
# Free Software Foundation, Inc.,
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.

if [ $(id -u) -gt 0 ]; then
	echo "ERROR: This script has to run as super-user root."
	exit 1
fi

set -e

NULL=""
E2G_SSLDIR=/etc/e2guardian/ssl/
E2G_GENCERTDIR=/var/lib/e2guardian/generatedcerts

mkdir -p ${E2G_SSLDIR}
chmod 0755 ${E2G_SSLDIR}
chown root:root ${E2G_SSLDIR}

# Create fake CA
openssl genrsa 4096 > ${E2G_SSLDIR}/ca.key
chmod o-rwx ${E2G_SSLDIR}/ca.key
chown root:e2guardian ${E2G_SSLDIR}/ca.key

openssl req -new			\
            -x509			\
            -days 3650			\
            -sha256			\
            -key ${E2G_SSLDIR}/ca.key	\
            -out ${E2G_SSLDIR}/ca.crt	\
            ${NULL}

# Convert to DER format
openssl x509 -in ${E2G_SSLDIR}/ca.crt	\
             -outform DER		\
             -out ${E2G_SSLDIR}/ca.der	\
             ${NULL}

# create e2guardian's secret key
openssl genrsa 4096 > ${E2G_SSLDIR}/e2guardian.key
chmod o-rwx ${E2G_SSLDIR}/e2guardian.key
chown root:e2guardian ${E2G_SSLDIR}/e2guardian.key


# Create generatedcerts dir...
mkdir -p ${E2G_GENCERTDIR}
chown e2guardian:e2guardian ${E2G_GENCERTDIR}
chmod go-rwx ${E2G_GENCERTDIR} -Rfv

echo "###"
echo "### All preparations done..."
echo "###"
echo "### Now read /usr/share/doc/e2guardian/ssl_mitm ..."
echo "###"
echo "### and set..."
echo
echo "/etc/e2guardian/e2guardian.conf:"
echo
echo '```'
echo "enablessl = on"
echo "cacertificatepath = '${E2G_SSLDIR}/ca.crt'"
echo "caprivatekeypath = '${E2G_SSLDIR}/ca.key'"
echo "certprivatekeypath = '${E2G_SSLDIR}/e2guardian.key'"
echo "generatedcertpath = '${E2G_GENCERTDIR}'"
echo '```'
echo
echo "###"
echo "### and set..."
echo
echo "/etc/e2guardian/e2guardianf1.conf:"
echo
echo '```'
echo "sslmitm = on"
echo '```'
echo
echo
echo "Finally, copy '${E2G_SSLDIR}/ca.crt' and 'ca.der' to TJENER as"
echo "/etc/debian-edu/www/E2Guardian-ca.crt and E2Guardian-ca.der."
echo
