#!/bin/sh

set -e

running_from_di() {
    # Look for file created by base-installer and removed at the end
    # of the d-i run.
    [ -e /etc/apt/apt.conf.d/00IgnoreTimeConflict ]
}

# This block must be done on upgrades before debconf is enabled, and
# not when the upgrade is done from within d-i.
if [ ! "$DEBIAN_HAS_FRONTEND" ] && [ "$1" = configure ] && [ -n "$2" ] && \
    ! running_from_di ; then
    # Purge clear text passwords left over from the installation from
    # debconf templates.dat and templates.dat-old (BTS #711251).
    # Calling debconf-set-selections twice to also purge it from
    # templates.dat-old.
    clearpwd=false
    for template in \
	debian-edu-config/kdc-password \
	debian-edu-config/kdc-password-again \
	debian-edu-config/ldap-password-again \
	debian-edu-config/ldap-password \
	debian-edu-config/first-user-password ; do
	if [ -n "$(perl -MDebconf::Db -MDebconf::Template -e "Debconf::Db->load; my \$template = Debconf::Template->get('$template'); print \$template->default || \$template->value;")" ]; then
	    clearpwd=true
	fi
    done
    wipepwdsfromdebconf() {
	cat <<EOF | debconf-set-selections
debian-edu-config debian-edu-config/kdc-password password
debian-edu-config debian-edu-config/kdc-password-again password
debian-edu-config debian-edu-config/ldap-password password
debian-edu-config debian-edu-config/ldap-password-again password
debian-edu-config debian-edu-config/first-user-password password
EOF
    }
    if $clearpwd ; then
	echo "info: Found clear text passwords in debconf database.  Wiping them."
	wipepwdsfromdebconf
	wipepwdsfromdebconf
    fi
fi

# Enable debconf
. /usr/share/debconf/confmodule

