#!/bin/sh

# TODO set $master_server from yaboot.conf, from DHCP with option would be even better
export master_server=`cat /proc/cmdline | sed 's/.*master=\(\(\w\+\.\)\+\w*\).*/\1/'`
export TARGET=/target

# TODO die to server's control... ? DEBIAN_FRONTEND=web ?
# 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.

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

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

# FIRST bring up the network ..
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."

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

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

echo Created partitions.

# now mkswap on part10 mke2fs on part11
linux_root_partition="/dev/discs/disc0/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
EOF

#echo "127.0.0.1	slave.g4cluster.prv	slave" > $TARGET/etc/hosts
# TODO - grap out IP address last octet and put into hostname, has to be done post-splat
#   I have no way of knowing what the IP address will be when we change to the other network.
# TODO - change boot-device using nvsetenv to tftp to internal address.
# TODO - when bootme script is rotated, so must dhcp config file be changed ! fix-this
# possible solution is to reinit network when going into cluster mode.

sed -n -e 's/.*fixed-address \(\(\w\+\.\)\+\w*\).*/\1/p' /var/dhcp/dhclient.leases | 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."
sed -n -e 's/.*fixed-address \(\(\w\+\.\)\+\w*\).*/\1/p' /var/dhcp/dhclient.leases > /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."

#echo "slave" > $TARGET/etc/hostname
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/authorized_keys2 || die "Failed to get public key."
cp authorized_keys2 target/root/.ssh/authorized_keys2 || die "Failed to copy key to $TARGET/.."

# if this fails just forget it - game over
# TODO: don't HARDCODE this.  This should be part of templates/debian-installer !
debootstrap --arch powerpc woody $TARGET http://sunsite.cnlab-switch.ch/ftp/mirror/debian/ || die "debootstrap unclean exit"

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


echo "Changing into TARGET/var/cache/apt/archives.."
cd $TARGET/var/cache/apt/archives || die "Unable to change into TARGET/var/cache/apt/archives"

echo "Retrieving extras (ssh, libssl, zlib1g).."
wget http://$master_server/extras/zlib1g_1.1.3-16.deb || die "wget pukage on retrieving libssl"
wget http://$master_server/extras/libssl0.9.6_0.9.6b-2.deb || die "wget pukage on retrieving libssl"
wget http://$master_server/extras/ssh_2.9p2-6.deb || die "wget pukage on retrieving ssh"

echo "Sourcing deboostrap functions .."
. /usr/lib/debootstrap/functions || die "Unable to source /usr/lib/debootstrap/functions"

echo "Installing ssh and libssl.."
export DEBIAN_FRONTEND=Noninteractive
in_target dpkg --install /var/cache/apt/archives/zlib1g_1.1.3-16.deb || die "Failure with chrooted dpkg install of libssl"
in_target dpkg --install /var/cache/apt/archives/libssl0.9.6_0.9.6b-2.deb || die "Failure with chrooted dpkg install of libssl"
in_target dpkg --unpack /var/cache/apt/archives/ssh_2.9p2-6.deb || die "Failure with chrooted dpkg install of libssl"

# TODO: need to merge in the templates/configdb setttings that I want.
in_target mv "/sbin/start-stop-daemon" "/sbin/start-stop-daemon.REAL" || die "shit"
in_target cp "/bin/true" "/sbin/start-stop-daemon" || die "shit"
in_target dpkg --configure ssh || die "shit"
in_target mv "/sbin/start-stop-daemon.REAL" "/sbin/start-stop-daemon" || die "shit"


## TODO: We need a /etc/apt/sources.list
#cat <<EOF > $TARGET/etc/apt/sources.list || die "Oh foo, can't make /target/etc/apt/sources.list"
## woody
#deb http://$master_server/debian/ woody main non-free contrib
##deb-src http://$master_server/debian/ woody main non-free contrib

#deb http://$master_server/debian/ woody/non-US main contrib non-free
##deb-src http://$master_server/debian/ woody/non-US main contrib non-free
#EOF

#chroot $TARGET apt-get update || die "apt-get update failed to work out right"
#chroot $TARGET apt-get install debconf-utils || die "Oh oh, problem on installing debconf-utils with apt-get"

## wget the sshdb.dat file
## TODO: don't hardcode the URL; respond to errors in a more reasonable fashion..
#cd /tmp
#wget http://$master_server/sshdb.dat || die "Failed to get sshdb.dat from http://$master_server/sshdb.dat"
#cp /tmp/sshdb.dat $TARGET/tmp/ || die "Can't copy sshdb.dat to /target/tmp/"

## merge into config.dat
#chroot $TARGET debconf-copydb configdb sshdb --config=Name:sshdb --config=Driver:File --config=Filename:/tmp/sshdb.dat || die "Argh, debconf-copydb, didn't work out."

## install ssh, non-interactively
#cat <<EOF > $TARGET/tmp/ssh-install.sh || die "Failure to create ssh install script /target/tmp/ssh-install.sh"
#!/bin/sh

#export DEBIAN_FRONTEND=noninteractive
#apt-get --yes install ssh
#EOF

#chmod 755 $TARGET/tmp/ssh-install.sh || die "Why can't I chmod /target/tmp/ssh-install.sh ?"
#chroot $TARGET /tmp/ssh-install.sh || die "Failure to run /tmp/ssh-install.sh in chroot /target"

# how does base-config figure out what to write to /etc/apt/source.list ?  ie. woody or potato
# argh.  
# I need some scripts to flop the symlinks around in /boot

# create /etc/apt/sources.list
# chroot and apt-get install ssh, with non-interactive frontend, and proper template defaults, ie. suid 'NO'

# Make sure we don't grab the wrong DHCP server.
# TODO: could we not use an "accept" instead of a "reject" ? so no hardcoding needs to be done here.
echo "Telling $TARGET/etc/dhclient.conf to reject 130.60.61.4"
echo "reject 130.60.61.4;" > $TARGET/etc/dhclient.conf || die "Can't create /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"
cp /etc/hostname $TARGET/etc/hostname || die "Could not set hostname on target."

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

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