#!/bin/sh
#
# Copyright (C) 2002-2003 by NCHC, Steven Shiau, K. L. Huang
# (steven@nchc.org.tw, c00hkl00@nchc.org.tw)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# script to prepare some files for DRBL server
# Written by Steven Shiau < steven@nchc.org.tw > 2003/4/13
#
#
url_prefix="http://opensource.nchc.org.tw/"
DRBL_SCRIPT_PATH="/opt/drbl"
drbl_setup_path="$DRBL_SCRIPT_PATH/setup"
drblroot="/tftpboot/nodes"
cache_dir="/var/cache/apt/archives"
drbl_pkgdir="/opt/drbl/share/"
pxelinux_file="/usr/lib/syslinux/pxelinux.0"
memdisk_file="/usr/lib/syslinux/memdisk"
fdos_img_src="/usr/lib/freedos/fdos1440.img"
fdos_img_output="fdos1440_drbl.img"
fdos_nbi_output="fdos1440_drbl.nbi"
#
cache_dir="/var/cache/apt/archives"
#
MDK92_wget_rpm="wget-1.8.2-12mdk.i586.rpm"
MDK10_0_wget_rpm="wget-1.9.1-4mdk.i586.rpm"
# for RH and MDK, the arch is different
ARCH="i586"

# Source function library.
. /etc/rc.d/init.d/functions


# functions
#
check_apt_install() {
  RETVAL=$1
  if [ "$RETVAL" -gt 0 ]; then 
    echo "$msg_failed_to_install_pkgs"
    echo "$msg_please $msg_browse $drbl_url_zh_TW $msg_or $drbl_url_en_US $msg_for_more_details. "
    echo "$msg_press_ctrl_c_stop"
    read
    exit 1 
  fi
}

check_if_root() {
# Check if root or not
   if [ ! "$UID" = "0" ]; then
     echo
     echo "[$LOGNAME] You need to run this script \"`basename $0`\" as root."
     echo
     exit 1
   fi
}

#
check_apt_integrity() {
   apt-get -f --yes install
}

