#!/bin/sh
#
# Prepare for PXE installation of Debian Edu.
#
# A better idea might be to use di-netboot-assistant,
# <URL:http://www.klabs.be/~fpiat/linux/debian/di-netboot-assistant/>.
# See also the original bin/debian-edu-pxelinux.cfg 
# (bin/debian-edu-pxelinux.cfg has been removed from the 
# debian-edu-config source after 1.443~svn66662)

set -e

LC_ALL=C
export LC_ALL

## 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

# Make sure the created directories and files are readable by tfptd
# run as user nobody.
umask 022

# Fetch ftp_proxy and http_proxy if set globally
if [ -f /etc/environment ] ; then
    . /etc/environment
fi

[ "$dist" ]      || dist=$(debian-edu-current-codename)
[ "$archs" ]     || archs="i386 amd64"
[ "$mirrorurl" ] || mirrorurl=http://http.debian.net/debian
[ "$archiveurl" ] || archiveurl=http://ftp.skolelinux.org/skolelinux
[ "$hostname" ]  || hostname=pxeinstall
[ "$domain" ]    || domain=intern
# Not hardcoded to allow PXE installation of a main-server without a
# proxy set
#[ "$http_proxy" ] || http_proxy=http://webcache:3128
#[ "$ftp_proxy" ] || ftp_proxy=http://webcache:3128

# Use Graphical installer by default
graphicdi=false

if [ -f /etc/debian-edu/config ] ; then
    . /etc/debian-edu/config
fi

# Special case test builds
if [ true = "$TESTINSTALL" ] ; then
    edudist=$dist-test
else
    edudist=$dist
fi

# This part does not work from within debian-installer, as it is
# executed from cfengine before the cdebconf files are copied into
# /var/log/installer/cdebconf/ ("debconf-get-selections --installer"
# does not work).  A workaround for this issue was added to
# debian-edu-install, copying the files a bit earlier.
installconfig=""
for template in debian-installer/locale \
    keyboard-configuration/xkb-keymap \
    tasksel/desktop; do
    value="$(debconf-get-selections --installer | grep $template | awk '{print $4}')"
    if [ -z "$value" ] ; then
	# If there is no value in the installer debconf database, try
	# the currently installed one.  This solve a problem with
	# tasksel/desktop when installing gnome via PXE.
	value="$(debconf-get-selections | grep $template | awk '{print $4}')"
    fi

    # Using desktop= as kernel argument work, while tasksel/desktop=
    # do not.  No idea why, but lets use the one that work.
    if [ "tasksel/desktop" = $template ] ; then template=desktop ; desktop=$value; fi

    # Map the long name to the short alias, to keep the argument list
    # shorter.
    if [ "debian-installer/locale" = $template ] ; then template=locale; fi
    if [ "keyboard-configuration/xkb-keymap" = $template ] ; then template=keymap; fi

    if [ "$value" ] ; then
	installconfig="$installconfig $template=$value"
    fi
done

tftpdir=/var/lib/tftpboot

# Where to find the preseed file on the web
preseedurl=http://www/debian-edu-install.dat

# Where the preseed file is on the disk.
preseedfile=/etc/debian-edu/www/debian-edu-install.dat

# Allow site specific overrides to the variables
if [ -f /etc/debian-edu/pxeinstall.conf ] ; then
    . /etc/debian-edu/pxeinstall.conf
fi

[ -d $tftpdir ] || mkdir $tftpdir
[ -d $tftpdir/debian-edu ] || mkdir $tftpdir/debian-edu


for arch in $archs ; do
    (
	[ -d $tftpdir/debian-installer ] || \
	    mkdir $tftpdir/debian-installer
        cd $tftpdir/debian-installer
	di_ver=8
        tarball=""
        if [ -d /usr/lib/debian-installer/images/$di_ver/$arch ]; then
	    di_img_dir="/usr/lib/debian-installer/images/$di_ver/$arch"
	    # Use the debian/installer netboot debs
            tarball=""
	    if [ true = "$graphicdi" ]; then
		ln -sf $di_img_dir/gtk/debian-installer/$arch $arch
		gtkvideo="video=vesa:ywrap,mtrr"
	    else
		ln -sf $di_img_dir/text/debian-installer/$arch $arch
	    fi
        elif [ ! -f netboot-$arch.tar.gz ] ; then
	    if [ true = "$graphicdi" ]; then
                # Use this URL for graphical installer, and fix
                # gtkvideo setting below
                url=$mirrorurl/dists/$dist/main/installer-$arch/current/images/netboot/gtk/netboot.tar.gz
                gtkvideo="video=vesa:ywrap,mtrr vga=788"
            else
                url=$mirrorurl/dists/$dist/main/installer-$arch/current/images/netboot/netboot.tar.gz
            fi
            echo "Fetching $url"
            if wget -q -O netboot-$arch.tar.gz.new $url ; then
                mv netboot-$arch.tar.gz.new netboot-$arch.tar.gz
                tarball=netboot-$arch.tar.gz
            else
                echo "error: Unable to download $url"
                exit 1
            fi
        fi
        if [ "$tarball" ] ; then
            tar --strip-components=2 -zxvf $tarball
        fi
    )
