#!/bin/sh
#
# This script is executed within the debian-installer environment when
# finish-install.d is executed, which is executed at the end of the
# installation. It includes running cf-agent for final configuration.

set -e

# export DEBCONF_DEBUG='developer'
. /usr/share/debconf/confmodule

log() {
	logger -t debian-edu-config-finish-install "$@"
}

# Make sure any dhclient processes started in pre-pkgsel is stopped to
# make sure /var/ is umounted and clean on first boot.
deconfigure_network() {
	if [ -e /tmp/debian-edu-nonetwork ] ; then
		in-target /bin/sh -c "/etc/init.d/networking stop" || true
	fi
}

# Prevent d-i to delete configured target interface file
preserve_network_interfaces() {
	file=/usr/lib/finish-install.d/55netcfg-copy-config
	if [ -x $file ] ; then
		log "Keep already configured interface file"
		cat /dev/null > $file
	fi
}

# Make the content of the BD available again and prevent unmounts
keep_cdrom_mountpoint_active=0
cd_type=$(cat /cdrom/.disk/cd_type)
case "$cd_type" in
    bluray*)
        keep_cdrom_mountpoint_active=1
        ;;
esac

if [ ${keep_cdrom_mountpoint_active} ]; then
	# /cdrom is mounted, but /target/media/cdrom isn't
	mount -o bind /cdrom /target/media/cdrom
	# Restore the 00NoMountCDROM file to prevent unmounting the BD
	# The file will later be deleted by 90base-installer
	cat > /target/etc/apt/apt.conf.d/00NoMountCDROM << EOT
APT::CDROM::NoMount "true";
Acquire::cdrom {
  "/media/cdrom/" {
    Mount  "true";
    UMount "true";
  };
  AutoDetect "false";
}
EOT
	# Fixup of /target/etc/apt/sources.list:
	# 1) Add a line with the magic marker 'BD' needed for debian-edu-ltsp-install
	# 2) Replace the cdrom: entry with a file entry
	in-target sed -i -e '1i# Origin BD image' -e 's|cdrom:\[.*\]/|[trusted=yes] file:///media/cdrom/|' /etc/apt/sources.list
	in-target apt-get update
fi

db_get debian-edu-install/profile
PROFILE="$RET"

# Create LTSP thin client image and iPXE setup in case of a combined server.
if echo "$PROFILE" | grep -Eq 'Main-Server.*LTSP-Server' ; then
	in-target /bin/sh -c "modprobe squashfs" || true
	in-target /bin/sh -c "modprobe loop" || true
	in-target /bin/sh -c "modprobe overlay" || true
	if in-target /bin/sh -c "/usr/sbin/debian-edu-ltsp-install --diskless_workstation no --thin_type bare" ; then
		log "info: Running 'debian-edu-ltsp-install' succeeded"
	else
		log "error: 'debian-edu-ltsp-install' failed"
	fi
fi

# Register changes before and after cf-agent is executed, to make it
# easier to track our changes
edu-etcvcs commit

# Make the installation look more like a finished system, to make sure
# debconf-get-selections --installer work.
. /usr/lib/finish-install.d/94save-logs

# Setup Cfengine3 environment.
if in-target /usr/share/debian-edu-config/tools/setup-cfengine3 ; then
	log "info: Running 'setup-cfengine3' succeeded"
else
	log "error: '/usr/share/debian-edu-config/tools/setup-cfengine3' is missing"
fi

# Update configuration via cf-agent for everything that could not be preseeded.
if in-target /bin/sh -c "cf-agent -v 2>&1 > /var/log/installer/cfengine-edu-install.log" ; then
	:
else
	log "error: Running 'cf-agent -v' failed to work at some point"
fi

edu-etcvcs commit

# Clean up changes done to tasksel in pre-pkgsel and go back to the
# default behavior.
in-target /usr/lib/education-tasks/edu-tasksel-setup teardown

preserve_network_interfaces
deconfigure_network

# Adjust /etc/network/interfaces eth0 entry once available (d-e-c postinst is
# run too early). Adds 'post-up /usr/sbin/update-hostname-from-ip' conditionally
# via the postinst script to the eth0 entry.
in-target /usr/sbin/dpkg-reconfigure -u --no-reload debian-edu-config || true

edu-etcvcs commit

# For non-Main-Server profiles, try to submit to sitesummary at the
# end of the installation, to try to avoid one extra boot to update
# hostname from DNS after updating GOsa.  Main-Server will become its
# own collector, so no need to try to submit here.
if echo $PROFILE | grep -q Main-Server ; then
	:
elif [ -x /target/usr/sbin/sitesummary-client ] ; then
	in-target /usr/sbin/sitesummary-client || true
fi

# Make sure the root password is gone from debconf after the
# installation, in case ldap-debian-edu-install and kerberos-init-kdc 
# scripts failed when cf-agent was executed.
# This needs to be done in the target system
file=/tmp/edu-passwords
	cat > $file <<EOF
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
EOF
# Pass above debconf information into the target
cat $file | LANG=C chroot /target debconf-set-selections || \
	error "Failed to clear kerberos and ldap passwords from debconf."
rm $file
log "info: Ensuring KDC and LDAP passwords are cleared from debconf database"

# Special case first user: the homedir is missing if LDAP setup failed; the
# /etc/krb5.keytab file is missing if Kerberos setup failed.
# In case the installation succeeds, the password is kept to be able to create
# the first-user Samba account at first boot (tools/run-at-firstboot, where the
# password is cleared afterwards).
if db_get passwd/username && [ "$RET" ] ; then
	FIRSTUSERNAME="$RET"
fi
if [ ! -d /target/skole/tjener/home0/"$FIRSTUSERNAME" ] || \
		[ ! -f /target/etc/krb5.keytab ] ; then
	file=/tmp/firstuser-password
	cat > $file <<EOF
debian-edu-config debian-edu-config/first-user-password password
EOF
	# Pass above debconf information into the target
	cat $file | LANG=C chroot /target debconf-set-selections || \
	error "Failed to clear first-user password from debconf."
	rm $file
	log "info: Installation is broken; all passwords cleared from debconf database."
fi

# Cleanup
if [ ${keep_cdrom_mountpoint_active} ]; then
	umount /target/media/cdrom
fi

echo "info: processes using mount point below /target"
mountpoints="$(grep " /target" /proc/mounts | cut -d" " -f2 | sed s%/target%%g)"
LANG=C chroot /target fuser -mv $mountpoints 2>&1 | sed 's/^/info: /'

if LANG=C chroot /target fuser -mv $mountpoints 2>&1 | grep -Eqv 'USER|mount |Cannot open ' ; then
	log "error: some processes blocking d-i from umounting /target/"
fi

