#!/bin/sh

# Author: Blake, Kuo-Lien Huang (c00hkl00@nchc.gov.tw)
# License: GPL
# Description:
#  2003/01/29 Blake, Kuo-Lien Huang (c00hkl00@nchc.gov.tw)
#    modified from knx_hdinstall
#    following are the information about knx_hdinstall
#
#    Knoppix Installation auf Festplatte
#    knx-hdinstall 0.29test
#    7/2002 Christian Perle, perle@itm.tu-clausthal.de
#

#
TARGET="/tmp/drblcd"
TMP="/tmp/hdinst.tmp.$$"
backtitle="DRBL Wizard"
title="drblcd-hdinstall"

# must be root
ID=`id -u`
if [ "$ID" != "0" ]; then
  echo "You must be root to use this script."
  echo "Use sudo to enable it for users."
  exit 1
fi

# text or x-window
case "`tty`" in
  /dev/tty[1-8])
    MODE=text
    DIA=dialog
    ;;
  /dev/pts/*|/dev/ttyp*)
    MODE=x
    XDIALOG_HIGH_DIALOG_COMPAT=1
    export XDIALOG_HIGH_DIALOG_COMPAT
    DIA=Xdialog
    ;;
  *)
    MODE=text
    DIA=dialog
    ;;
esac

if [ -z "$DISPLAY" ] ; then
  MODE=text
  DIA=dialog
fi

# main
$DIA --backtitle "$backtitle" --title "$title" \
  --msgbox "This wizard will help you to install\n\
		(1)Debian\n\
		(2)Software Packages for Cluster" 15 40 
		
# fdisk
> $TMP
NUMHD=0
if [ -f /proc/partitions ] ; then
  while read x x x p x
  do
    case "$p" in
      hd?)
        if [ "`cat /proc/ide/$p/media`" = "disk" ] ; then
          echo "$p `tr ' ' _ </proc/ide/$p/model`" >> $TMP
          NUMHD=$[NUMHD+1]
        fi
        ;;
      sd?)
        x="`scsi_info /dev/$p | grep MODEL | tr ' ' _`"
        x=${x#*\"}
        x=${x%\"*}
        echo "$p $x" >> $TMP
        NUMHD=$[NUMHD+1]
        ;;
      *) ;;
    esac
  done < /proc/partitions
fi

HARDDISKS="`cat $TMP`"
$DIA --backtitle "$backtitle" --title "$title" \
  --radiolist "Choose the disk to install:" 16 60 $NUMHD \
  $(echo "$HARDDISKS" | while read p model ; do echo "$p" "$model" off ; done) \
  2> $TMP
HDCHOICE="`cat $TMP`"

if [ -z "$HDCHOICE" ] ; then
  $DIA --backtitle "$backtitle" --title "$title" \
    --msgbox "You have to choose one disk for installation. Abort" 15 40
  rm -f $TMP
  exit 0
fi

if [ $MODE = text ]; then
  cfdisk /dev/$HDCHOICE
else
  xterm -bg black -fg white -e cfdisk /dev/$HDCHOICE
fi

# swap partition
# choice the first one linux swap partition
> $TMP
SWCHOICE=`fdisk -l /dev/$HDCHOICE | grep "^/dev.*82.*Linux swap$" | awk '{print $1;}'`
dd if=/dev/zero of=$SWCHOICE bs=1k count=16 >/dev/null 2>&1
sync
mkswap $SWCHOICE 2> $TMP
if [ $? != 0 ] ; then
  $DIA --backtitle "$backtitle" --title "$title" \
       --msgbox "/sbin/mkswap failed:\n`tail -8 $TMP`" 15 60
  rm -f $TMP
  exit 0
fi
swapon $SWCHOICE >/dev/null 2>&1

# partition && mount point && file system
# get the partition information
> $TMP
fdisk -l /dev/$HDCHOICE | grep "^/dev.*83.*Linux$" | tr -d '*' |
while read dev x x size x
do
  size=${size%+}
  echo $dev $[size/1024]_MB off >> $TMP
done
NUMPART="`wc -l $TMP | awk '{print $1;}'`"
PART="`cat $TMP`"
if [ "$MUMPART" = "0" ]; then
  $DIA --backtitle "$backtitle" --title "$title" \
    --msgbox "No Linux Partition for installation" 15 40
  rm -f $TMP
  exit 0
fi

MPNUM=3
MPLIST="/home home off /usr usr off /var var off"
MPCHOICE="/"
ROOTPART=""
while [ "$MPCHOICE" = "" -o $MPCHOICE="/" ]
do
  # choose the mouting point
  if [ "$PART" = "" -o "$MPLIST" = "" ]; then break; fi 
  if [ "$MPCHOICE" = "" ]; then
    >$TMP
    radionum=$MPNUM
    radiolist=$MPLIST
    $DIA --backtitle "$backtitle" --title "$title" \
	  --radiolist "Choose the mount point:" 20 60 $radionum $radiolist 2> $TMP
    MPCHOICE="`cat $TMP`"
    #echo $MPCHOICE
    # no more, just break it
    if [ "$MPCHOICE" = "" ]; then break; fi
	# remove $MPCHOICE from $MPLIST
    echo "$MPLIST" | awk -v D=$MPCHOICE '{ for(i=1;i<=NF;i+=3) if($i!=D) print $i " " $(i+1) " " $(i+2) " "; }' > $TMP
    MPLIST="`cat $TMP`"
    MPNUM=`expr $NUMPART - 1`
  fi
  # choose the partition 
  >$TMP
  $DIA --backtitle "$backtitle" --title "$title" \
    --radiolist "Choose the partition that will be mounted as $MPCHOICE:" \
	16 60 $NUMPART $PART 2> $TMP
  PARTCHOICE="`cat $TMP`"
  #echo $PARTCHOICE
  # remove the $PARTCHOICE from $PART
  echo "$PART" | awk -v D=$PARTCHOICE '{ if($1!=D) print $1 " " $2 " " $3 " "; }' > $TMP
  PART="`cat $TMP`"
  NUMPART=`expr $NUMPART - 1`
  #echo $NUMPART ":" $PART
  # filesystem: ext2 ext3 reiserfs xfs
  # format the partition and mount it in the target directory
  > $TMP
  radionum=4
  radiolist="ext2 ext2_fs off ext3 ext3_journalling_fs off reiserfs reiserfs_journalling_fs off xfs xfs_journalling_fs off"
  $DIA --backtitle "$backtitle" --title "$title" \
    --radiolist "Choose the filesystem type:" \
	22 60 $radionum $radiolist 2> $TMP
  FSCHOICE="`cat $TMP`"
  if [ "$FSCHOICE" = "" ]; then FSCHOICE="ext2"; fi
  #echo $FSCHOICE
  case "$FSCHOICE" in
    "ext2" | "ext3")
	  mkfs.$FSCHOICE $PARTCHOICE 2> $TMP
	  ;;
	"reiserfs" | "xfs")
      mkfs.$FSCHOICE -f $PARTCHOICE 2> $TMP
	  ;;
  esac
  if [ $? != 0 ]; then
    $DIA --backtitle "$backtitle" --title "$title" \
	  --msgbox "mkfs.$FSCHOICE failed: `tail -8 $TMP`" 15 60
	rm -f $TMP
	exit 0
  fi
  mkdir -p $TARGET/$MPCHOICE 2> $TMP
  mount -t $FSCHOICE $PARTCHOICE $TARGET/$MPCHOICE 2> $TMP
  # create fstab
  echo "$PARTCHOICE $MPCHOICE $FSCHOICE defaults,rw 0 1" >> /tmp/fstab 
  # do next one  
  if [ "$MPCHOICE" = "/" ]; then ROOTPART=$PARTCHOICE; fi
  MPCHOICE=""
done
echo "proc /proc proc defaults 0 0" >> /tmp/fstab

# copy everything to TARGET
# mkdir all directory in $TARGET directory
mkdir -p $TARGET/bin $TARGET/boot $TARGET/dev $TARGET/etc $TARGET/home $TARGET/lib $TARGET/mnt $TARGET/opt $TARGET/proc $TARGET/root $TARGET/sbin $TARGET/tmp $TARGET/usr $TARGET/var

for dir in bin boot dev etc home lib opt root sbin usr 
do cp -a /$dir/* $TARGET/$dir; done
cp -a /vmlinuz $TARGET/
# copy var.ro to $TARGET/var 
# because there are only empty directory in /var
# (see line 798 of /usr/bin/bootcdwrite for more detail)
cp -a /var.ro/* $TARGET/var

# configuration
# fstab
mv /tmp/fstab $TARGET/etc/
# recovery the init scripts we change when creating bootcd
cp /etc/init.d/modutils.orig $TARGET/etc/init.d/
# remove the init scripts that bootcd used
rm -f $TARGET/etc/rcS.d/S12bootcdram.sh
rm -f $TARGET/etc/rcS.d/S13bootcdflop.sh
# remove /opt/drblcd
rm -rf $TARGET/opt/drblcd
# hostname
DEFHNAME="base"
$DIA --backtitle "$backtitle" --title "$title" \
  --inputbox "Input the name of the host:" 12 60 $DEFHNAME 2> $TMP
HNAME="`cat $TMP`"
[ -z "$HNAME" ] && HNAME=$DEFNAME
cat <<-EOF > $TARGET/etc/hosts
127.0.0.1	$HNAME	localhost

# The following lines are desirable for IPv6 capable hosts
# (added automatically by netbase upgrade)

::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet                                            
ff00::0 ip6-mcastprefix                                         
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts
EOF
echo "$HNAME" > $TARGET/etc/hostname
echo "$HNAME" > $TARGET/etc/mailname
# ip address
cat <<-EOF > $TARGET/etc/network/interfaces
auto lo
iface lo inet loopback
EOF
NETDEVICES="$(cat /proc/net/dev | awk -F: '/eth.:|tr.:/{print $1}')"
DEVICELIST=""
NUMDEVICE=0
for DEVICE in $NETDEVICES 
do 
  DEVICELIST="$DEVICELIST ${DEVICE} network_device_${DEVICE##eth} off"
  NUMDEVICE=`expr $NUMDEVICE + 1`
done
DONAMECONF="1"
if [ "$DEVICELIST" = "" ]; then DONAMECONF="0"; fi

while [ "$DEVICELIST" != "" ]; do
  > $TMP
  $DIA --backtitle "$backtitle" --title "$title" \
    --radiolist "Choose the network device:" 16 60 $NUMDEVICE $DEVICELIST 2>$TMP
  DEVCHOICE="`cat $TMP`"
  # doesn't choose any one, just break it
  if [ "$DEVCHOICE" = "" ]; then break; fi
  # do configure
  $DIA --backtitle "$backtitle" --title "$title" \
    --inputbox "Input IP address for $DEVCHOICE:" 12 60 "" 2> $TMP
  IP="`cat $TMP`"
  #$DIA --backtitle "$backtitle" --title "$title" \
  #  --inputbox "Input NETWORK address for $DEVCHOICE:" 12 60 "" 2> $TMP
  #NETWORK="`cat $TMP`"
  $DIA --backtitle "$backtitle" --title "$title" \
    --inputbox "Input NETMASK for $DEVCHOICE:" 12 60 "" 2> $TMP
  NETMASK="`cat $TMP`"
  $DIA --backtitle "$backtitle" --title "$title" \
    --inputbox "Input BROADCAST address for $DEVCHOICE:" 12 60 "" 2> $TMP
  BROADCAST="`cat $TMP`"
  $DIA --backtitle "$backtitle" --title "$title" \
    --inputbox "Input GATEWAY address for $DEVCHOICE:" 12 60 "" 2> $TMP
  GATEWAY="`cat $TMP`" 
  NETWORK="`netmask $IP/$NETMASK | awk -F/ '{ print $1; }'`"

  cat <<-EOF >> $TARGET/etc/network/interfaces
auto $DEVCHOICE
iface $DEVCHOICE inet static
  address $IP
  netmask $NETMASK
  network $NETWORK
  broadcast $BROADCAST
EOF
  if [ "$GATEWAY" != "" ]; then 
    echo "  gateway $GATEWAY" >> $TARGET/etc/network/interfaces
  fi
  cat <<-EOF >> $TARGET/etc/networks
localnet $NETWORK
EOF
  # remove $DEVCHOICE form $DEVICELIST
  >$TMP
  echo "$DEVICELIST" | awk -v D=$DEVCHOICE '{ for(i=1;i<=NF;i+=3) if($i!=D) print $i " " $(i+1) " " $(i+2) " "; }' > $TMP
  DEVICELIST="`cat $TMP`"
  NUMDEVICE=`expr $NUMDEVICE - 1`
done
# name server
if [ "$DONAMECONF" = "1" ]; then 
  >$TMP
  $DIA --backtitle "$backtitle" --title "$title" \
    --inputbox "Input name server address:" 12 60 "" 2>$TMP
  NAMESERV="`cat $TMP`"
  if [ "$NAMESERV" != "" ]; then
    echo "nameserver $NAMESERV" > $TARGET/etc/resolv.conf
  fi
fi

# lilo.conf
cat <<-EOF > $TARGET/etc/lilo.conf
lba32
boot=/dev/$HDCHOICE
root=$ROOTPART
install=/boot/boot-menu.b
map=/boot/map
delay=0
vga=normal
default=Linux

image=/vmlinuz
	label=Linux
	read-only
EOF

# execute bootloader: lilo
lilo -r $TARGET

# fai enable or not
if [ "$FAI_ENABLE" != "" ]; then
  echo "Installing FAI..."
  # install fai
  echo "140.110.17.49	opensource.nchc.gov.tw" >> $TARGET/etc/hosts
  cat <<-EOF > $TARGET/root/fai.sh
apt-get update
apt-get -y install fai fai-kernels
# remove the create_base from /usr/sbin/make-fai-nfsroot
mv /usr/sbin/make-fai-nfsroot /usr/sbin/make-fai-nfsroot.orig
sed -e "s/call_with_stamp create_base//g" /usr/sbin/make-fai-nfsroot.orig > /usr/sbin/make-fai-nfsroot
chmod 755 /usr/sbin/make-fai-nfsroot
EOF
  chmod 755 $TARGET/root/fai.sh
  mount -t proc proc $TARGET/proc
  chroot $TARGET /root/fai.sh
  umount $TARGET/proc 

  # create fai nfsroot 
  FAIROOT=$TARGET/var/lib/diskless/default/root
  mkdir -p $FAIROOT
  mkdir -p $FAIROOT/bin $FAIROOT/boot $FAIROOT/dev $FAIROOT/etc $FAIROOT/home $FAIROOT/lib $FAIROOT/mnt $FAIROOT/opt $FAIROOT/proc $FAIROOT/root $FAIROOT/sbin $FAIROOT/tmp $FAIROOT/usr $FAIROOT/var

  for dir in bin boot dev etc lib opt root sbin usr 
  do cp -a /$dir/* $FAIROOT/$dir; done
  cp -a /vmlinuz $FAIROOT/
  # copy var.ro to $TARGET/var 
  # because there are only empty directory in /var
  # (see line 798 of /usr/bin/bootcdwrite for more detail)
  cp -a /var.ro/* $FAIROOT/var
  cp /etc/init.d/modutils.orig $FAIROOT/etc/init.d/
 
  # $TARGET/etc/fai/fai.conf
  cat <<-EOF > $TARGET/etc/fai/fai.conf
ftpserver=opensource.nchc.gov.tw
debdist=woody # distribution: potato, woody, sid

# if FAI_DEBOOTSTRAP is defined, use debootstrap, not FAI_BASETGZ
FAI_DEBOOTSTRAP="\$debdist http://\$ftpserver/debian"
#FAI_DEBOOTSTRAP="\$debdist file:/files/scratch/debian"
FAI_DEBOOTSTRAP_OPTS="--exclude=pcmcia-cs,ppp,pppconfig,pppoe,pppoeconf"

# Location of the Debian mirror; this is used for creating the nfsroot
# and for installing packages on the install clients
#
# - FAI_SOURCES_LIST can contain more than one line
#   there you can use nfs, ftp or http access. If undefined, FAI will
#   use /etc/apt/sources.list instead
# - if FAI_DEBMIRROR is defined, install clients mount it to \$MNTPOINT

# Access to Debian mirror via FTP or HTTP
FAI_SOURCES_LIST="deb http://\$ftpserver/debian \$debdist main contrib non-free
deb http://non-us.debian.org/debian-non-US \$debdist/non-US main contrib non-free"

#
# Access to Debian mirror via NFS mounted directory
#
# NFS remote location of mirror
#FAI_DEBMIRROR=kueppers:/files/scratch/
# mount point where the mirror will be mounted;
# must not be used by other filesystems
#MNTPOINT=/mnt2
# define both MNTPOINT and FAI_DEBMIRROR or none
#FAI_SOURCES_LIST="deb file:\$MNTPOINT/debian \$debdist main contrib non-free
#deb file:\$MNTPOINT/debian/ dists/\$debdist-proposed-updates/
#deb file:\$MNTPOINT/debian-non-US \$debdist/non-US main contrib non-free
#deb file:\$MNTPOINT/debian-security/ \$debdist/updates main contrib non-free"

# extra packages, that will be installed into nfsroot
# add lvm, raidtools2 only if needed
# woody packages
NFSROOT_PACKAGES="ssh expect reiserfsprogs dpkg-dev"

# the encrypted root password on all install clients during
# installation process; used when log in via ssh; pw is: fai
FAI_ROOTPW="56hNVqht51tzc"

# location of a identity.pub file; this user can log in as root
# without password ; only usefull with FAI_FLAGS="sshd"
#SSH_IDENTITY=/home/admin/.ssh/identity.pub

# this kernel package will be used when booting the install clients
KERNELPACKAGE=

# LOGUSER: an account on the install server, which saves all log-files
# and which can change the kernel that is booted via
# network. Configure .rhosts for this account and PAM , so root can
# log in from all install clients without password. This account
# should have write permissions for /boot/fai. For eg. you can use
# write permissions for the group linuxadm. chgrp linuxadm
# /boot/fai;chmod g+w /boot/fai. If the variable is undefined, this
# feature is disabled
LOGUSER=fai
# use ssh or rsh for copying log files to user fai and for changing
# tftp symbolic link
FAI_REMOTESH=rsh
FAI_REMOTECP=rcp

#
# following variables are read only for most users
#

# directory on the install server, where the nfsroot for FAI is
# created, approx size: 140MB, also defined in bootptab or dhcp.conf
NFSROOT=/var/lib/diskless/default/root

# the configuration space
FAI_CONFIGDIR=/usr/local/share/fai
# where the subroutines are
FAI_SHAREDIR=/usr/share/fai

# the local configuration directory on the install client
FAI=/fai

# the type of operating system (linux, sunos)
OS_TYPE=`uname -s |  tr '[A-Z]' '[a-z]'`

###
### NFSROOT_ETC_HOSTS && SERVER must be configured before installing it
###
# Beowulf nodes can only connect to their master server - called
# atom00 for the clients - so they must know it during
# installation. This line will be added to \$nfsroot/etc/hosts
##NFSROOT_ETC_HOSTS="192.168.42.250 atom00"

# SERVER
##SERVER=$HNAME
EOF

cat <<-EOF > $TARGET/sbin/setup.sh
echo "============= /usr/bin/fai-setup ==============="
/usr/sbin/fai-setup
rm -rf /sbin/setup.sh
echo "============= END =============================="
EOF
chmod 755 $TARGET/sbin/setup.sh

fi

rm $TMP