#
setup_apt_mdk() {
# define a function get_inst_rpm to get and install rpm package which 
# apt can not process now. ie. only $ARCH rpms
get_inst_rpm() {
  # example: get_inst_rpm http://os.nchc.org.tw/... glibc --force
  url_tmp="$1"
  pkg="$2"
  opt="$3"
  pkg_tmp_dir=`mktemp -d -q /tmp/$pkg.XXXXXX || exit 1`
  # note! the last / in $url must be kept!!!
  wget -r -l1 --no-parent --passive-ftp -e robots=off -q -nd -P "$pkg_tmp_dir" -A "$pkg-[0-9].*.$ARCH.rpm" $url_tmp/
  rc="$?"
  if [ $rc -gt 0 ]; then
     [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
     echo "$msg_Failed_to_get $pkg...$msg_program_stop"
     [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
     exit 1
  fi
  pkg_file=$(ls $pkg_tmp_dir/$pkg-[0-9].*.$ARCH.rpm)
  if [ "$pkg_file" != "" ]; then
    rpm -ivh $opt $pkg_file
    RETVAL=$?
    if [ "$RETVAL" -gt 0 ]; then 
       echo "$msg_Failed_to_install $pkg_file..."
       return $RETVAL
    fi
  else
    echo "XXXXXXX        XXXXXXX       XXXXXXX"
    echo "$msg_Failed_to_install \"$pkg\"!!!"
    echo "$msg_check_network_and_url $url"
    exit 1
  fi
  if [ -d $pkg_tmp_dir ]; then
    rm -rf $pkg_tmp_dir
  fi
}
# create the shared library program runtime env.
create_depmod_env() {
  local newroot="$1"
  [ -z $newroot ] && exit 1
  cp --parents /sbin/depmod $newroot
  if ldd /sbin/depmod > /dev/null 2>&1; then
    depmod_lib_need=$(ldd /sbin/depmod | cut -d" " -f3)
    cp --parents $depmod_lib_need $newroot
  fi
}
clean_depmod_env() {
  local newroot="$1"
  [ -z $newroot ] && exit 1
  [ -f $newroot/sbin/depmod ] && rm -f $newroot/sbin/depmod
  if ldd /sbin/depmod > /dev/null 2>&1; then
    depmod_lib_need=$(ldd /sbin/depmod | cut -d" " -f3)
    for f2rm in `echo $depmod_lib_need`; do
      [ -f $newroot/$f2rm ] && rm -f $newroot/$f2rm
    done
  fi
}

# Setting
# 8.0:/etc/issue or /etc/redhat-release: Red Hat Linux release 8.0 (Psyche)
# 9.0:/etc/issue or /etc/redhat-release: Red Hat Linux release 9 (Shrike)
# FC1:/etc/fedora-release: Fedora Core release 1 (Yarrow)
# $OS_Version will be the directory index for apt repository
echo "$msg_delimiter_star_line"
grep "Mandrake Linux release 9.2 (FiveStar) for i586" /etc/mandrake-release 2>/dev/null && OS_Version="MDK9.2"
grep "Mandrake Linux release 10.0 (Community) for i586" /etc/mandrake-release 2> /dev/null && OS_Version="MDK10.0"
grep "Mandrake Linux release 10.0 (Official) for i586" /etc/mandrake-release 2> /dev/null && OS_Version="MDK10.0"
echo "$msg_delimiter_star_line"
if [ -z "$OS_Version" ]; then
  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  echo "$msg_not_determine_OS"
  echo "$msg_enter_OS_ver"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  read OS_Version
  case "$OS_Version" in
  MDK9.2|MDK10.0)
              [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
              echo "The version number you entered is $OS_Version."
              [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
              ;;
  *)
              [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
              echo "$OS_Version is not supported version, program stop!."
	      echo "$msg_press_ctrl_c_stop!"
              [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
	      read
	      exit 1 
  esac
fi

#
case "$OS_Version" in
   MDK9.2|MDK10.0)
            [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
            echo "$msg_OS_version: $OS_Version"
            [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
            #http://opensource.nchc.org.tw/redhat/apt/ redhat/9/en/$ARCH/ os updates drbl... -> $url_prefix/$apt_dir $apt_list $core_dir
	    # core_dir is for the core program, for RH8 and 9, RPMS.os, set it as "os"
            #
            VER="`echo $OS_Version | sed -e 's/MDK//g'`"
            apt_dir="/mandrake/apt/"
	    # note!!! Do NOT append "/" in the end of $apt_list
	    apt_list="mandrake/i586"
	    core_dir="$VER"
            ;;
   *)
            [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
            echo "$OS_Version $msg_is_not_supported"
	    echo "$msg_press_ctrl_c_stop"
            [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
	    read
	    exit 1 
            
esac

# 0.
echo "$msg_delimiter_star_line"
DOMAINNAME=`/bin/dnsdomainname`
if [ -n "$DOMAINNAME" ]; then
    DEFAULT_PROXY="proxy.$DOMAINNAME"
fi
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_set_proxy"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
echo -n "[y/N] "
read proxy_answer
case "$proxy_answer" in
    [yY]|[yY])
      echo "$msg_http_proxy_server"
      echo -n "[$DEFAULT_PROXY] "
      read http_proxy_server_name
      echo "$msg_http_proxy_port"
      echo -n "[3128] "
      read http_proxy_server_port
      if [ -z  "$http_proxy_server_name" ]; then
          http_proxy_server_name="proxy.$DOMAINNAME"
      fi
      if [ -z  "$http_proxy_server_port" ]; then
          http_proxy_server_port="3128"
      fi

      # use the one use input for DEFAULT value. 
      echo "$msg_ftp_proxy_server"
      echo -n "[$http_proxy_server_name] "
      read ftp_proxy_server_name
      echo "$msg_ftp_proxy_port"
      echo -n "[$http_proxy_server_port] "
      read ftp_proxy_server_port
      if [ -z  "$ftp_proxy_server_name" ]; then
          ftp_proxy_server_name="$http_proxy_server_name"
      fi
      if [ -z  "$ftp_proxy_server_port" ]; then
          ftp_proxy_server_port="$http_proxy_server_port"
      fi

      echo "$msg_delimiter_star_line"
      echo "$msg_http_proxy_you_set: http://$http_proxy_server_name:$http_proxy_server_port"
      echo "$msg_ftp_proxy_you_set:  http://$ftp_proxy_server_name:$ftp_proxy_server_port"
      echo "$msg_delimiter_star_line"

      export http_proxy=http://$http_proxy_server_name:$http_proxy_server_port
      export ftp_proxy=ftp://$ftp_proxy_server_name:$ftp_proxy_server_port
      ;;
    *)
esac

# 1.
echo "$msg_delimiter_star_line"
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_which_apt_repository"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
echo "$msg_apt_repository_0"
echo "$msg_apt_repository_5"
echo -n "[0] "
read apt_freshrpms_answer
echo "$msg_delimiter_star_line"

# url is where the RPMS.os, RPMS.update, RPMS.drbl... exist
# try to get url first, we need url for get wget and apt
case "$apt_freshrpms_answer" in
    5)
      url_prefix_default="ftp://opensource.nchc.org.tw"
      apt_path_default="/distributions/mandrake/apt/mandrake/i586"
      #enter by user
      echo "Please enter the hostname or IP address of apt reposity with http or ftp prefix..."
      echo -n "[$url_prefix_default] "
      read url_prefix
      # set the default url for local apt repository as drbl.sourceforge.net
      [ -z "$url_prefix" ] && url_prefix="$url_prefix_default"
      echo "Enter the path where RPMS.$VER-$core_dir and RPMS.$VER-drbl exist..." 
      echo -n "[$apt_path_default] "
      read apt_path
      # apt_path actually is $apt_dir/$apt_list/, 
      # but we want user to answer just one question
      # set the default url for local apt repository as drbl.sourceforge.net
      [ -z "$apt_path" ] && apt_path="$apt_path_default"
      # url is for downloading "apt" rpm, 
      # while we use $url_prefix and $apt_path in sources.list
      url="$url_prefix"/"$apt_path"
      echo "------------------------------------------------------"
      echo "$msg_input_apt_url_path: $url_prefix, $apt_path"
      echo "------------------------------------------------------"
      ;;

    *)
      # default one, use opensource.nchc.org.tw
      url_prefix="http://opensource.nchc.org.tw/"
      url="$url_prefix/$apt_dir/$apt_list/"

esac
# 2. 

[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_drbl_test_option"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
echo -n "[y/N] "
read drbl_test_answer
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_firefly_option"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
echo -n "[y/N] "
read cjk_answer
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_serial_console_option"
echo "$msg_know_nothing_serial_console"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
echo -n "[y/N] "
read console_output_answer
case "$console_output_answer" in
    [yY]|[yY])
      echo "$msg_serial_console_only"
      echo -n "[y/N] "
      read serial_console_only
      echo "$msg_redirect_to_which_port"
      echo "$msg_text_Enter \"1\" for COM1, \"2\" for COM2, \"3\" for COM3, \"4\" for COM4,"
      echo -n "[1] "
      read console_port
      echo "$msg_serial_console_speed"
      echo "$msg_text_Enter \"1\" for 9600, \"2\" for 19200, \"3\" for 38400."
      echo -n "[3] "
      read console_port_speed
      ;;
    *)
esac
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_smp_clients_MDK"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
echo -n "[y/N] "
read SMP_answer

# url is where the RPMS.os, RPMS.update, RPMS.drbl... exist
#url="$url_prefix/$apt_dir/$apt_list/"

# check the installed apt is compatable with DRBL or not...
if rpm -q --quiet apt; then
   if [ -z "`rpm -q apt | grep drbl`" ]; then
      echo "$msg_delimiter_star_line"
      [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
      echo "$msg_apt_not_compatable"
      echo "$msg_do_u_want_to_remove"
      [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
      echo -n "[Y/n] "
      read rm_apt_answer
      case "$rm_apt_answer" in
            n|N|[nN][oO])
                [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
                echo "$msg_warning_apt_not_compatable_and_fail"
                [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
                exit 1
                ;;
                *)
                echo "$msg_rm_apt"
                rpm -e libapt-pkg0 apt
      esac
   fi
fi
# check if apt is installed or not
if ! rpm -q --quiet apt; then
   echo "$msg_install_apt"
   rpm -q wget &>/dev/null
   if [ "$?" -gt 0 ]; then 
      echo "$msg_no_wget_get_it"
      case "$VER" in
      9.2)
        echo "The MDK version is $VER"
        # This one only works for RH8
        rpm -ivh $url/RPMS.$VER/$MDK92_wget_rpm
        ;;
      10.0)
        echo "The MDK version is $VER"
        # This one only works for RH8
        rpm -ivh $url/RPMS.$VER/${MDK10_0_wget_rpm}
        ;;
      esac
   fi
   get_inst_rpm $url/RPMS.$VER-drbl libapt-pkg0
   get_inst_rpm $url/RPMS.$VER-drbl apt   
else
   echo "$msg_delimiter_star_line"
   echo "$msg_apt_already_installed"
   echo "$msg_delimiter_star_line"
fi

#
echo "$msg_delimiter_star_line"
if [ -f /etc/apt/sources.list ]; then
  echo "$msg_backup_apt_sources"
  mv -v /etc/apt/sources.list /etc/apt/sources.list.orig
fi

#
case "$drbl_test_answer" in
    [yY]|[yY][eE][Ss])
      DRBL_TEST="$VER-drbl-test"
      ;;
    *)
      DRBL_TEST=""
