#!/bin/sh
#
# Set up LTSP environment for Debian Edu
#
# Author: Petter Reinholdtsen
# Date:   2005-10-08

base=
dist=

while [ $# -gt 0 ] ; do 
  case "$1" in 
    --base) base="$2" ; shift ;;
    --dist) dist="$2" ; shift ;;
    --arch) arch="$2" ; shift ;;
  esac
  shift
done

if [ -z "$base" -a -z "$arch" ] ; then 
  case $(uname -m) in
    ppc) ARCH=powerpc ;;
    i*86) ARCH=i386 ;;
    x86_64) ARCH=amd64 ;;
    *) echo "Unknown Architecture, please fix the script $0"
       exit 9
       ;;
  esac
elif [ -n "$arch" ] ; then
  ARCH="$arch"
fi

# Make the installation a bit more quiet when started from the command line
# The locale is not setup in the thin client chroot (yet?)
LC_ALL=C
export LC_ALL

test "$base" || base=/opt/ltsp
test "$dist" || dist=$(debian-edu-current-codename)

if [ -d $base/$ARCH ] ; then
    echo "error: $base/$ARCH already exist.  Remove it before running $0"
    echo "       If you want to install in parallell with an old installation, "
    echo "       please use --base <new location> as an option"
    exit 1
fi

# Check if server uses install or cd to install
if apt-cache policy ltsp-client | grep -q "cdrom://" ; then 
  mirror=file:///media/cdrom
  components="main local"
  securitymirror=""
  extramirror=""
else
  mirror=http://http.debian.net/debian
  extramirror=""
  securitymirror="http://security.debian.org/ $dist/updates main contrib"
  components="main contrib"
fi

umounts=
exit_handler() {
    # Unmount if anything is mounted
    for dir in $umounts ; do
	info "Unmounting $dir"
	umount $dir || true
    done
}
trap exit_handler EXIT INT

# Mount the CD ROM if needed
case $mirror in
    file:///cdrom)
        mount /cdrom
	umounts="/cdrom"
	;;
    file:///media/cdrom)
        mount /media/cdrom
	umounts="/media/cdrom"
	;;
    *)
        ;;
esac

if ltsp-build-client --help 2>&1 |grep -q -- --root ; then
    # Old version
    ltspopts="--root $base/$ARCH"
else
    # new version (at least >= 0.93debian1)
    ltspopts="--eatmydata --accept-unsigned-packages --base /opt/ltsp --arch $ARCH"
fi

# Build LTSP chroot, fetch packages from default APT sources
# FIXME: Added ugly workaround to let installation succeed in case the
# dictionaries-common problem occurs.
if ltsp-build-client \
  $ltspopts \
  --mirror $mirror \
  --dist $dist \
  --components "$components" \
  --security-mirror "$securitymirror" \
  --extra-mirror "$extramirror" ; then
  :
  else
  ltsp-chroot /usr/share/debconf/fix_db.pl
  ltsp-chroot dpkg --configure -a
fi

#populate /var/lib/tftpboot with kernel images and pxelinux configuration
if [ -f /usr/sbin/ltsp-update-kernels ] ; then
     ltsp-update-kernels
fi

# And update ssh keys
if [ -x /usr/sbin/ltsp-update-sshkeys ]; then
    ltsp-update-sshkeys
fi
