#!/bin/sh
# Copyright Peter Jordan 2001
# GPL2 - permission granted to use, copy, modify if this notice retained.

# TODO - use a makefile to generate this file "debian-installer"

#export DISTRO="unstable"
export SUITE="unstable"
export MIRROR="http://sunsite.cnlab-switch.ch"
export DIRECTORY="ftp/mirror/debian/"
export TARGET=/target
linux_root_partition="/dev/discs/disc0/part11"

# assume master_server was set on the kernel boot command line
#rdate 192.168.2.1
rdate $MASTER_SERVER

# TODO die to server's control... ? DEBIAN_FRONTEND=web ? sql or something would be nice too
# TODO do sanity checks before partitioning, in the sense of checking for
#  the local debian mirror, and maybe even downloading necessary files ?
# hmm. at some point we just have to redo it. so I need to be able to be
# robust and reentrant.  I think a CONTINUE prompt is a good idea for
# the debsplat thing.  <- I disagree now.

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
die() {

    echo ERROR: $*
    exit 99
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

# FIRST bring up the network ..
# reject "official" dhcp server, or else /etc/hostname munging gets munged
# TODO this should be an external setting somehow, but I don't see how.  an accept line
# would be preferrable to a reject line, for then we could accept only from the tftp server
#echo "request option-133;" > /etc/dhclient.conf || die "Can't create /etc/dhclient.conf"
#echo "require option-133;" >> /etc/dhclient.conf || die "Can't append /etc/dhclient.conf"
# now I am doing this in rootskel... hmm. the script could do it all...
# TODO - "the script could do it all"

#dhclient eth0 || die "This doesn't work right.  Need another test below."

#/sbin/ifconfig lo 127.0.0.1 || die "Unable to configure loopback interface."

# TODO do we need a hostname set here ?

#ping -c 1 $MASTER_SERVER || die "Can not ping master server: $MASTER_SERVER."

# getting install.config has to be done after the network is up silly
# wget http://$MASTER_SERVER/install.config || die "Failed to wget install.config."
# . ./install.config

# TODO - grab install.config info by catting together 'this' script from
# the web page control interface

# TODO instead of cheking for "Home", check for a param in device-tree. (?)
# check for linux partition and abort if not found .... ahummm..
# TODO this is dangerous, not check, simply remove 10 and 11.
parted /dev/ide/host0/bus0/target0/lun0/disc print | grep "^9 " > /tmp/foo || die "No partition minor 9 ?  Aborting..."

start=`sed 's/\(\ \ *\)/\ /g' /tmp/foo | cut -d' ' -f 3`

#end=`sed 's/\(\ \ *\)/\ /g' /tmp/foo | cut -d' ' -f 3`

start=`echo $start | sed 's/\.//'` # take out the decimal
start=`expr $start + 1` # add 1 to get start of part. minor 10
start=`echo $start | sed 's/.\{3\}$/.&/'`  # Put the decimal back in.  rking++

# TODO, take $end from the grep of parted's print output.
# TODO, better still,have the partition policy be downloaded from $MASTER_SERVER
# This should be set to the max size of the disk.
end=28629.562

swapend=`echo $start | sed 's/\.//'` # take out the decimal
swapend=`expr $swapend + 512000` # make a 512MB swap partition
swapend=`echo $swapend | sed 's/.\{3\}$/.&/'`  # Put the decimal back in.  rking++

newstart=`echo $swapend | sed 's/\.//'` # take out the decimal
newstart=`expr $newstart + 1`  # just past the last spot
newstart=`echo $newstart | sed 's/.\{3\}$/.&/'`  # Put the decimal back in.  rking++

echo
echo start: $start
echo swapend: $swapend
echo newstart: $newstart
echo end: $end
echo

#newstart=`awk 'BEGIN { print $swapend + 0.001 }'`  # Roderick++

# ok, this is borky, needs to use something like cfengine or cdebconf, but for now dammit.
parted /dev/ide/host0/bus0/target0/lun0/disc rm 10 #|| die "Can't remove the preallocated partition"
parted /dev/ide/host0/bus0/target0/lun0/disc rm 11 #|| die "Can't remove the preallocated partition"

# now create the swap and the new linux partition
parted /dev/ide/host0/bus0/target0/lun0/disc mkpart primary linux-swap $start $swapend || die "Can't create swap partition"
parted /dev/ide/host0/bus0/target0/lun0/disc mkpart primary ext2 $newstart $end || die "Can't create ext2 partition"
parted /dev/ide/host0/bus0/target0/lun0/disc name 11 EXT2-CLUSTER  || die "Can't create ext2 partition"

# use parted to mke2fs and mkswap - hope this works
parted /dev/ide/host0/bus0/target0/lun0/disc mkfs 10 linux-swap || die "parted failed to mkswap on 10"
parted /dev/ide/host0/bus0/target0/lun0/disc mkfs 11 ext2 || die "parted failed to mke2fs on 11"

echo Created partitions.

# now mkswap on part10 mke2fs on part11
#mkswap /dev/discs/disc0/part10 || die "Can't mkswap"
#mke2fs -v $linux_root_partition || die "Can't mke2fs"

# okie, all set to go, let's mount the sucker and debootstrap 
echo "Creating $TARGET"
mkdir $TARGET || die "Unable to make /target"
echo "Mounting $TARGET"
mount $linux_root_partition $TARGET || die "Can't mount target"

# make all those nasty files..
echo "Creating $TARGET/etc/resolv.conf and /target/etc/network"
mkdir -p $TARGET/etc/network
cp /etc/resolv.conf $TARGET/etc/resolv.conf

# TODO Don't hardcode the root device ! This should be $linux_root_partition but devfs is confounding me.
# add devfsd to your woody script, don't call it woody either perhaps.. maintain your own for now.
echo "Creating fstab"
cat <<EOF > $TARGET/etc/fstab
# /etc/fstab: static file system information.
#
# <file system> <mount point>   <type>  <options>                       <dump>  <pass>
/dev/hda11      /               ext2    defaults,errors=remount-ro      0       1
/dev/hda10      swap            swap    defaults                        0       0
proc            /proc           proc    defaults                        0       0
/dev/cdrom      /cdrom          iso9660 defaults,ro,user,noauto         0       0
#$MASTER_SERVER:/home	/home		nfs	rsize=8192,wsize=8192		0	0
EOF


# TODO - replace 192.168.2. with $master_network
ifconfig | sed -n -e 's/.*inet addr:\(192\.168\.2\.\w*\).*/\1/p' | sed -e 's/.*\.\([0-9]\+\)$/\1/' -e 's/\(\w\w\)/0\1/' -e 's/\b\(\w\)\b/00\1/' -e 's/\(\w\w\w\)/slave\1/' > $TARGET/etc/hostname || die "Could not set hostname on target."
ifconfig | sed -n -e 's/.*inet addr:\(192\.168\.2\.\w*\).*/\1/p' > /tmp/myipaddr || die "Could not extract ip address."

echo `cat /tmp/myipaddr`	`cat $TARGET/etc/hostname`.g4cluster.prv	`cat /target/etc/hostname` > /target/etc/hosts

cp $TARGET/etc/hostname /etc/hostname || die "Failed to save to /etc/hostname."

# TODO - use busybox's hostname to set the hostname for the kernel.
#echo "127.0.0.1	slave.g4cluster.prv	slave" > $TARGET/etc/hosts

echo "auto lo" > $TARGET/etc/network/interfaces
echo "iface lo inet loopback" >> $TARGET/etc/network/interfaces
echo "auto eth0" >> $TARGET/etc/network/interfaces
echo "iface eth0 inet dhcp" >> $TARGET/etc/network/interfaces


# Splat my public key into /root/.ssh/authorized_keys
mkdir -p $TARGET/root/.ssh || die "Failed to create /target/root/.ssh"
wget http://$MASTER_SERVER/debut/authorized_keys || die "Failed to get public key."
cp authorized_keys target/root/.ssh/authorized_keys || die "Failed to copy key to $TARGET/.."

# TODO: implement wget as a function that can retry and has some intelligence
# kinda like debootstrap does huh ? soo.. umm.. redundancy here I think
# should be using a debootstrap function, or this whole thing should be
# a new or different debootstrap
# TODO - remove this when you sed out the pcmcia-cs or it honors debconf
wget http://$MASTER_SERVER/debut/debootstrap_script || die "Failed to get me script."
cp debootstrap_script /usr/lib/debootstrap/scripts/ || die "Unable to cp script into /usr/lib/debootstrap/scripts"


################################################################################################################
# This is where the action happens

debootstrap --arch powerpc $SUITE $TARGET $MIRROR/$DIRECTORY /usr/lib/debootstrap/scripts/debootstrap_script|| die "debootstrap unclean exit"
#debootstrap --arch powerpc $SUITE $TARGET $MIRROR/$DIRECTORY || die "debootstrap unclean exit"
#debootstrap --arch powerpc $SUITE $TARGET $MIRROR/$DIRECTORY || die "debootstrap unclean exit"

################################################################################################################
# POST DEBOOTSTRAP
################################################################################################################

echo "Copying sshd_config to $TARGET/etc/ssh/ ..."
mkdir $TARGET/etc/ssh || die "can't create $TARGET/etc/ssh"
cp /etc/ssh/sshd_config $TARGET/etc/ssh || die "can't copy to $TARGET/etc/ssh/sshd_config"

# Make sure we don't grab the wrong DHCP server.
echo Creating $TARGET/etc/dhclient.conf
echo "request domain, domain-name-servers, routers, subnet-mask, option-143;" > $TARGET/etc/dhclient.conf || die "Can't create /target/etc/dhclient.conf"
echo "require option-143;" >> $TARGET/etc/dhclient.conf || die "Can't append to /target/etc/dhclient.conf"

# once more stick a hostname file in, the first one dissapeared for some strange reason...
#echo "slave" > $TARGET/etc/hostname || die "can't make /target/etc/hostname - go on"
echo Creating $TARGET/etc/hostname
cp /etc/hostname $TARGET/etc/hostname || die "Could not set hostname on target."

#wget http://$MASTER_SERVER/apt-sources.list && mv apt-sources.list $TARGET/etc/apt/sources.list || die "failed apt-sources.list"
#echo Attempting to set timezone with symbolic link to $TARGET/etc/localtime
#ln -sf /usr/share/zoneinfo/Europe/Zurich $TARGET/etc/localtime || die "Couldn't set timezone."
echo Attempting to set timezone with $TARGET/etc/timezone
echo "Europe/Zurich" > $TARGET/etc/timezone

# TODO - setup base-config.
#rm $TARGET/usr/lib/base-config/77exim || die "oops rm failed"
#rm $TARGET/usr/lib/base-config/50tasksel || die "oops rm failed"
#rm $TARGET/usr/lib/base-config/60dselect || die "oops rm failed"
#rm $TARGET/usr/lib/base-config/12console-tools || die "oops rm failed"


# TODO - ensure that the non-US mirror of sunsite.cnlab-switch.ch is used
echo Creating second stage installer settings file $TARGET/root/dbootstrap_settings
cat > $TARGET/root/dbootstrap_settings <<EOF || die "failure creating dbootstrap_settings"
DEBIAN_FRONTEND=Noninteractive
SUITE=$SUITE
EOF

echo Create $TARGET/usr/lib/base-config/01localconfig
cat > $TARGET/usr/lib/base-config/01localconfig <<EOF || die "failure creating 01localconfig"
. /usr/share/debconf/confmodule
db_set apt-setup/mirror sunsite.cnlab-switch.ch
db_set apt-setup/country Switzerland
db_set apt-setup/uri_type http

db_set tzconfig/gmt true
db_set tzconfig/change_timezone false
# may need to file a bug against tzconfig

db_set apt-setup/non-us true
db_set apt-setup/contrib true
db_set apt-setup/non-free true

db_set base-config/run-dselect false
db_set base-config/run-tasksel false

# done with template sed foo
#db_set passwd/md5 true
#db_set passwd/shadow true
echo "$MASTER_SERVER:/home   /home           nfs     rsize=8192,wsize=8192           0       0" >> /etc/fstab
EOF

echo Chmod $TARGET/usr/lib/base-config/01localconfig
chmod 755 $TARGET/usr/lib/base-config/01localconfig || die "failure on chmod of 01localconfig"

# this template sed foo is done since we don't have a simple sweet way to load-templates, and db_register can't
# create a template
# HMM. busybox can't handle a <space> between addresses and 's' command.
echo Modifying $TARGET/var/lib/dpkg/into/passwd.templates to default md5
sed -e '/passwd\/md5/,/false/s/false/true/' \
  $TARGET/var/lib/dpkg/info/passwd.templates > $TARGET/var/lib/dpkg/info/passwd.templates-new || die "sed passwd template"

mv $TARGET/var/lib/dpkg/info/passwd.templates-new $TARGET/var/lib/dpkg/info/passwd.templates || die "mv passwd template"


# set-selections based on ... eg) "webots", "pvm"
# 
#
#      todpkg = popen("dpkg --set-selections", "w");
#
#    if (!todpkg) PERROR("Cannot send output to dpkg");
#    for (i = 0; i < pkgcount; i++) {
#      if (pkglist[i]->selected > 0) {
#        fprintf(todpkg, "%s install\n", pkglist[i]->name);
#        c++;
#      }
#    }

# let's do ssh just to test it and figure out how to be flexible later
echo Setting dpkg selections in $TARGET
echo "ssh install" | chroot $TARGET dpkg --set-selections - || die "dpkg --set-selections"
echo "less install" | chroot $TARGET dpkg --set-selections - || die "dpkg --set-selections"
echo "rsync install" | chroot $TARGET dpkg --set-selections - || die "dpkg --set-selections"
echo "rdate install" | chroot $TARGET dpkg --set-selections - || die "dpkg --set-selections"
echo "portmap install" | chroot $TARGET dpkg --set-selections - || die "dpkg --set-selections"
echo "xlibs install" | chroot $TARGET dpkg --set-selections - || die "dpkg --set-selections"

# these are for X-windows, should be added from web page task list
#echo "xterm install" | chroot $TARGET dpkg --set-selections - || die "dpkg --set-selections"
#echo "xutils install" | chroot $TARGET dpkg --set-selections - || die "dpkg --set-selections"
#echo "xdm install" | chroot $TARGET dpkg --set-selections - || die "dpkg --set-selections"
#echo "xserver-xfree86 install" | chroot $TARGET dpkg --set-selections - || die "dpkg --set-selections"
#echo "xfonts-base install" | chroot $TARGET dpkg --set-selections - || die "dpkg --set-selections"
#echo "xfonts-100dpi install" | chroot $TARGET dpkg --set-selections - || die "dpkg --set-selections"
#echo "xfonts-75dpi install" | chroot $TARGET dpkg --set-selections - || die "dpkg --set-selections"
#echo "xfonts-scalable install" | chroot $TARGET dpkg --set-selections - || die "dpkg --set-selections"
#echo "xfonts-pex install" | chroot $TARGET dpkg --set-selections - || die "dpkg --set-selections"

# evilwm here will break things.  since apt-setup ain't gonna like or find it.
#echo "xfonts-pex evilwm" | chroot $TARGET dpkg --set-selections - || die "dpkg --set-selections"

# make sure base-config doesn't prompt for exim configuration
# or... pull this in as well as a conf file somehow somewhere if we do indeed want it set up
# zero byte file won't work to suppress /usr/lib/base-config/77exim
# take exim.conf from a config files pacakge along with sshd_config and other that we want, sysctl.conf ...
echo "#foo" > $TARGET/etc/exim/exim.conf

# this suppresses the "Do you want to continue" prompt of /usr/lib/base-config/75apt-get
echo 'DSelect { Options "-y -f"; };' > $TARGET/etc/apt/apt.conf
echo 'DSelect { Clean "clean"; };' >> $TARGET/etc/apt/apt.conf
echo 'ACQUIRE { Retries "3"; };' >> $TARGET/etc/apt/apt.conf

# TODO - suppress last two prompts, should be able to get at least one anyway

# set up machine to run base-config on next boot
if [ -e $TARGET/etc/inittab ]; then
  mv $TARGET/etc/inittab $TARGET/etc/inittab.real || die "Could not rename inittab to inittab.real"
fi
cp /etc/inittab.install $TARGET/etc/inittab || die "Could not install inittab for base-config"

################################################################################################################
# FINISHED, SO SET LINK AND REBOOT
################################################################################################################

# get out of /target/....
cd /

sleep 2
umount $TARGET || die "Unmounting /target failed.."

# if the setlink-hda11 fails, well... then I guess we try again huh ?
wget http://$MASTER_SERVER/cgi-bin/setlink-hda11

sleep 5

/sbin/reboot # self explanatory, what are ya going to do on die huh ?

################################################################################################################
# NO MORE
################################################################################################################