done

echo "Generating $preseedfile"
(
    cat <<EOF
# Enable the Debian Edu installer overrides
d-i     anna/choose_modules     multiselect     debian-edu-install-udeb: Execute Debian-Edu debian-installer profile

# Just accept the proposed hostname and domain, as it is dynamically
# fetched from DNS.
d-i     netcfg/get_hostname     seen    true
d-i     netcfg/get_domain       seen    true

# location of the proxies, in case it is required, both http and ftp
# in case someone ask d-i to use ftp mirrors.
d-i     mirror/http/proxy       string  $http_proxy
d-i     mirror/ftp/proxy        string  $ftp_proxy

# list extra packages to install here
#d-i     pkgsel/include string acroread

# if you want popcon enabled by default
#d-i     debian-edu-install/participate-popcon boolean true

# If you want a specific set of profiles installed
#d-i	debian-edu-install/profile multiselect Workstation, Thin-Client-Server

# If you want automatic partitioning
#d-i	debian-edu-install/confirm boolean true

# If you want to avoid the password question
#d-i passwd/root-password-crypted password passwordhash

# Tell LTSP to not use the CDROM, but a HTTP mirror
d-i ltsp-client-builder/use_cdrom boolean false
d-i ltsp-client-builder/build-client-opts string --mirror $mirrorurl --dist $dist

# Tell PXE clients to fetch the correct time from the central NTP server
# d-i is unable to discover the ntp-server DHCP option.  Hardcode
# setting here instead.  FIXME: Remove when #714288 in netcfg is fixed.
d-i netcfg/dhcp_ntp_servers string ntp

# Pass on the time zone used on the main-server
EOF
    debconf-get-selections --installer | grep -w 'time/zone'

    if [ wheezy = "$dist" ] ; then
	# FIXME check if this workaround is still needed.  It is
	# needed when the udebs we want to use during installation are
	# newer in our repository than in the official Debian
	# repository.
        cat <<EOF

# Workaround for old udebs in Debian/Wheezy
d-i     preseed/early_command   string  anna-install dmidecode-udeb; export http_proxy="$http_proxy"; cd /tmp; archiveurl=$archiveurl; arch=i386; wget \$archiveurl/dists/$edudist/local/debian-installer/binary-\$arch/Packages; packages_file=Packages; desired_udebs="debian-edu-profile-udeb"; for file in \$(grep 'Filename:' \$packages_file | cut -d : -f 2); do udeb=\$(basename \$file | cut -d _ -f 1); for u in \$desired_udebs ; do if [ "\$u" = "\$udeb" ]; then url="\$archiveurl/\$file"; echo "info: Trying to fetch and install \$url"; if wget \$url; then udpkg --unpack \$(basename \$file); else echo "error: Unable to download \$url"; fi; break; fi; done; done; if [ -z "\$url" ] ; then echo "error: Unable to find updated udebs"; fi
EOF
    fi

    # Enable test repository during testing, but not for production
    if [ "$dist" != "$edudist" ] ; then
	cat <<EOF

# Test install, activate test repository, uses local0 which is also
# used by debian-edu-install, which will make sure a duplicate APT
# source is not inserted into sources.list when doing test installs.
d-i apt-setup/local0/repository string http://ftp.skolelinux.org/skolelinux $edudist local
d-i apt-setup/local0/comment string Debian Edu $edudist repository
d-i apt-setup/local0/source boolean true
EOF
    fi

    # No use copying the installation mirror setting if a DVD or USB
    # stick was used.
    if grep -qi 'dvd|bd' /etc/apt/sources.list ; then
cat <<EOF

# Avoid questions about mirrors, using manual setup
choose-mirror-bin     mirror/country          string  manual
choose-mirror-bin     mirror/protocol select  http
choose-mirror-bin     mirror/http/mirror      select
choose-mirror-bin     mirror/http/hostname    string  http.debian.net
choose-mirror-bin     mirror/http/directory   string  /debian
EOF
    else
	debconf-get-selections --installer | egrep -w 'mirror/http/mirror|mirror/country|mirror/protocol|mirror/http/hostname|mirror/http/directory|mirror/ftp/hostname|mirror/ftp/directory' | sort
    fi

    # Make it easier to have local overrides and still be able to
    # rerun debian-edu-pxeinstall.
    if [ -f $preseedfile.local ] ; then
	cat $preseedfile.local
    fi
) > $preseedfile

if [ "$passwdmd5hash" ]; then
    cat <<EOF > $tftpdir/debian-edu/menupasswd.cfg
        MENU PASSWD $passwdmd5hash
EOF
fi