esac
case "$cjk_answer" in
    [yY]|[yY][eE][Ss])
      CJK_REPOSITORY="$VER-firefly"
      ;;
    *)
      CJK_REPOSITORY=""
esac
case "$console_output_answer" in
    [yY]|[yY][eE][Ss])
      case "$console_port" in
          2)
            PXE_CONSOLE_PORT="1"
            CONSOLE_PORT="ttyS1"
            ;;
          3)
            PXE_CONSOLE_PORT="2"
            CONSOLE_PORT="ttyS2"
            ;;
          4)
            PXE_CONSOLE_PORT="3"
            CONSOLE_PORT="ttyS3"
            ;;
          *)
            PXE_CONSOLE_PORT="0"
            CONSOLE_PORT="ttyS0"
      esac
      case "$console_port_speed" in
          1)
            CONSOLE_PORT_SPEED="9600"
            ;;
          2)
            CONSOLE_PORT_SPEED="19200"
            ;;
          *)
            CONSOLE_PORT_SPEED="38400"
      esac
      case "$serial_console_only" in
      [yY]|[yY][eE][Ss])
        # note! The latter console will dominate the whole boot message
        CONSOLE_OUTPUT="console=tty0 console=$CONSOLE_PORT,"$CONSOLE_PORT_SPEED"n81"
	;;
      *)
        CONSOLE_OUTPUT="console=$CONSOLE_PORT,"$CONSOLE_PORT_SPEED"n81 console=tty0 "
      esac
      PXE_SERIAL_OUTPUT="serial $PXE_CONSOLE_PORT $CONSOLE_PORT_SPEED"
      echo "------------------------------------------------------"
      echo "$msg_serial_console_parameter: $CONSOLE_OUTPUT"
      echo "------------------------------------------------------"
      ;;
    *)
      CONSOLE_OUTPUT=""
      PXE_SERIAL_OUTPUT=""
