#!/bin/bash
#
# Set up Iceweasel to accept the default ssl certificate created by debian-edu-config
# for new users and new Iceweasel profiles.
#
# 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"

SERVERS='www:443 www:631 backup:443'

## FIXME: Why is resolv.conf empty or missing? Because network 
## was started in the chroot (target)? 
## Try to find the DNS from the leases file, if that fails use
## default DNS:
if [ ! -s /etc/resolv.conf ] ; then
    DNS="10.0.2.2"
    LEASEDIR=/var/lib/dhcp/
    if [ -d $LEASEDIR ] ; then
	LEASEFILE=$LEASEDIR`ls -tr -1 $LEASEDIR | tail -n 1`
	if [ -r $LEASEFILE ] ; then
	    if DNSLEASE=`cat $LEASEFILE | grep domain-name-servers | \
		tail -n 1 | \
		grep -o "[0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+"` ; then
		DNS=$DNSLEASE
		echo "info: Found leases file and domain-name-server: $DNS."
	    else
		echo "info: Could not extract DNS from leases file."
	    fi
	fi
    fi
    echo "info: Create temporary /etc/resolv.conf with DNS: $DNS."
    cat >> /etc/resolv.conf <<EOF
## This is a temporary resolv.conf created by $0.
## If you find it after installation, something went wrong. Try to replace it 
## by a symlink: /etc/resolv.conf -> /etc/resolvconf/run/resolv.conf, i.e.: 
## rm /etc/resolv.conf; ln -s /etc/resolvconf/run/resolv.conf /etc/resolv.conf
nameserver $DNS
search intern
EOF
fi

# On main server read local certificate
# otherwise fetch the certificate over ssl.

if [[ $PROFILE =~ Main-Server ]]; then
	CERT=/etc/ssl/certs/ssl-cert-snakeoil.pem;
elif (ping -c 1 www > /dev/null); then
	CERT=$(tempfile -p fetch -s cert)
	echo | openssl s_client -connect www:443 2>/dev/null | \
	    sed -n '/-----BEGIN CERTIFICATE-----/,/-----END CERTIFICATE-----/p' > $CERT;
else
	echo 'error: can not find SSL certificate for http://www'
	exit 1;
fi


# Write the override entries in the default profile.
# These will be copied to new Iceweasel profiles.

OVERRIDE_FILE=/etc/iceweasel/profile/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)

if [ -f $OVERRIDE_FILE ]; then
	sed "/$SED_SERVERS/ s/..\(:..\)\{31\}/$FINGERPRINT/" $OVERRIDE_FILE > $OVERRIDE_FILE.temp;
	if cmp $OVERRIDE_FILE $OVERRIDE_FILE.temp ; then
		cat <<-EOF 1>&2
			info: File $OVERRIDE_FILE
			info: already up to date. No need to do anything, exiting.
		EOF
		rm $OVERRIDE_FILE.temp
		exit 0
	else
		cp --backup=numbered $OVERRIDE_FILE /var/backups/cert_override
		echo -e "warning: Found old $OVERRIDE_FILE," \
			"\n\tcreated versioned backup in /var/backups/cert_override.x."
	fi
else
	[ -d /etc/iceweasel/profile ] || mkdir -p /etc/iceweasel/profile
	echo -e '# PSM Certificate Override Settings file\n# This is a generated file!  Do not edit.\n' > $OVERRIDE_FILE.temp;
fi

for server in $SERVERS ; do
	if ! (grep -q $server $OVERRIDE_FILE.temp); then
		echo "$server	$OVERRIDE_STRING" >> $OVERRIDE_FILE.temp;
	fi;
done

chmod a+r $OVERRIDE_FILE.temp
mv $OVERRIDE_FILE.temp $OVERRIDE_FILE


# On main server also check /etc/skel/ for default profile.
# This will be copied to new users home directories.

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

# Check/copy the override file.

	if ! cmp $TEMPLATE_PROF/cert_override.txt $OVERRIDE_FILE ; then
		[ -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
	fi

# 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

for ROOT in `find /opt/ltsp/ -mindepth 1 -maxdepth 1 -type d`; do
    if [ ! -d $ROOT/etc/iceweasel/profile ] ; then
	continue # Only process LTSP chroots with iceweasel installed
    fi
    # Make sure self signed SSL certificate for internal web site also
    # work on diskless workstations.
    OVERRIDE_FILE=/etc/iceweasel/profile/cert_override.txt
    if [ -f $OVERRIDE_FILE ] ; then
        mkdir -p $(dirname $ROOT$OVERRIDE_FILE)
        if cp $OVERRIDE_FILE $ROOT$OVERRIDE_FILE ; then
            chmod a+r $ROOT$OVERRIDE_FILE
        else
cat 1>&2 <<EOF
error: Can't copy the new Iceweasel override settings to LTSP.
error: Iceweasel profiles created on a thin client will not accept
error: the new certificate
EOF
        fi
    else
        error "Fail to find Iceweasel certificate override file."
    fi
    ls -l $ROOT$OVERRIDE_FILE |sed "s%^%info: $0: snakeoil-on-ice: %"
done
