#!/bin/bash
#
# Set up Firefox to accept the default ssl certificate created by debian-edu-config
# for new users.
#
# Author: Oded Naveh
# Date:   03-06-2009
#
# TODO:
# Update existing profiles and users?
# Figure out how to calculate the last field of the override string.
#			(hint: the database key obtained from NSS).


set -e
. /etc/debian-edu/config	# get Debian-Edu PROFILE

echo "info: Running $0"


# On main server read local certificate

if [[ $PROFILE =~ Main-Server ]]; then
    :
else
    echo 'Not running on main server; exiting'
    exit 1;
fi

CERT=/etc/ssl/certs/ssl-cert-snakeoil.pem;
SERVERS='www:443 www:631 backup:443'

# The override entries will go into cert_override.txt in the skel directory.
# This override file will be copied to the firefox profile for new users.
# If users create another profile they'll have to do it themselves.

OVERRIDE_FILE=/tmp/cert_override.txt
SED_SERVERS=$(echo $SERVERS | sed 's/ /\\|/g')
FINGERPRINT=$(openssl x509 -in $CERT -noout -sha256 -fingerprint | sed 's/SHA256 Fingerprint=//')
OVERRIDE_STRING="OID.2.16.840.1.101.3.4.2.1	$FINGERPRINT	MU	AAAAAAAAAAAAAAAJAAAAGgDgwHd5q3rzhTAYMRYwFAYDVQQDEw10amVuZXIuaW50  ZXJu"	# Bogus database key (A.*Ju)

echo -e '# PSM Certificate Override Settings file\n# This is a generated file!  Do not edit.\n' > $OVERRIDE_FILE;

for server in $SERVERS ; do
    echo "$server	$OVERRIDE_STRING" >> $OVERRIDE_FILE;
done

chmod a+r $OVERRIDE_FILE

if [[ $PROFILE =~ Main-Server ]]; then
	TEMPLATE_DIR=/etc/skel/.mozilla/firefox
	TEMPLATE_PROF=$TEMPLATE_DIR/debian-edu.default

# Check/copy the override file.

[ -d $TEMPLATE_PROF ] || mkdir -p $TEMPLATE_PROF
rm -f $TEMPLATE_PROF/cert_override.txt
cp $OVERRIDE_FILE $TEMPLATE_PROF/cert_override.txt
chmod a+r $TEMPLATE_PROF/cert_override.txt
echo "info: $TEMPLATE_PROF/cert_override.txt generated"

# Check/make access to the profile enabled in profiles.ini.

	if ! (grep -q 'Path=debian-edu.default' $TEMPLATE_DIR/profiles.ini); then
		if [ -f $TEMPLATE_DIR/profiles.ini ]; then
			cp --backup=numbered $TEMPLATE_DIR/profiles.ini /var/backups/profiles.ini
			echo -e "Found old $TEMPLATE_DIR/profiles.ini,"\
				"\n\tcreated versioned backup in /var/backups/profiles.ini.x.";
		else
			echo -e '[General]\nStartWithLastProfile=1' > $TEMPLATE_DIR/profiles.ini;
		fi

		echo -e '[ProfileX]\nName=DebEdu\nIsRelative=1\nPath=debian-edu.default\n' \
		| awk '/^\[Profile.*]$/{sub(/e.*/,"e"i++"]")} {print}' $TEMPLATE_DIR/profiles.ini - \
		> $TEMPLATE_DIR/profiles.tmp;

		mv -f $TEMPLATE_DIR/profiles.tmp $TEMPLATE_DIR/profiles.ini;

	fi;
fi

# Cleanup
rm $OVERRIDE_FILE 