esac
case "$SMP_answer" in
    [yY]|[yY][eE][Ss])
      SMP_OPTION="-smp"
      ;;
    *)
      SMP_OPTION=""
esac

# set the apt sources.list
echo "$msg_setup_apt_sources_MDK $VER..."
case "$apt_freshrpms_answer" in
    5) 
      #enter by user
cat <<-APT_END > /etc/apt/sources.list
rpm $url_prefix/$apt_path . $core_dir $VER-contrib $VER-updates $VER-drbl $DRBL_TEST $CJK_REPOSITORY

APT_END

    ;;
    *)
      # default one, use opensource.nchc.org.tw
cat <<-APT_END > /etc/apt/sources.list
rpm $url_prefix/$apt_dir $apt_list $core_dir $VER-contrib $VER-updates $VER-drbl $DRBL_TEST $CJK_REPOSITORY

APT_END

esac

echo "--------------------------------------------------------------------"
echo "$msg_enjoy_apt"

} # setup_apt_mdk

install_mdk_drbl() {

# function to install mdk drbl
# setup apt first
setup_apt_mdk

#
# It's important to remove the cache of apt, otherwise 
# the RPM::Architecture will not take effect. check this:
# http://distro2.conectiva.com.br/pipermail/apt-rpm/2003-November/002015.html
# ... RPM::Architecture, is what he's looking for. His problem was that the cache was built before he set the architecture. Doing "rm -f /var/cache/apt/*.bin; apt-get update" would make it work.

echo "$msg_clean_apt_cache"
for ifile in /var/cache/apt/*.bin; do
   rm -f /var/cache/apt/$ifile
done

# Update the apt data with repository.
apt-get update

# check if apt is integrity... original MDK 9.2 is buggy...
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_check_apt_integrity"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
check_apt_integrity

#
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_delimiter_star_line"
echo "$msg_upgrade_whole_system"
echo "$msg_delimiter_star_line"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
apt-get -o RPM::Hold::="apt" upgrade


#
[ -f $drbl_pkgdir/dev.tgz ] && rm -f $drbl_pkgdir/dev.tgz

# create the directory for diskless image
[ ! -d "/tftpboot/nbi_img" ] && mkdir -p /tftpboot/nbi_img

#
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_delimiter_star_line"
echo "$msg_install_DRBL_necesary_files"
echo "$msg_delimiter_star_line"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
apt-get -y install dhcp-server tftp-server nfs-utils ypserv ypbind yp-tools mkinitrd ntp iptables
#apt-get -y install -o $latest_drbl_kernel_in_rep
apt-get -y install mkinitrd-net etherboot syslinux partimage drbl-script socket memtest86+ freedos clonezilla rh-.*-netinstall mdk-.*-netinstall cdialog initscripts rsync drakxtools pciutils autologin reiserfsprogs tcpdump bc woody-netinstall

# if no gdm, we do not install drbl-gdm
if rpm -q --quiet gdm; then
  apt-get install drbl-gdm
fi
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL

# Steven todo, for MDK 9.2... no dev rpm...I have to make one...
# It's ugly here...
# from DRBL server system ?
# 8.b
# Creat dev tarball in $drbl_pkgdir,
# which will be copied to /tftpboot/node_root/etc/diskless-image 
# in deploy script
#tmp_dev_dir=`mktemp -d -q /tmp/devtmp.XXXXXX || exit 1`
#[ ! -d $drbl_pkgdir ] && mkdir -p $drbl_pkgdir
#
#apt-get -y --download-only --reinstall install dev86 makedev
#RETVAL=$?
#check_apt_install $RETVAL
#(cd $tmp_dev_dir; rpm2cpio $cache_dir/dev86_*_i586.rpm |cpio -idm)
#(cd $tmp_dev_dir; rpm2cpio $cache_dir/makedev_*_noarch.rpm |cpio -idm)
mkdir -p $drbl_pkgdir/
cp -f $drbl_setup_path/files/dev.$OS_Version.tgz $drbl_pkgdir/dev.tgz
#(cd $tmp_dev_dir/dev; tar czf $drbl_pkgdir/dev.tgz *)
#echo "Cleaning the tmp device directory..."
#rm -rf $tmp_dev_dir

# Check if the kernel matches the user specified ?
echo "$msg_delimiter_star_line"
echo "$msg_search_kernel_in_apt kernel${SMP_OPTION} ..."
# The search in apt repository includes vanilla kernel and drbl kernel...
# if both found, drbl kernel will be used first 
# i.e. sort -g -r will make kernel-xxxdrbl be the choosen one.
# The search result by using apt-cache pkgnames, 
# in RF/FC, it looks like kernel#2.4.22-1.2199.nptldrbl
# For Mandrake, the kernel looks like kernel-2.4.22.10mdk, 
# note!!! the difference "#"
#
# note: (1) apt-cache pkgnames does not support regular expression...
#       (2) we must use drbl kernel for Mandrake, because the devfs problem...
#           The drbl kernel disable the devfs support.
#           There is no way to turn off devfs for mandrake kernel,
#           even put kernel parameter devfs=nomount, 
#           the /proc/partitions still uses devfs format!!! shit!
#           This will make partimage fail!!!
#           A bug for kernel 2.4... while for kernel 2.6, it's fixed...
drbl_kernel_in_rep=`apt-cache pkgnames kernel${SMP_OPTION}-2 | grep drbl |sort -rdn -t - -k 2,2`
# we have to compare the last tag, like 2.4.20-8, 2.4.20-31.9
# using -rnd -t - -k 2,2 just sort the 8 or 31.9, this results in 31.9. not 8.
latest_drbl_kernel_in_rep=`echo $drbl_kernel_in_rep | cut -d" " -f1`
# latest_drbl_kernel_in_rep looks like: kernel-2.4.22.28drbl
if [ -z "$latest_drbl_kernel_in_rep" ]; then
   [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
   echo "$msg_error_no_drbl_kernel_in_apt"
   echo "$msg_program_stop"
   [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
   exit 1
fi
echo "$msg_latest_kernel_in_apt $latest_drbl_kernel_in_rep"
drbl_kernel_ver=`echo $latest_drbl_kernel_in_rep | sed -e s/kernel${SMP_OPTION}-//g`
# drbl_kernel_ver looks like: 2.4.22-28drbl
# the rpm version tag is like 2.4.22.28drbl...ha... - and . different...
# It's different than what is in RedHat/Fedora...For RH/FC, they are consistent
# so replace it!
last_tag=$(echo $drbl_kernel_ver | awk -F'.' '{print $NF}')
drbl_kernel_ver=$(echo $drbl_kernel_ver | sed -e "s/\.$last_tag/-$last_tag/")


# Install kernel
# Create the necessary dirctories, UGLY...
# the /tftpboot/node_root/tmp/boot is for link only, refer to the /tftpboot/node_root/etc/rc.d/rc.sysinit, the code "# For DRBL, create the directory /tmp/boot, so that the link /tmp/boot /boot...
mkdir -p /tftpboot/node_root/tmp/boot/ /tftpboot/node_root/var/lib/ /tftpboot/nodes 
(cd /tftpboot/node_root; ln -fs tmp/boot boot)

if [ ! -d "/tftpboot/node_root/lib/modules/$drbl_kernel_ver" -a ! -f "/tftpboot/node_root/lib/modules/$drbl_kernel_ver/modules.dep" ] ; then 
   # if we did find the installed kernel in common root, install the kernel and
   # create the modules.dep

   # sync the RPM db for the node_root, cheat apt-get... otherwise apt-get will
   # try to install a base system in /tftpboot/node_root, we do not need that.
   rsync -a /var/lib/rpm /tftpboot/node_root/var/lib/
   
   # install the kernel
   apt-get -y --reinstall -o RPM::RootDir="/tftpboot/node_root/" -o RPM::Install-Options::="--force" -o RPM::Install-Options::="--nodeps" -o RPM::Install-Options::="--noscripts" install $latest_drbl_kernel_in_rep
   # clean the rpm db to avoid confusing.
   [ -d "/tftpboot/node_root/var/lib/rpm/" ] && rm -rf /tftpboot/node_root/var/lib/rpm/
   
   # create modules.dep...
   if [ -e "/tftpboot/node_root/boot/System.map-$drbl_kernel_ver" ]; then
      create_depmod_env /tftpboot/node_root
      /usr/sbin/chroot /tftpboot/node_root/ depmod -ae -F /boot/System.map-$drbl_kernel_ver $drbl_kernel_ver
      clean_depmod_env /tftpboot/node_root
   else
      echo "Can not find /tftpboot/node_root/boot/System.map-$drbl_kernel_ver $drbl_kernel_ver! Program stop!!!"
      exit 1 
   fi
fi

#
echo "$msg_delimiter_star_line"
echo "$msg_create_nbi_files"
# put and create the kernel and initrd for DRBL clients, this will be done by
# mknic-nbi
echo "$msg_latest_kernel_for_clients $drbl_kernel_ver"

# check if drbl-script is installed or not.
if ! rpm -q --quiet drbl-script; then
  [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
  echo "$msg_no_drbl_script"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  exit 1
fi
# create the NBI and PXE image for DRBL clients
# modules will be copied when user runs drblpush
case "$SMP_OPTION" in
	"-smp")
         $DRBL_SCRIPT_PATH/sbin/mknic-nbi --kernel $drbl_kernel_ver --all --smp --no-modules
         ;;
	 *)
         $DRBL_SCRIPT_PATH/sbin/mknic-nbi --kernel $drbl_kernel_ver --all --no-modules
esac
echo "$msg_Done!"

# 11.
echo "$msg_delimiter_star_line"
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo -n "$msg_create_files_for_PXE_clients"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
if [ ! -d /tftpboot/nbi_img/pxelinux.cfg ]; then
   mkdir -p /tftpboot/nbi_img/pxelinux.cfg
fi
if [ -f $pxelinux_file ]; then
   cp -f $pxelinux_file /tftpboot/nbi_img
else
   [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
   echo "$msg_Warning! $pxelinux_file $msg_NOT_found!!! $msg_PXE_NOT_work"
   echo "$msg_press_enter_to_continue"
   [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
   read
fi
if [ -f $memdisk_file ]; then
   cp -f $memdisk_file /tftpboot/nbi_img
else
   [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
   echo "$msg_Warning! $memdisk_file $msg_NOT_found!!! $msg_PXE_NOT_work"
   echo "$msg_press_enter_to_continue"
   [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
   read
fi

cat <<-PXE_END > /tftpboot/nbi_img/pxelinux.cfg/default
# note!!! if "serial" directive exists, it must be the first directive
$PXE_SERIAL_OUTPUT
default drbl
timeout 70
prompt 1
say **********************************************
say Welcome to DRBL.
say NCHC Free Software Labs, Taiwan.
say http://drbl.nchc.org.tw; http://drbl.sf.net
say **********************************************
say Boot:
say ----------------------------------------------
say (Enter) System assigned by DRBL server (default)
say (1) Linux (from DRBL server)
say (2) System in local harddrive (if available)
say (3) Memtest
say (4) Freedos
say 5 options, what's your choice ? [Enter, 1, 2, 3, 4]:

#---------------------------------
label drbl
  kernel vmlinuz-pxe
  append initrd=initrd-pxe.img ramdisk_size=9600 $CONSOLE_OUTPUT

# alias for drbl... Easier for user to select by number...
label 1
  kernel vmlinuz-pxe
  append initrd=initrd-pxe.img ramdisk_size=9600
#---------------------------------
#---------------------------------
label local
  localboot 0
# alias for local... Easier for user to select by number...
label 2
  localboot 0
#---------------------------------
#---------------------------------
label memtest
  # note! *.bin is specially purpose for syslinux, 
  # do NOT use memtest86.bin, use memtest86 instead of memtest86.bin
  kernel memtest86
label 3
  # note! *.bin is specially purpose for syslinux, 
  # do NOT use memtest86.bin, use memtest86 instead of memtest86.bin
  kernel memtest86
#---------------------------------

#---------------------------------
label fdos
  # ref: http://syslinux.zytor.com/memdisk.php
  kernel memdisk
  append initrd=$fdos_img_output
label 4
  # ref: http://syslinux.zytor.com/memdisk.php
  kernel memdisk
  append initrd=$fdos_img_output
#---------------------------------

label rh-8.0-netinstall
  kernel vmlinuz.rh8.0_netinstall
  append initrd=initrd_rh8.0_netinstall.img

label rh-9-netinstall
  kernel vmlinuz.rh9_netinstall
  append initrd=initrd_rh9_netinstall.img

label rh-FC1-netinstall
  kernel vmlinuz.FC1_netinstall
  append initrd=initrd_FC1_netinstall.img

label rh-FC2-netinstall
  kernel vmlinuz.FC2_netinstall
  append initrd=initrd_FC2_netinstall.img

label mdk-9.2-netinstall
  kernel vmlinuz.mdk9.2_netinstall
  append initrd=initrd_mdk9.2_netinstall.img

label mdk-10.0-netinstall
  kernel vmlinuz.mdk10.0_netinstall
  append initrd=initrd_mdk10.0_netinstall.img

label woody-netinstall
  kernel vmlinuz.woody_netinstall
  append initrd=initrd_woody_netinstall.img ramdisk_size=65535

PXE_END

# create the freedos image, which a clean one.
# if user wants to insert files, use 
# the script /opt/drbl/sbin/insert-file-fdos.sh
[ -f kernel.sys ] && rm -f kernel.sys
if [ -f $fdos_img_src ]; then
   img_mt=`mktemp -d fdos_img.XXXXXX`
   mount -t vfat -o loop $fdos_img_src $img_mt
   cp -f $img_mt/kernel.sys .
   umount $img_mt
   mknbi-fdos --output=/tftpboot/nbi_img/$fdos_nbi_output kernel.sys $fdos_img_src
   cp -f $fdos_img_src /tftpboot/nbi_img/$fdos_img_output
   [ -d $img_mt ] && rm -rf $img_mt
   [ -f kernel.sys ] && rm -f kernel.sys
else
   [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
   echo "$msg_Warning! $fdos_img_src $msg_NOT_found!!! $msg_FreeDOS_NOT_work"
   echo "$msg_press_enter_to_continue"
   [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL

fi

[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_Done!"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL

echo "$msg_delimiter_star_line"
echo "$msg_Done!"
} # end of install_mdk_drbl

uninstall_drbl_mdk() {

#apt-get remove dhcp-server tftp-server nfs-utils ypserv ypbind yp-tools mkinitrd ntp iptables
#apt-get remove mkinitrd-net etherboot syslinux partimage drbl-script socket memtest86+ freedos clonezilla  mdk-.*-netinstall cdialog initscripts rsync drakxtools pciutils autologin drbl-gdm

# check if apt is installed or not
if ! rpm -q --quiet apt; then
   [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
   echo "$msg_no_apt_already_uninstall"
   echo "$msg_program_stop"
   [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
   exit 1
fi

# now kernel is installed in /tftpboot/node_root directly. Comment the following:
## for Kernel, check it's being used or not
#kernel_in_use=`uname -r`
#kernel_pkg_in_use=`rpm -qf /boot/vmlinuz-${kernel_in_use}`
## ugly... but it works here...need to change ! To do!
## For RH, we have to changet the kernel pkg name used in rpm to that in apt,
## Ex: kernel-smp-2.4.20-20.9drbl -> kernel-smp#2.4.20-20.9drbl
##if echo $kernel_pkg_in_use | grep -q "kernel-smp-[0-9]"; then
##   kernel_pkg_in_use=`echo $kernel_pkg_in_use | sed -e "s/kernel-smp-/kernel-smp#/"`
##elif echo $kernel_pkg_in_use | grep -q "kernel-[0-9]"; then
##   kernel_pkg_in_use=`echo $kernel_pkg_in_use | sed -e "s/kernel-/kernel#/"`
##fi
#
#if apt-get remove --simulate -q=2 kernel.*drbl | grep ${kernel_pkg_in_use}; then
#  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
#  echo "$msg_delimiter_star_line"
#  echo "$msg_kernel_being_used: $kernel_in_use..."
#  echo "$msg_warning_not_to_remove"
#  echo "$msg_not_remove"
#  echo "$msg_delimiter_star_line"
#  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
#fi
#apt-get remove kernel.*drbl

#
apt-get remove mkinitrd-net etherboot partimage drbl-script socket memtest86+ freedos clonezilla rh-.*-netinstall mdk-.*-netinstall woody-netinstall drbl-gdm

[ -f $drbl_pkgdir/dev.tgz ] && rm -f $drbl_pkgdir/dev.tgz
echo "$msg_remove_drbl_setup_question"
echo -n "[y/N] "
read drbl_setup_answer
case "$drbl_setup_answer" in 
   y|Y|[yY][eE][sS])
      rpm -e drbl-setup
   ;;
esac
echo "$msg_remove_apt_question"
echo -n "[y/N] "
read apt_answer
case "$apt_answer" in 
   y|Y|[yY][eE][sS])
      rpm -e apt
      [ -d /var/cache/apt/ ] && echo "$msg_cleaning_apt_cache" && rm -rf /var/cache/apt/
   ;;
esac
echo "$msg_delimiter_star_line"
echo "$msg_cleaning_tftpboot"
echo "$msg_delimiter_star_line"
rm -rf /tftpboot/* 

echo "$msg_Done!!!"

}

#
Usage() {
  echo "Usage:"
  echo "$0 [-i|--install] [-l|--language] [-u|--uninstall]"
  echo "-i, --install:    install DRBL for Mandrake." 
  echo "-l, --language INDEX   Set the language to be shown with index -"
  echo "[0]: English, [1]: Chinese Traditional (Big5) - Taiwan, [2] Chinese Traditional (UTF-8, Unicode) - Taiwan."
  echo "-u, --uninstal:   uninstall DRBL for Mandrake." 
}

#
check_if_root

# main
while [ $# -gt 0 ]; do
  case "$1" in
   -l|--language)
	shift; specified_lang="$1"
	shift
	;;
   -i|--install)
        shift; mode="install"
	;;
   -u|--uninstall)
        shift; mode="uninstall"
	;;
   *)
	Usage
	exit 1
  esac
done
     
# mode is essential
[ -z "$mode" ] && Usage && exit 1

# get the language
if [ -z "$specified_lang" ]; then
  # Language
  echo "Language | y| 語言 ?".
  echo "[0]: English"
  echo "[1]: Chinese Traditional (Big5) - Taiwan |  (jX) - xW".
  echo "[2]: Chinese Traditional (UTF-8, Unicode) - Taiwan | 中文 (萬國標準碼) - 台灣"
  echo -n "[0] "
  read lang_answer
else
  lang_answer="$specified_lang"
fi
case "$lang_answer" in
   1)
      lang="tw.BIG5"
      ;;
   2)
      lang="tw.UTF-8"
      ;;
   *)
      lang="en"
esac

# get the l10n message
if [ -f "$drbl_setup_path/lang/bash/$lang" ] ; then
 . $drbl_setup_path/lang/bash/$lang
else
   echo "Not such language option!!!"
   exit 1
fi
#
echo "$msg_delimiter_star_line"

case "$mode" in
   install)
        [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
	echo $msg_install_MDK
        [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
	install_mdk_drbl
	;;
   uninstall)
        [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
	echo "$msg_uninstalling_DRBL_MDK"
	echo "$msg_analyzing_rpm_info"
        [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
	uninstall_drbl_mdk
	;;
   *)
	Usage
	exit 1
esac