menufile=$tftpdir/debian-edu/install.cfg
echo "Generating $menufile"
(
    for arch in $archs ; do
        cat <<EOF
	# Based on the values used in Debian, and added the preseed URL
LABEL neteduboot-$arch
        MENU LABEL Install Edu/^$arch ($desktop)
        kernel debian-installer/$arch/linux
        append $gtkvideo initrd=debian-installer/$arch/initrd.gz auto url=$preseedurl hostname=$hostname domain=$domain $installconfig --- quiet
	ipappend 2
include menupassword.cfg

EOF
    done
) > $menufile

memtest=
if [ -f /boot/memtest86.bin ] ; then
    memtest=/boot/memtest86.bin
fi
if [ -f /boot/memtest86+.bin ] ; then
    memtest=/boot/memtest86+.bin
fi
if [ "$memtest" ] ; then
    cp $memtest $tftpdir/debian-edu/memtest86
    cat <<EOF > $tftpdir/debian-edu/memtest.cfg
LABEL memtest86
        MENU    LABEL  Test ^memory
        kernel  debian-edu/memtest86

EOF
fi

if [ -d /var/lib/tftpboot/ltsp/i386 ] ; then
    ltsproot=/opt/ltsp/i386

    cat <<EOF > $tftpdir/debian-edu/ltsp-thin.cfg

LABEL ltsp-thin
        MENU    LABEL  LTSP ^thin client
        KERNEL ltsp/i386/vmlinuz
        APPEND initrd=ltsp/i386/initrd.img init=/sbin/init-ltsp nfsroot=$ltsproot boot=nfs ro LTSP_FATCLIENT=False quiet
	IPAPPEND 2
EOF
    cat > $tftpdir/debian-edu/default-thin.cfg <<EOF
DEFAULT ltsp/i386/vmlinuz initrd=ltsp/i386/initrd.img init=/sbin/init-ltsp nfsroot=$ltsproot boot=nfs ro LTSP_FATCLIENT=False quiet ipappend 2

EOF

# See if LTSP also have diskless workstation support
    if [ -e $ltsproot/lib/i386-linux-gnu/security/pam_krb5.so ] || \
       [ -e $ltsproot/lib/i386-linux-gnu/security/pam_ldap.so ] || \
       [ -e $ltsproot/lib/i386-linux-gnu/security/pam_sss.so ] ; then
	cat <<EOF > $tftpdir/debian-edu/ltsp-diskless.cfg

LABEL ltsp-diskless
        MENU    LABEL  LTSP ^diskless workstation
        KERNEL ltsp/i386/vmlinuz
        APPEND initrd=ltsp/i386/initrd.img init=/sbin/init-ltsp nfsroot=$ltsproot boot=nfs ro quiet
	IPAPPEND 2

EOF
	cat > $tftpdir/debian-edu/default-diskless.cfg <<EOF
DEFAULT ltsp/i386/vmlinuz initrd=ltsp/i386/initrd.img init=/sbin/init-ltsp nfsroot=$ltsproot boot=nfs ro quiet ipappend 2
EOF
    fi
fi

cat <<EOF > $tftpdir/debian-edu/localboot.cfg
LABEL localboot
        MENU LABEL Boot from ^local harddrive
        MENU DEFAULT
        localboot 0

EOF

ln -sf /usr/lib/PXELINUX/pxelinux.0 $tftpdir/pxelinux.0
ln -sf /usr/lib/syslinux/modules/bios $tftpdir/syslinux
ln -sf /usr/share/pixmaps/splash/debian-edu-splash.png $tftpdir/debian-edu/debian-edu-splash.png

defaultfile=$tftpdir/debian-edu/default-menu.cfg
echo "Generating $defaultfile"
(
    cat <<EOF
include debian-edu/localboot.cfg
MENU SEPARATOR
include debian-edu/ltsp-diskless.cfg
include debian-edu/ltsp-thin.cfg
MENU SEPARATOR
include debian-edu/install.cfg
MENU SEPARATOR
include debian-edu/memtest.cfg

menu color title        * #FFFFFFFF *
menu color border       * #00000000 #00000000 none
menu color sel          * #ffffffff #76a1d0ff *
menu color hotsel       1;7;37;40 #ffffffff #76a1d0ff *
menu color tabmsg       * #ffffffff #00000000 *
menu color help         37;40 #ffdddd00 #00000000 none

menu vshift 8
menu rows 10
menu hshift 13
menu width 49
menu background debian-edu/debian-edu-splash.png
menu tabmsg Press ENTER to boot or TAB to edit a menu entry
default vesamenu.c32
prompt 0
timeout 0
EOF
) > $defaultfile

# Use the complete menu by default
pxecfgdir=$tftpdir/pxelinux.cfg
[ -d  $pxecfgdir ] || mkdir $pxecfgdir
ln -sf ../debian-edu/default-menu.cfg $pxecfgdir/default
