#!/bin/sh

# Mount filesystems and configure apt
mount --bind /proc /target/proc
mount --bind /dev /target/dev
mount --bind /dev/pts /target/dev/pts
mount --bind /cdrom /target/cdrom
chroot /target apt-cdrom add
sed -i 's/#deb cdrom/deb cdrom/g' /target/etc/apt/sources.list

# Close down if dpkg is running on the system
if [ "`chroot /target ps aux | grep dpkg | wc -l`" -gt "1" ]; then
  zenity --info --title "Operation in Progress" --text "Another process is currently installing software, please try again later."
  exit
fi

# LTSP installation
echo " * Installing LTSP Server..."

# Divert init scripts
mv /target/sbin/initctl /target/sbin/initctl.orig
echo '#!/bin/sh' > /target/sbin/initctl
echo "exit 0" >> /target/sbin/initctl
chmod +x /target/sbin/initctl


mv /target/sbin/start-stop-daemon /target/sbin/start-stop-daemon.orig
echo '#!/bin/sh' > /target/sbin/start-stop-daemon
echo "exit 0" >> /target/sbin/start-stop-daemon
chmod +x /target/sbin/start-stop-daemon

# Install all the services
chroot /target apt-get -y install ltsp-server-standalone

# Undivert init scripts
mv /target/sbin/initctl.orig /target/sbin/initctl
mv /target/sbin/start-stop-daemon.orig /target/sbin/start-stop-daemon

# Unpack the chroot
mkdir -p /target/opt/ltsp/ /opt/ltsp/i386
mount /cdrom/ltsp/i386.img /opt/ltsp/i386 -o loop
cp -r /opt/ltsp/i386 /target/opt/ltsp

ifconfig $INTERFACE 192.168.0.254
# FIXME: We need to start SSH in Lucid, probably not in later versions anymore
# FIXME: Starting ssh manually as the init script requires initctl that we
# disabled before
mkdir -p /target/var/run/sshd/
chroot /target /usr/sbin/sshd
touch /target/var/log/syslog
touch /target/var/log/messages
chroot /target hostname `cat /etc/hostname`
chroot /target ltsp-update-sshkeys
hostname `cat /etc/hostname`

# Rebuild the image
chroot /target ltsp-update-image -a i386
chroot /target ltsp-update-kernels

cat >> /target/etc/network/interfaces <<EOF

auto $INTERFACE
iface $INTERFACE inet static
  address 192.168.0.254
  netmask 255.255.255.0

EOF

# Some cleaning up
chroot /target killall sshd
chroot /target killall inetd

# Unmount filesystems
umount -l /opt/ltsp/i386
umount -l /target/dev/pts
umount -l /target/dev
umount -l /target/proc
umount -l /target/cdrom