# Remove a no-longer used conffile.  From
# http://wiki.debian.org/DpkgConffileHandling
rm_conffile() {
    PKGNAME="$1"
    CONFFILE="$2"

    [ -e "$CONFFILE" ] || return 0

    md5sum="$(md5sum $CONFFILE | sed -e 's/ .*//')"
    old_md5sum="$(dpkg-query -W -f='${Conffiles}' $PKGNAME | \
            sed -n -e "\' $CONFFILE ' { s/ obsolete$//; s/.* //; p }")"
    if [ "$md5sum" != "$old_md5sum" ]; then
        echo "Obsolete conffile $CONFFILE has been modified by you." 1>&2
        echo "Saving as $CONFFILE.dpkg-bak ..." 1>&2
        mv -f "$CONFFILE" "$CONFFILE".dpkg-bak
    else
        echo "Removing obsolete conffile $CONFFILE ..." 1>&2
        rm -f "$CONFFILE"
    fi
}

# Move a conffile without triggering a dpkg question.  From
# http://wiki.debian.org/DpkgConffileHandling
mv_conffile() {
    local OLDCONFFILE="$1"
    local NEWCONFFILE="$2"

    [ -e "$OLDCONFFILE" ] || return 0

    echo "Preserving user changes to $NEWCONFFILE ..."
    mv -f "$NEWCONFFILE" "$NEWCONFFILE".dpkg-new
    mv -f "$OLDCONFFILE" "$NEWCONFFILE"
}


# Disable/remove divert created by update-iceweasel-homepage in
# Squeeze.
disable_iceweasel_homepage_divert() {
    file=/usr/share/iceweasel/browserconfig.properties
    etcfile=/etc/iceweasel/browserconfig.properties
    if [ "$etcfile" = "$(readlink $file)" ] ; then
	rm $file
	dpkg-divert --package debian-edu-config \
	    --rename --quiet --remove $file
	rm $etcfile
    fi
}

# Execute early, to get the state before changes activated by this
# package is done.
if [ -x /usr/bin/etckeeper ] ; then
    etckeeper commit "start of debian-edu-config postinst" || true
fi

update-mime

# Update config for init.d/update-hostname based on debconf preseeding
ENABLED_DEFAULT=false
ENABLED=$ENABLED_DEFAULT
DEFAULTFILE=/etc/default/update-hostname
# Load current value if set in /etc/
if [ -f $DEFAULTFILE ] ; then
    . $DEFAULTFILE
    if [ "$ENABLED" ] ; then
	db_set debian-edu-config/update-hostname "$ENABLED"
    fi
fi
db_get debian-edu-config/update-hostname
# Only replace if the value changed
if [ -f $DEFAULTFILE ] ; then
    if [ "$RET" != "$ENABLED" ] ; then
	sed "s/ENABLED=.+/ENABLED=\"$RET\"" < $DEFAULTFILE > $DEFAULTFILE.new &&
	    mv $DEFAULTFILE.new $DEFAULTFILE	    
    fi
else
    # Only create or update the file if the value isn't the default value
    if [ "$ENABLED_DEFAULT" != "$RET" ] ; then
	echo "ENABLED=\"$RET\"" >> $DEFAULTFILE
    fi
fi

db_get debian-edu-config/enable-nat
FILE="/etc/default/enable-nat"
# Check the value for enable-nat and set it according to the boolean
if [ "$RET" = "false" ] ; then
	if [ ! -e "$FILE" ] ; then
		echo "NETWORK_TO_NAT=" > $FILE
	fi
fi

# Remove now obsolete diverted config file as bug #656309 is fixed
if [ configure = "$1" ] && \
    dpkg --compare-versions "$2" le "1.726" && \
    [ -h /usr/share/pam-configs/edu-krb5 ]; then
    dpkg-divert --package debian-edu-config --remove /usr/share/pam-configs/krb5
    rm /usr/share/pam-configs/edu-krb5
    pam-auth-update --package --remove edu-krb5
fi

pam-auth-update --package

# Some init-scripts fail if to many fd is open ??
# close debconf db_handle before they start
db_stop


# start the enable-nat init script if we have a ltspserver
if [ -f /etc/debian-edu/config ] && grep -q Thin-Client-Server /etc/debian-edu/config ; then
	if ! grep -q Main-Server /etc/debian-edu/config ; then
		if [ -x "`which invoke-rc.d 2>/dev/null`" ] ; then
			invoke-rc.d enable-nat start || exit $?
		else
			/etc/init.d/enable-nat start || exit $?
		fi
	fi
fi

# Install the file kde-user-profile if it does not exist to ensure
# we can use our kiosk modes
KIOSK_MAP_FILE="/etc/kde-user-profile"
KIOSK_CONFIG_FILE="/etc/kderc"
if [ ! -e "$KIOSK_MAP_FILE" ] ; then
        update-ini-file $KIOSK_MAP_FILE 'General' 'groups' 'students,admins,root'
        update-ini-file $KIOSK_MAP_FILE 'Groups' 'students' 'debian_edu_pupils'
        update-ini-file $KIOSK_MAP_FILE 'Groups' 'admins' 'debian_edu_root'
        update-ini-file $KIOSK_MAP_FILE 'Groups' 'root' 'debian_edu_root'
fi

if [ ! -e "$KIOSK_CONFIG_FILE" ] ; then
        update-ini-file $KIOSK_CONFIG_FILE 'Directories' 'userProfileMapFile' '/etc/kde-user-profile'
        update-ini-file $KIOSK_CONFIG_FILE 'Directories-debian_edu_pupils' 'ProfileDescription' 'Debian-Edu Profile for pupils'
        update-ini-file $KIOSK_CONFIG_FILE 'Directories-debian_edu_pupils' 'prefixes' '/usr/share/debian-edu/students'
        update-ini-file $KIOSK_CONFIG_FILE 'Directories-debian_edu_root' 'ProfileDescription' 'Debian-Edu Profile for root'
        update-ini-file $KIOSK_CONFIG_FILE 'Directories-debian_edu_root' 'prefixes' '/usr/share/debian-edu/root'
fi

case "$1" in
configure)
    if dpkg --compare-versions "$2" le "1.446~svn71241"; then
        rm_conffile debian-edu-config /etc/X11/Xsession.d/15debian-edu-ltsp
    fi

    if dpkg --compare-versions "$2" le "1.446~svn73270"; then
        update-rc.d -f update-hostname remove
        rm_conffile debian-edu-config /etc/init.d/update-hostname
    fi

    if dpkg --compare-versions "$2" le "1.446~svn73463"; then
        update-rc.d -f open-backdoor remove
        rm_conffile debian-edu-config /etc/init.d/open-backdoor
    fi

    if dpkg --compare-versions "$2" le "1.447"; then
        rm_conffile debian-edu-config /etc/cfengine/debian-edu/cf.network-manager
    fi

    if dpkg --compare-versions "$2" le "1.448~svn75140"; then
        rm_conffile debian-edu-config /etc/ldap/dhcp.ldif
        rm_conffile debian-edu-config /etc/ldap/dhcp_hosts.ldif
        rm_conffile debian-edu-config /etc/ldap/dns_skole.ldif
        rm_conffile debian-edu-config /etc/ldap/dns_arpa.ldif
        rm_conffile debian-edu-config /etc/ldap/dns_ranges.ldif
    fi

    if dpkg --compare-versions "$2" le "1.708~svn81297"; then
        rm_conffile debian-edu-config /etc/cfengine/debian-edu/cf.mplayer
    fi

    if dpkg --compare-versions "$2" le "1.714~svn82243"; then
        rm_conffile debian-edu-config /etc/cfengine/debian-edu/cf.lwat
    fi

    if dpkg --compare-versions "$2" le "1.710~svn81721"; then
        disable_iceweasel_homepage_divert
    fi

    if dpkg --compare-versions "$2" le "1.715"; then
	swapfiles=/var/opt/ltsp/swapfiles
	if [ -d $swapfiles ] && getent passwd nbd > /dev/null ; then
	    chmod 700 $swapfiles
	    chown nbd:nbd $swapfiles
	fi
    fi

    if dpkg --compare-versions "$2" le "1.811"; then
	rm_conffile debian-edu-config /etc/cfengine/debian-edu/cf.pdns
	rm_conffile debian-edu-config /etc/insserv.conf.d/debian-edu-config
	rm_conffile debian-edu-config /etc/powerdns/pdns.d/pdns-debian-edu.conf
    fi

    # sssd refuses to read the file if it has any other mode
    chmod 600 /etc/sssd/sssd-debian-edu.conf
    chown root:root /etc/sssd/sssd-debian-edu.conf

    # silence dovecot's message: if you have trouble with authentication failures,
    # enable auth_debug setting. See http://wiki.dovecot.org/WhyDoesItNotWork
    # This message goes away after the first successful login.
    mkdir -p /var/lib/dovecot
    chmod 750 /var/lib/dovecot
    chown root:root /var/lib/dovecot
    touch /var/lib/dovecot/auth_success

    ;;
esac

#DEBHELPER#

#fix symlink for exim4.conf, related to #1264
if [ -h /etc/exim4/exim4.conf ] && [ -x /etc/init.d/exim4 ] ; then
	if [ $(readlink /etc/exim4/exim4.conf) = "/etc/exim/exim-ldap-client-v4.conf" ] ; then
		ln -sf /etc/exim4/exim-ldap-client-v4.conf /etc/exim4/exim4.conf
		invoke-rc.d exim4 reload
	fi
fi

# Make sure KDE screen unlocking work on diskless workstations
# (Skolelinux bug #1415).
ltsparch="$(ltsp-arch-debian-edu)"
certfile="/opt/ltsp/$ltsparch/etc/ldap/ssl/ldap-server-pubkey.pem"
if [ -f "$certfile" ] && [ 644 != "$(stat -c '%a' "$certfile")" ] ; then
    chmod 644 $certfile
fi

# Make sure LTSP resolv.conf is readable by all (Skolelinux bug #1416)
resolvconf="/opt/ltsp/$ltsparch/etc/resolv.conf"
if [ -f "$resolvconf" ] && [ 644 != "$(stat -c '%a' "$resolvconf")" ] ; then
    chmod 644 $resolvconf
fi

# Register all changes done by this postinst script
if [ -x /usr/bin/etckeeper ] ; then
    etckeeper commit "end of debian-edu-config postinst" || true
fi

# Regenerate desktop-profiles cache, as we've installed new .listing files 
if(  ( test "$1" = "configure" ) &&
     ( test -x "$(which update-profile-cache 2>/dev/null)" ) ); then
    update-profile-cache;
fi;

exit 0
