#!/bin/sh
#
# Copyright (C) 2002-2003 by NCHC, Steven Shiau, K. L. Huang
# (steven _at_ nchc org tw, klhaung _at_ gmail com)
#
# 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.
#

# Load DRBL setting and functions
# Setting
# Source function library.
. /etc/rc.d/init.d/functions

# Source DRBL setting
. /opt/drbl/conf/drbl.conf

# Source the drbl related functions
. $DRBL_SCRIPT_PATH/sbin/drbl-functions

# functions
setup_RH_yum() {
# 1.
# OS AYO repository
echo "$msg_delimiter_star_line"
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_which_os_ayo_repository"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
echo "$msg_os_ayo_repository_0"
echo "$msg_os_ayo_repository_download_fedora_redhat_com"
echo "$msg_os_ayo_repository_use_existing_yum_config"
echo "$msg_os_ayo_repository_enter_by_yourself"
echo -n "[0] "
read os_ayo_repo_answer
echo "$msg_delimiter_star_line"
parse_RH_os_yum_repo_answer $OS_Version $os_ayo_repo_answer 

# drbl AYO repository
echo "$msg_delimiter_star_line"
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_which_drbl_ayo_repository"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
echo "$msg_drbl_ayo_repository_0"
echo "$msg_drbl_ayo_repository_1"
echo "$msg_drbl_ayo_repository_2"
echo "$msg_drbl_ayo_repository_enter_by_yourself"
echo -n "[0] "
read drbl_ayo_repo_answer
echo "$msg_delimiter_star_line"
parse_RH_drbl_yum_repo_answer $drbl_ayo_repo_answer

# ask some RPM and  apt repository options, such as drbl-testin, drbl-unstable
ask_and_parse_rpm_ayo_repo_options

generate_fedora_yum_conf

generate_drbl_yum_conf

} # end of setup_RH_yum

setup_RH_apt() {
# 1.
echo "$msg_delimiter_star_line"
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_which_os_ayo_repository"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
echo "$msg_os_ayo_repository_0"
echo "$msg_os_ayo_repository_1"
#echo "$msg_ayo_repository_2"
echo "$msg_os_ayo_repository_3"
#echo "$msg_ayo_repository_4"
echo "$msg_os_ayo_repository_5"
echo -n "[0] "
read os_ayo_repo_answer
echo "$msg_delimiter_star_line"
parse_RH_os_apt_repo_answer $OS_Version $os_ayo_repo_answer 

#
echo "$msg_delimiter_star_line"
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_which_drbl_ayo_repository"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
echo "$msg_drbl_ayo_repository_0"
echo "$msg_drbl_ayo_repository_1"
echo "$msg_drbl_ayo_repository_2"
echo "$msg_drbl_ayo_repository_3"
#echo "$msg_ayo_repository_4"
echo "$msg_drbl_ayo_repository_5"
echo -n "[0] "
read drbl_ayo_repo_answer
echo "$msg_delimiter_star_line"
parse_RH_drbl_apt_repo_answer $drbl_ayo_repo_answer

# ask some RPM and  apt repository options, such as drbl-testin, drbl-unstable
ask_and_parse_rpm_ayo_repo_options

# check if apt is installed or not
rpm -q apt &>/dev/null
if [ "$?" -gt 0 ]; then 
   echo "$msg_install_apt"
   rpm -q wget &>/dev/null
   if [ "$?" -gt 0 ]; then 
      echo "$msg_no_wget_get_it"
      WGET_idx=$(echo $OS_Version | tr "\." "_")
      # we will get the variables like wget_rpm_RH8_0, wget_rpm_FC1, wget_rpm_MDK9_2
      eval WGET_RPM=\$wget_rpm_$WGET_idx
      for irpm in $RH_RPMS_os_update_dir; do
        echo "Try to install wget from $url_os_coreroot/$irpm/$WGET_RPM..."
        rpm -ivh --quiet $url_os_coreroot/$irpm/$WGET_RPM &>/dev/null
        RETVAL=$?
        [ $RETVAL -eq 0 ] && break
      done
      # check if wget installed
      rpm -q wget &>/dev/null
      if [ "$?" -gt 0 ]; then
       echo "$msg_wget_installed_failure"
      else
       echo "$msg_wget_installed_successful"
      fi
   fi

   # install apt
   echo "$msg_no_apt_get_it"
   case "$ayo_repo_answer" in
   # if local apt repository, do not use url in the network 
   3)
     # local apt repository
     rpm -Uvh $url_drbl_rpmroot/RPMS.drbl/apt-[0-9]*.i386.rpm
     RETVAL=$?
     if [ "$RETVAL" -gt 0 ]; then 
        echo "$msg_Failed_to_install $pkg_file..."
        return $RETVAL
     fi
     ;;
   *)
     get_inst_rpm $url_drbl_rpmroot/RPMS.drbl apt i386
     rc=$?
     check_rpm_install $rc apt
   esac
else
   echo "$msg_delimiter_star_line"
   echo "$msg_apt_already_installed"
   echo "$msg_delimiter_star_line"
fi
# Clean the "Architecture "i[356]86"; "in apt.conf first,
# later we will insert Architecture "i386" to /etc/apt/apt.conf here,
perl -p -i -e "s/Architecture *\"i[356]86\".*;//g" /etc/apt/apt.conf

# backup apt sources.list if it's found.
echo "$msg_delimiter_star_line"
backup_apt_sources_list

# set the apt sources.list
# OS
case "$os_ayo_repo_answer" in
    3) 
      #local harddisk dir
cat <<-APT_END > /etc/apt/sources.list
rpm copy:$url_os/$os_ayo_path . $core_dir updates $FRESHRPMS
#rpm-src copy:$url_os/$os_ayo_path . $core_dir updates $FRESHRPMS
APT_END
    ;;
    *)
cat <<-APT_END > /etc/apt/sources.list
rpm $url_os/$os_ayo_path . $core_dir updates $FRESHRPMS
#rpm-src $url_os/$os_ayo_path . $core_dir updates $FRESHRPMS
APT_END
esac

# DRBL
case "$drbl_ayo_repo_answer" in
    3) 
      #local harddisk dir
cat <<-APT_END >> /etc/apt/sources.list
rpm copy:$url_drbl/$drbl_ayo_path . drbl $DRBL_TEST $DRBL_UNSTABLE $CJK_REPOSITORY $DRBL_EXTRA 
#rpm-src copy:$url_drbl/$drbl_ayo_path . drbl $DRBL_TEST $DRBL_UNSTABLE $CJK_REPOSITORY $DRBL_EXTRA 
APT_END
    ;;
    *)
cat <<-APT_END >> /etc/apt/sources.list
rpm $url_drbl/$drbl_ayo_path . drbl $DRBL_TEST $DRBL_UNSTABLE $CJK_REPOSITORY $DRBL_EXTRA 
#rpm-src $url_drbl/$drbl_ayo_path . drbl $DRBL_TEST $DRBL_UNSTABLE $CJK_REPOSITORY $DRBL_EXTRA 
APT_END
esac

# append some examples to sources.list 
append_RH_apt_sources_list_example

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

} # setup_RH_apt

install_drbl_RH() {
# function to install Redhat/Fedora DRBL

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 0

# clean the stale files and make necessary directories
[ -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
# even withouit apt, we still need the cache_dir to process something.
[ ! -d "$cache_dir" ] && mkdir -p $cache_dir

# 1.
# setup apt/yum first

# parse os to set the repository
parse_os_to_set_repository

if [ -z "$select_repository" ]; then
  # default setting, maybe overwritten by command option
  echo "$msg_delimiter_star_line"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  echo "$msg_do_you_want_set_yum_repo"
  echo "$msg_set_yum_conf_yes_prompt"
  echo "$msg_set_yum_conf_no_prompt"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  echo -n "[y/N] "
  read set_repo_ans 
  case "$set_repo_ans" in
     y|Y|[yY][eE][sS])
       select_repository="yes"
       ;;
     *)
       select_repository="no"
       ;;
  esac
fi

if [ "$select_repository" = "yes" ]; then 
  setup_${OS_type}_${installer}
else
  # put drbl-core yum repos conf
  [ ! -d "/etc/yum.repos.d" ] && mkdir -p /etc/yum.repos.d
  # backup the old setting
  repo_lists="drbl.repo drbl-testing.repo drbl-unstable.repo drbl-extra.repo"
  for ifile in $repo_lists; do
    [ -f "/etc/yum.repos.d/$ifile" ] && mv -f /etc/yum.repos.d/$ifile /etc/yum.repos.d/$ifile.drblsave
  done
  cp -f $DRBL_SCRIPT_PATH/setup/yum-repos/drbl*.repo /etc/yum.repos.d/

  # ask some RPM and  apt repository options, such as drbl-testin, drbl-unstable
  ask_and_parse_rpm_ayo_repo_options
  # turn on some branches if set
  [ -n "$DRBL_TEST" ] && perl -pi -e "s/^[[:space:]]*enabled=.*/enabled=1/gi" /etc/yum.repos.d/drbl-testing.repo
  [ -n "$DRBL_UNSTABLE" ] && perl -pi -e "s/^[[:space:]]*enabled=.*/enabled=1/gi" /etc/yum.repos.d/drbl-unstable.repo
  # [ -n "$DRBL_EXTRA" ] && perl -pi -e "s/^[[:space:]]*enabled=.*/enabled=1/gi" /etc/yum.repos.d/drbl-extra.repo

  # we need $url_os, "$os_ayo_path"and "$url_os_coreroot for kernel and dev
  # try to parse the yum config in the system
  # We will search CentOS-base.repo, fedora.repo in /etc/yum.repos.d/
  # TODO: maybe search all the *.repo in /etc/yum.repos.d/ ?
  echo "$msg_delimiter_star_line"
  echo "Try to find yum repository url..."
  for i in CentOS-Base fedora; do
    if [ -f "/etc/yum.repos.d/${i}.repo" ]; then
      if ! rpm -q --quiet lynx; then
        [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
	echo "$msg_need_lynx_to_parse_config"
        [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
	$installer -y install lynx
      fi
      url_tmp="$($DRBL_SCRIPT_PATH/bin/find-url-in-yum-set /etc/yum.repos.d/${i}.repo ${OS_Version:2} $ARCH 2>/dev/null)"
      if [ -n "$url_tmp" ]; then
        url_os="$(echo $url_tmp | awk -F' ' '{print $1}')"
        os_ayo_path="$(echo $url_tmp | awk -F' ' '{print $2}')"
        url_os_coreroot=$url_os/$os_ayo_path
        echo "$msg_delimiter_star_line"
        echo "Use yum repository in $url_os_coreroot"
	break
      fi
    fi
  done
  if [ -z "$url_os" ]; then
    # Not found, use the default one...
    echo "Unable to find the repository in the system, use DRBL default one."
    parse_${OS_type}_os_${installer}_repo_answer $OS_Version default
    parse_${OS_type}_drbl_${installer}_repo_answer default
    echo "Use yum repository in $url_os_coreroot"
  fi
fi

# ask some setting for client, such as SMP, serial console...
ask_and_parse_client_extra_setting

# parse the setting of client archi.
parse_client_archi_setting

# import RPM key for yum, the default setting of yum enables key check.
[ "$installer" = "yum" ] && import_rpm_key

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

if [ "$installer" = "apt" ]; then
  echo "$msg_clean_apt_cache"
  for ifile in /var/cache/apt/*.bin; do
     rm -f /var/cache/apt/$ifile
  done
fi

# Update the apt data with repository.
# if it's yum, skip this, later yum will do it. Because yum update will also
# do upgrade...
[ "$installer" = "apt" ] && $inst_prog update

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

# 3.
# We will upgrade system first.
# Try to find if the i386 glibc and openssl are installed or not
# If they are installed, hold them not to be upgraded to i686
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_upgrade_system_question"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
echo -n "[Y/n] "
read upgrade_system_answer
case "$upgrade_system_answer" in 
   n|N|[nN][oO])
      ;;
   *)
      do_upgrade_system_for_RH
      ;;
esac

# After the dist upgrade, check the ARCH for glibc, openssl
glibc_ARCH=""
glibc_VER=""
openssl_ARCH=""
openssl_VER=""
rpm -q --qf '%{ARCH}' glibc > /dev/null && glibc_ARCH=`rpm -q --qf '%{ARCH}' glibc`
rpm -q --qf '%{ARCH}' openssl > /dev/null && openssl_ARCH=`rpm -q --qf '%{ARCH}' openssl`
rpm -q --qf '%{VERSION}' glibc > /dev/null && glibc_VER=`rpm -q --qf '%{VERSION}' glibc`
rpm -q --qf '%{VERSION}' openssl > /dev/null && openssl_VER=`rpm -q --qf '%{VERSION}' openssl`

#if [ $glibc_ARCH = "i386" ] && [ $openssl_ARCH = "i386" ]; then 
#  apt-get dist-upgrade -o RPM::Hold::="openssl" -o RPM::Hold::="glibc"
#else
#  apt-get dist-upgrade
#fi
# After contacting Gustavo Niemeyer <niemeyer@conectiva.com>, 
# new function in apt 0.5.5cnc3, check:http://moin.conectiva.com.br/AptRpm
# * mplemented RPM architecture setting. Packages "above" the given architecture will be considered invalid for the current machine. For example, if RPM::Architecture is set to "i386" in an i686 machine, only i386 and noarch packages will be considered valid. 

# 4.
# Install the necessary packages for DRBL 
echo "$msg_delimiter_star_line"
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_install_DRBL_necesary_files"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
echo "$msg_delimiter_star_line"
echo "$msg_install_dhcp_tftp_etc"
# Tune!
# Bugs fix for nfs-util, otherwise these is a bug about nfs over root 
# related links:
# http://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=76065
# if not, you will see a lot of 
# "kernel: lockd: rejected NSM callback from 7f000001:1027" in the console and
# /var/log/messages
# if upgrade first time, it's better to reboot

# wget maybe not installed, we will check it is installed only when apt is not installed, so if apt/yum is installed while wget is not installed, get_inst_rpm() will failed! Add wget here.
$inst_prog -y install dhcp tftp-server nfs-utils ypserv ypbind yp-tools mkinitrd ntp firstboot iptables wget mkinitrd-net etherboot syslinux partimage socket memtest86+ freedos clonezilla dialog initscripts rsync parted reiserfs-utils tcpdump bc grub dos2unix ddrescue lynx lftp
# TODO
RETVAL=$?
check_apt_install $RETVAL

# 5.
install_client_archi_glibc_openssl

# 6.
# mkinitrd-net, modified from mkinitrd-net of Mandrake 9.0 by Steven Shiau

echo "$msg_delimiter_star_line"
# 7.
# 7.a
# ugly...in the future we can delete this one... this is due to to old version
# memtest86 and new memtest86+ conflicts...and can not be upgrade due to version
# number reset.
for ipackage in memtest86 rh-netinstall mdk-netinstall; do
   if rpm -q --quiet $ipackage; then
      echo -n "$msg_removing_the_old $ipackage..."
      rpm -e $ipackage
      echo "$msg_done!"
   fi
done

# ugly...might be not my fault...
# for some distribution some version, we have to force upgrading some packages.
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_try_to_update_some_pkgs"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
case "$OS_Version" in
  "RH8.0"|"RH9")
        # This one only works for RH8
        $inst_prog -y install redhat-config-xfree86
        ;;
  "FC1")
        # gpm is buggy, can not work with clonezilla, so upgrage to mine
	# in drbl repository
        echo "$msg_OS_version: $OS_Version."
	echo "$msg_force_to_upgrade_some_pkgs"
	$inst_prog -y install gpm redhat-config-xfree86
        ;;
  FC*)
        # FC2 use different name "system-config-display" instead of "redhat-config-xfree86"
        echo "$msg_OS_version: $OS_Version."
	echo "$msg_force_to_upgrade_some_pkgs"
	$inst_prog -y install system-config-display
        ;;
esac

# netinstall
if [ "$DRBL_NETINSTALL" = "yes" ]; then
  echo "$msg_delimiter_star_line"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  echo "$msg_install_net_install_images"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  echo "$msg_delimiter_star_line"
  $inst_prog -y install $net_install_pkgs
  # TODO
  RETVAL=$?
  check_apt_install $RETVAL
fi

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

echo "$msg_delimiter_star_line"
echo "$msg_creating_dev"
# clean the old files if the exists
rm -f $cache_dir/dev[-_]*.i386.rpm $cache_dir/MAKEDEV[-_]*.i386.rpm

# get dev
echo "$msg_get_dev"
     dev_got=0
     for ipkg in dev MAKEDEV; do
      for idir in $RH_RPMS_os_update_dir; do
	echo "Try to download $ipkg rpm from $url_os_coreroot/$idir/..." 
        wget -r -l1 --no-parent --passive-ftp -e robots=off -q -nd --retr-symlinks -P "$cache_dir" -A "$ipkg-[0-9]*.i386.rpm" $url_os_coreroot/${idir}/
        # once it's done, skip the next search
	if [ "$(ls $cache_dir/$ipkg-[0-9]*.i386.rpm 2> /dev/null)" ]; then
          echo "Got the $ipkg rpm!"
	  dev_got=1
          break
	else
          echo "\"$ipkg\" is not found in $url_os_coreroot/$idir/."
        fi
      done
      # if we can not download dev rpm, then skip the MAKEDEV download.
      [ "$dev_got" = 0 ] && break
     done
(
  if [ -n "$(ls $cache_dir/dev[-_]*.i386.rpm 2>/dev/null)" -a -n "$(ls $cache_dir/MAKEDEV[-_]*.i386.rpm 2>/dev/null)" ]; then
    cd $tmp_dev_dir
    echo -n "Creating the device files for DRBL client..."
    # To avoid the duplicated rpms... just find the latest one.
    latest_dev="$($DRBL_SCRIPT_PATH/bin/list_latest_rpm $cache_dir/ | grep -E "^dev[-_].*.i386.rpm")"
    latest_MAKEDEV="$($DRBL_SCRIPT_PATH/bin/list_latest_rpm $cache_dir/ | grep -E "^MAKEDEV[-_].*.i386.rpm")"
    rpm2cpio $cache_dir/$latest_dev | cpio -idm
    rpm2cpio $cache_dir/$latest_MAKEDEV | cpio -idm
    cd $tmp_dev_dir/dev && tar czf $drbl_pkgdir/dev.tgz *
    echo "done!"
  else
    echo "Unable to find dev and MAKEDEV rpm... The DRBL client will use udev..."
    # we must install udev...
    if ! rpm -q --quiet udev; then
      echo -n "Try to install udev..."
      $inst_prog -y install udev
      echo "done!"
    fi
    if ! rpm -q --quiet udev; then
      echo "No udev, and no pre-packaged devices file!!! Program terminated!"
      exit 1
    fi
  fi
)
echo "$msg_clean_tmp_dev"
[ -d "$tmp_dev_dir" ] && rm -rf $tmp_dev_dir

# 8.
echo "$msg_delimiter_star_line"
# Force to install all the kernel selected.
# Ref:
# http://distro.conectiva.com.br/pipermail/apt-rpm/2003-December/002119.html
echo "$msg_search_kernel_in_ayo kernel${SMP_OPTION} ..."

install_client_kernel

# 9.
# make the nbi/pxe files
create_pxe_nbi_files

# 10.
# force client not to use devfs
if [ -n "$CONSOLE_OUTPUT" ]; then
  echo -n "$msg_make_client_serial_console"
  # Notes, there are at least 3 "option etherboot.kernel-cmdline", so 
  # just the one - option etherboot.kernel-cmdline " mount=devfs" is replaced
  # ...
  perl -p -i -e "s/option etherboot.kernel-cmdline \".*\".*;/option etherboot.kernel-cmdline \" $CONSOLE_OUTPUT devfs=nomount\" ;/g" /etc/dhcpd.conf.etherboot.include
  echo "$msg_done!"
fi
# 11.
echo "$msg_delimiter_star_line"
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_create_files_for_PXE_clients"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
create_files_for_PXE_clients

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

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

# if apt is not installed, the installer must be yum
if ! rpm -q --quiet apt; then
   installer="yum"
   inst_prog="yum"
fi

# rm the YP securenets
$DRBL_SCRIPT_PATH/sbin/drbl-yp-securenets off

#
# skip removing dialog, rsync... which are usually necessary.
# TODO, separate ntp, it seems that to remove ntp together will fail in FC3 
# with yum.
$inst_prog remove dhcp tftp-server nfs-utils ypserv ypbind yp-tools etherboot syslinux partimage socket memtest86+ freedos clonezilla dos2unix ddrescue lynx 
$inst_prog remove ntp

$inst_prog remove $net_install_pkgs

$inst_prog remove drbl-driver-.*

# rename some config files if they still exist
for icfg in dhcpd.conf exports ntp.conf sysconfig/iptables; do
  [ -f "/etc/${icfg}" ] && mv -f /etc/${icfg} /etc/${icfg}.drblsave 
done

# remove the stale file
[ -f "/etc/init.d/ocs" ] && rm -f /etc/init.d/ocs

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
   ;;
esac
if [ "$installer" = "apt" ]; then
  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
else
  echo "$msg_remove_yum_repo_question"
  echo -n "[y/N] "
  read yum_repo_answer
  case "$yum_repo_answer" in 
   y|Y|[yY][eE][sS])
     # we won't touch the existing fedora.repo fedora-updates.repo
     repo_lists="drbl.repo drbl-testing.repo drbl-unstable.repo drbl-extra.repo fedora.repo fedora-updates.repo drbl.repo drbl-testing.repo drbl-unstable.repo"
     for ifile in $repo_lists; do
       [ -f "/etc/yum.repos.d/$ifile" ] && mv -v /etc/yum.repos.d/$ifile /etc/yum.repos.d/$ifile.drblsave
     done
  esac
fi

# clean tftpboot and misc files.
clean_tftpboot_and_misc

echo "$msg_Done!!!"

} # end of uninstall_drbl_RH

#
setup_MDK_apt() {
# Setting
echo "$msg_delimiter_star_line"

# 1.
echo "$msg_delimiter_star_line"
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_which_os_ayo_repository"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
echo "$msg_os_ayo_repository_0"
echo "$msg_os_ayo_repository_1_mdk"
echo "$msg_os_ayo_repository_2_mdk"
echo "$msg_os_ayo_repository_5"
echo -n "[0] "
read mdk_os_ayo_repo_answer
echo "$msg_delimiter_star_line"
parse_MDK_os_ayo_repo_answer $mdk_os_ayo_repo_answer

echo "$msg_delimiter_star_line"
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_which_drbl_ayo_repository"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
echo "$msg_drbl_ayo_repository_0"
echo "$msg_drbl_ayo_repository_1_mdk"
echo "$msg_drbl_ayo_repository_2_mdk"
echo "$msg_drbl_ayo_repository_5"
echo -n "[0] "
read mdk_drbl_ayo_repo_answer
echo "$msg_delimiter_star_line"
parse_MDK_drbl_ayo_repo_answer $mdk_drbl_ayo_repo_answer

# ask some RPM and  apt repository options, such as drbl-testin, drbl-unstable
ask_and_parse_rpm_ayo_repo_options

# check if apt is installed or not
if rpm -q --quiet apt || rpm -q --quiet libapt-pkg0; then
   if [ -n "$(rpm -q apt | grep drbl)" -o -n "$(rpm -q libapt-pkg0 | 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"
		# Try to uninstall libapt-pkg0 and apt saparately... otherwise one fails will make all fail!!! libapt-pkg0 must be first one to be removed.
                rpm -v -e apt
                rpm -v -e libapt-pkg0
      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
   RC=$?
   if [ "$RC" -gt 0 ]; then 
      echo "$msg_no_wget_get_it"
      WGET_idx=$(echo $OS_Version | tr "\." "_")
      # we will get the variables like wget_rpm_RH8_0, wget_rpm_FC1, wget_rpm_MDK9_2
      eval WGET_RPM=\$wget_rpm_$WGET_idx
      for irpm in $MDK_RPMS_os_update_dir; do
        echo "Try to install wget from $url_os_coreroot/$irpm/$WGET_RPM..."
        rpm -ivh --quiet $url_os_coreroot/$irpm/$WGET_RPM &>/dev/null
        RETVAL=$?
        [ $RETVAL -eq 0 ] && break
      done
      # check if wget installed
      rpm -q wget &>/dev/null
      if [ "$?" -gt 0 ]; then
       echo "$msg_wget_installed_failure"
      else
       echo "$msg_wget_installed_successful"
      fi
   fi

   # install apt... for MDK, we need to install libapt-pkg0 first...
   # but how about other dependance ? well, from MDK 10.1, we will
   # use urpmi, no more apt...
   echo "$msg_no_apt_get_it"
   for ipkg in libapt-pkg0 apt; do
     get_inst_rpm $url_drbl_rpmroot/RPMS.drbl $ipkg $ARCH
     if ! rpm -q --quiet $ipkg; then
       echo "$msg_Failed_to_install \"$ipkg\"!!!"
       echo "Program terminated!!!"
     fi
   done
else
   echo "$msg_delimiter_star_line"
   echo "$msg_apt_already_installed"
   echo "$msg_delimiter_star_line"
fi

# backup apt sources.list if it's found.
echo "$msg_delimiter_star_line"
backup_apt_sources_list

# set the apt sources.list
echo "$msg_setup_apt_sources_MDK $MDK_VER..."
cat <<-APT_END > /etc/apt/sources.list
# Mandrake core
rpm $url_os/$os_ayo_path/$MDK_VER/i586/$media/ $media_info/hdlist $main_rpmdir
# Mandrake contrib
rpm $url_os/$os_ayo_path/$MDK_VER/i586/$media/ $media_info/hdlist2 $contrib_rpmdir
# Mandrake jpackage
rpm $url_os/$os_ayo_path/$MDK_VER/i586/$media/ $media_info/hdlist3 $jpackage_rpmdir

# Mandrake updates
rpm $url_os/$os_ayo_path/updates/$MDK_VER/ $main_updates/hdlist $update_rpmdir

# DRBL related.
rpm $url_drbl/$drbl_ayo_path base/hdlist.drbl RPMS.drbl
APT_END

# append the drbl-test/drbl-unstable if necessary
if [ -n "$DRBL_TEST" ]; then
  cat <<-APT_END >> /etc/apt/sources.list
rpm $url_drbl/$drbl_ayo_path base/hdlist.drbl-test RPMS.drbl-test
APT_END
fi

if [ -n "$DRBL_UNSTABLE" ]; then
  cat <<-APT_END >> /etc/apt/sources.list
rpm $url_drbl/$drbl_ayo_path base/hdlist.drbl-unstable RPMS.drbl-unstable
APT_END
fi

# if [ -n "$DRBL_EXTRA" ]; then
#  cat <<-APT_END >> /etc/apt/sources.list
# rpm $url_drbl/$drbl_ayo_path base/hdlist.drbl-extra RPMS.drbl-extra
# APT_END
# fi

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

} # setup_MDK_apt

#
setup_MDK_urpmi() {
# Setting
echo "$msg_delimiter_star_line"

# 1.
echo "$msg_delimiter_star_line"
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_which_os_ayo_repository"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
echo "$msg_os_ayo_repository_0"
echo "$msg_os_ayo_repository_1_mdk"
echo "$msg_os_ayo_repository_2_mdk"
echo "$msg_os_ayo_repository_5"
echo -n "[0] "
read mdk_os_ayo_repo_answer
echo "$msg_delimiter_star_line"
parse_MDK_os_ayo_repo_answer $mdk_os_ayo_repo_answer

echo "$msg_delimiter_star_line"
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_which_drbl_ayo_repository"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
echo "$msg_drbl_ayo_repository_0"
echo "$msg_drbl_ayo_repository_1_mdk"
echo "$msg_drbl_ayo_repository_2_mdk"
echo "$msg_drbl_ayo_repository_5"
echo -n "[0] "
read mdk_drbl_ayo_repo_answer
echo "$msg_delimiter_star_line"
parse_MDK_drbl_ayo_repo_answer $mdk_drbl_ayo_repo_answer

# ask some RPM and  apt repository options, such as drbl-testin, drbl-unstable
ask_and_parse_rpm_ayo_repo_options

# TODO: find a method to keep the existing OS uprmi, but overwrite the DRBL urpmi
[  -f "/etc/urpmi/urpmi.cfg" ] && cp -v /etc/urpmi/urpmi.cfg /etc/urpmi/urpmi.cfg.drblsave
echo "$msg_delimiter_star_line"
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "Removing the old urpmi setting..."
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
echo "$msg_delimiter_star_line"
urpmi.removemedia -a

echo "$msg_delimiter_star_line"
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "Adding urpmi source..."
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
echo "$msg_delimiter_star_line"
# OS
urpmi.addmedia MDK${MDK_VER}-core $url_os/$os_ayo_path/$MDK_VER/i586/$media/$main_rpmdir
urpmi.addmedia MDK${MDK_VER}-contrib $url_os/$os_ayo_path/$MDK_VER/i586/$media/$contrib_rpmdir
urpmi.addmedia MDK${MDK_VER}-jpackage $url_os/$os_ayo_path/$MDK_VER/i586/$media/$jpackage_rpmdir
urpmi.addmedia MDK${MDK_VER}-updates $url_os/$os_ayo_path/updates/$MDK_VER/$update_rpmdir

# DRBL
urpmi.addmedia drbl-stable $url_drbl/$drbl_ayo_path/base with synthesis.hdlist.drbl.cz
if [ -n "$DRBL_TEST" ]; then
  urpmi.addmedia drbl-testing $url_drbl/$drbl_ayo_path/base with synthesis.hdlist.drbl-test.cz
fi
if [ -n "$DRBL_UNSTABLE" ]; then
  urpmi.addmedia drbl-unstable $url_drbl/$drbl_ayo_path/base with synthesis.hdlist.drbl-unstable.cz
fi
# if [ -n "$DRBL_EXTRA" ]; then
#   urpmi.addmedia drbl-extra $url_drbl/$drbl_ayo_path/base with synthesis.hdlist.drbl-extra.cz
# fi

echo "--------------------------------------------------------------------"
echo "The urpmi setting is finished."

} # setup_MDK_apt

install_drbl_MDK() {
# function to install MDK DRBL

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 0

# clean the stale files and make necessary directories
[ -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

# 1.
# parse os to set the repository
parse_os_to_set_repository

if [ "$select_repository" = "yes" ]; then 
  setup_${OS_type}_${installer}
else
  # we need $url_os, "$os_ayo_path"and "$url_os_coreroot for kernel and dev
  # for MDK, apt and urpmi use the same function, it's different with RH.
  parse_${OS_type}_os_ayo_repo_answer default $OS_Version
  parse_${OS_type}_drbl_ayo_repo_answer default
fi

# ask some setting for client, such as SMP, serial console...
ask_and_parse_client_extra_setting

# for MDK, we do not have to check arch, it's only i586, so comment this.
# parse_client_archi_setting

#
case "$installer" in
  "apt")
    inst_prog="apt-get"
    inst_opt="-y"
    inst_action="install"
  ;;
  "urpmi")
    inst_prog="urpmi"
    inst_opt="--auto"
    inst_action=""
  ;;
  *)
    # maybe other installer, just in case...
    echo "The installer is not apt, not urpmi. \"$installer\" is not a supported installer. Program terminated!!!"
    exit 1
esac

if [ "$installer" = "apt" ]; then
  #
  # 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

  # 2.
  # 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

fi

# 3.
# We will upgrade system first.
echo "$msg_delimiter_star_line"
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_upgrade_system_question"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
echo -n "[Y/n] "
read upgrade_system_answer
case "$upgrade_system_answer" in 
   n|N|[nN][oO])
      ;;
   *)
      do_upgrade_system_for_MDK
      ;;
esac

# 4.
# Install the necessary packages for DRBL 
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_delimiter_star_line"
echo "$msg_install_DRBL_necesary_files"
echo "$msg_delimiter_star_line"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
$inst_prog $inst_opt $inst_action dhcp-server tftp-server nfs-utils ypserv ypbind yp-tools mkinitrd ntp iptables wget mkinitrd-net etherboot syslinux partimage socket memtest86+ freedos clonezilla cdialog initscripts rsync parted drakxtools pciutils autologin reiserfsprogs tcpdump bc grub dos2unix ddrescue lynx lftp

# netinstall
# Get the available netinstall rpms:
# urpmq will output the resutl to stderr... Strange! Anyway, redirect to stdout
netinstall_for_urpmi="$(urpmq netinstall 2>&1 | grep -E "(^mdk-|^rh-|^rh-FC|^woody|^CentOS)" | sort)"
eval net_install_pkgs=\$netinstall_for_${installer}

if [ "$DRBL_NETINSTALL" = "yes" ]; then
  echo "$msg_delimiter_star_line"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  echo "Installing some Linux distribution network installation images..."
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  echo "$msg_delimiter_star_line"
  $inst_prog $inst_opt $inst_action $net_install_pkgs
fi

# Steven todo, for MDK 9.2... no dev rpm...It's necessary to make one before run
# this... (Just create the tarball from some Mandrake machine)
# It's ugly here...
# 8.b
[ ! -d $drbl_pkgdir ] && mkdir -p $drbl_pkgdir
# dev
if [ -f $drbl_setup_path/files/dev.$OS_Version.tgz ]; then
  cp -f $drbl_setup_path/files/dev.$OS_Version.tgz $drbl_pkgdir/dev.tgz
else
  # we must install udev...
  if ! rpm -q --quiet udev; then
    echo -n "Try to install udev..."
    $inst_prog $inst_opt $inst_action udev
    echo "done!"
  fi
  if ! rpm -q --quiet udev; then
    echo "No udev, and no pre-packaged devices file!!! Program terminated!"
    exit 1
  fi
fi

# 8.
echo "$msg_delimiter_star_line"
# Force to install all the kernel selected.
# Ref:
# http://distro.conectiva.com.br/pipermail/apt-rpm/2003-December/002119.html
echo "$msg_search_kernel_in_ayo kernel${SMP_OPTION} ..."

install_client_kernel

# 9.
# make the nbi/pxe files
create_pxe_nbi_files

# 10.
# skip forcing client not to use devfs... it's MDK... we need devfs for version
# using kernel 2.4 (like MDK 9.2).

# 11.
echo "$msg_delimiter_star_line"
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo -n "$msg_create_files_for_PXE_clients"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
create_files_for_PXE_clients

echo "$msg_delimiter_star_line"
echo "$msg_Done!"

} # end of install_drbl_MDK

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

# if apt is not installed, the installer must be urpmi
if ! rpm -q --quiet apt; then
   installer="urpmi"
   uninst_prog="urpme"
   uninst_action=""
else
   installer="apt"
   uninst_prog="apt-get"
   uninst_action="remove"
fi

# Get the installed netinstall rpms, this is special for MDK urpme... 
# for RH/FC, it's easier... just use regular expression package name (like rh-.*-netinstall)
net_install_pkgs="$(rpm -qa | grep -i netinstall | grep -E "(^mdk-|^rh-|^rh-FC|^woody|^CentOS)" | sort)"

# rm the YP securenets
$DRBL_SCRIPT_PATH/sbin/drbl-yp-securenets off

# skip syslinux uninstallation in MDK, it will remove basesystem...
# FOR MDK 9.2, there is no dos2unix, well, do not uninstall dos2unix for all.
$uninst_prog $uninst_action dhcp-server tftp-server nfs-utils ypserv ypbind yp-tools etherboot partimage mkinitrd-net etherboot partimage socket memtest86+ freedos clonezilla ddrescue lynx 
$uninst_prog $uninst_action ntp

[ -n "$net_install_pkgs" ] && $uninst_prog $uninst_action $net_install_pkgs

# rename some config files if they exist
for icfg in dhcpd.conf exports ntp.conf sysconfig/iptables; do
  [ -f "/etc/${icfg}" ] && mv -f /etc/${icfg} /etc/${icfg}.drblsave 
done

# remove the stale file
[ -f "/etc/init.d/ocs" ] && rm -f /etc/init.d/ocs

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
   ;;
esac

if [ "$installer" = "apt" ]; then
  echo "$msg_remove_apt_question"
  echo -n "[y/N] "
  read apt_answer
  case "$apt_answer" in 
     y|Y|[yY][eE][sS])
        rpm -e libapt-pkg0 apt
        [ -d /var/cache/apt/ ] && echo "$msg_cleaning_apt_cache" && rm -rf /var/cache/apt/
     ;;
  esac
else
  echo "$msg_remove_urpmi_media_question"
  echo -n "[y/N] "
  read urpmi_media_answer
  case "$urpmi_media_answer" in 
     y|Y|[yY][eE][sS])
       urpmi.removemedia -a
     ;;
  esac
fi

# clean tftpboot and misc files.
clean_tftpboot_and_misc

echo "$msg_Done!!!"

} # end of uninstall_drbl_MDK

# common functions for DRBL in RedHat/Fedora/Mandrake Linux.

#
apt_install_result_msg() {
  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_apt_install() {
  local 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_rpm_install() {
  local RETVAL=$1
  local pkg=$2
  if [ "$RETVAL" -gt 0 ]; then
  echo "XXXXXXX        XXXXXXX       XXXXXXX"
  echo "$msg_Failed_to_install \"$pkg\"!!!"
  echo "$msg_check_network_and_url $url"
  exit 1
  fi
}

# define a function get_inst_rpm to get and install rpm package which 
# apt can not process now. ie. only i386 rpms
get_inst_rpm() {
  # example: get_inst_rpm http://os.nchc.org.tw/... glibc i386
  local url_tmp="$1"
  local pkg="$2"
  local arch="$3"
  local rpm_opt="$4"
  pkg_tmp_dir="$(mktemp -d -q /tmp/$pkg.XXXXXX)"
  # note! the last / in $url must be kept!!!
  local pkg_prefix
  # try to append the version for regular expression if pkg without version number filter.
  if [ -z "$(echo $pkg | grep -E "\-[0-9]")" ]; then
    pkg="$pkg-[0-9]"
  fi
  wget -r -l1 --no-parent --passive-ftp -e robots=off -q -nd --retr-symlinks -P "$pkg_tmp_dir" -A "$pkg*.$arch.rpm" $url_tmp/
  pkg_file="$(ls $pkg_tmp_dir/$pkg*.$arch.rpm 2>/dev/null)"
  if [ -n "$pkg_file" ]; then
    rpm -Uvh $rpm_opt $opt $pkg_file
    RETVAL=$?
    if [ "$RETVAL" -gt 0 ]; then 
       echo "$msg_Failed_to_install $pkg_file..."
    fi
  else
    RETVAL=1
  fi
  [ -d "$pkg_tmp_dir" ] && rm -rf $pkg_tmp_dir
  return $RETVAL
}
# force to run apt-get install, this will force to install the necessary packages
check_apt_integrity() {
   apt-get -f --yes install
}

#
install_client_kernel() {
# here we have 2 method to install kernel, 1 is apt, 2 using rpm directly.
local kgot

#case "$installer" in
# "apt")
#   # 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...
#   # For MDK, there are some kernel labeled as test in contrib, we do not want that
#   # For RedHat/Fedora Ex. kernel-smp#2.6.9-1.681_FC3
#   # For MDK: Ex. kernel-smp-2.4.22.37mdk
#   # The difference is # or -
#   echo "$msg_available_kernel:"
#   apt-cache pkgnames kernel | grep -E "kernel${SMP_OPTION}[#-]2\.[0-9]+\.[0-9]+" | grep -v "test"
#   
#   latest_drbl_kernel_in_rep="$(apt-cache pkgnames kernel | grep -E "kernel${SMP_OPTION}[#-]2\.[0-9]+\.[0-9]+" | grep -v "test" | $DRBL_SCRIPT_PATH/bin/pkg-ver-latest )"
#   
#   # latest_drbl_kernel_in_rep looks like: (1) for RH: kernel#2.4.22-1.2199.nptl
#   # (2) for MDK, kernel-2.4.22.28mdk
#   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
#   ;;
# *)
     # we use lynx and other script to find the latest kernel
     LATEST_KTMP="$(mktemp /tmp/latest_ktmp.XXXXXX)"
     # set the OS and update dir
     eval RPMS_os_update_dir=\$${OS_type}_RPMS_os_update_dir
     for idir in $RPMS_os_update_dir; do
       kgot="$($DRBL_SCRIPT_PATH/bin/list_latest_rpm $url_os_coreroot/${idir}/  | grep -E "kernel${SMP_OPTION}[#-]2\.[0-9]+\.[0-9]+" | grep -v "test" | sed -e "s/\.i[356]86.rpm//g" -e "s/\.x86_64.rpm//g")" 
       # RPMS.os and RPMS.core might be symbolic link, so maybe the result will
       # duplicate
       if [ -n "$kgot" ]; then
          for ikgot in $kgot; do
	   if ! grep -q $ikgot $LATEST_KTMP; then
	     echo "$ikgot" >> $LATEST_KTMP
           fi
          done
       fi
     done
     # UGLY... find a better to strip the tail for MDK kernel
     # for MDK kernel-2.6.8.1.24mdk-1-1mdk, howver the kernel tag is 2.6.8.1-24mdk
     # we need to strip the -1-1mdk
     perl -p -i -e "s/-1-1mdk//g" $LATEST_KTMP

     echo "$msg_available_kernel:"
     cat $LATEST_KTMP
     
     latest_drbl_kernel_in_rep="$(cat $LATEST_KTMP | $DRBL_SCRIPT_PATH/bin/pkg-ver-latest)"
     [ -f "$LATEST_KTMP" ] && rm -f $LATEST_KTMP
#   ;;
#esac

echo "$msg_latest_kernel_in_ayo $latest_drbl_kernel_in_rep"
# get the version and release of kernel, strip the kernel[#-] or kernel-smp[#-]
drbl_kernel_ver="$(echo $latest_drbl_kernel_in_rep | sed -e s/kernel${SMP_OPTION}[#-]//g)"

if [ -n "$(echo $OS_Version | grep -i "MDK")" ]; then
  # For Mandrake only.
  # drbl_kernel_ver looks like: 2.4.22-28mdk
  # the rpm version tag is like 2.4.22.28mdk...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/")
fi

[ -z "$drbl_kernel_ver" ] && echo "Unable to find an appropriate kernel for client! Program terminated!!!" && exit 1

# UGLY!!! find a better way to know drbl_kernel_ver for SMP...
[ -n "$SMP_OPTION" ] && drbl_kernel_ver=${drbl_kernel_ver}smp
# drbl_kernel_ver looks like: 2.4.22-1.2199.nptl
# for SMP, it looks like: 2.4.22-1.2199.nptlsmp

# 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 /tftpboot/node_root/lib/modules/
(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
   echo "$msg_install_kernel_might_take_several_minutes"

   # if the latest kernel exists in the server, and its ARCH fits client, 
   # just copy it
   # if not, apt-get install it.
   # client arch maybe: i386/i586/best_optimization
   # we must convert the apt-cache result (only in redhat/mandrake) 
   # kernel#2.6.10-1.760_FC3 -> kernel-2.6.10-1.760_FC3 if querying by rpm -q
   latest_drbl_kernel="$(echo $latest_drbl_kernel_in_rep | tr "#" "-")"
   rpm -q --quiet $latest_drbl_kernel && server_kernel_ARCH="$(rpm -q --qf '%{ARCH}' $latest_drbl_kernel)"
   if [ "$client_archi_set" = "best_optimization" -o "$server_kernel_ARCH" = "$client_archi_set" ] && [ -d "/lib/modules/$drbl_kernel_ver" ]; then
    echo -n "Found latest kernel \"$latest_drbl_kernel\" in the server, and its architecture \"$server_kernel_ARCH\" meets the client's requirement ($client_archi_set). Copy it to clients' common root template..."
    # files like:
    #/boot/System.map-2.6.10-1.760_FC3
    #/boot/config-2.6.10-1.760_FC3
    #/boot/vmlinuz-2.6.10-1.760_FC3
    rsync -a /boot/*$drbl_kernel_ver /tftpboot/node_root/boot
    
    #/lib/modules/2.6.10-1.760_FC3
    rsync -a /lib/modules/$drbl_kernel_ver /tftpboot/node_root/lib/modules/

    # make a tag in the system for client's kernel arch.
    echo "$client_archi_set" > /tftpboot/nbi_img/client_kernel_arch.txt
    echo "done!"

   else

    # 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/
    
    #case "$installer" in
    #"apt")
     # method (1)
     # install the kernel by apt, but this will fail when server kernel with same version but different arch (say i686) installed...
     # Ex. kernel#2.6.10-1.766_FC3 (i686) is installed in server, but client
     # want i586 kernel#2.6.10-1.766_FC3, WILL FAIL!!!
     # The error is" Reinstallation of kernel#2.6.10-1.766_FC3 is not possible, it cannot be downloaded."
    # 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
    # ;;

    #*) 
     # method (2)
     # using RPM to install kernel. 
     # Try to find it's in RPMS.core or RPMS.updates
     # Find the architecture first.
     
     # filename got from apt-cache is different from that in the url, 
     # we have to replace like
     # kernel#2.6.10-1.766_FC3*.i586.rpm -> kernel-2.6.10-1.766_FC3*.i586.rpm
     latest_drbl_kernel_in_rep_RPM_FORMAT="$(echo $latest_drbl_kernel_in_rep | sed -e "s/#/-/g")"
     if [ "$OS_type" = "RH" ]; then
      case "$client_archi_set" in
       "best_optimization")
         # optimization, it could be i386/i586/i686/athlon
         # UGLY!! 
         # RPM package name is not same with that of "uname -r", we have to
         # do some modification.
         #~/>rpm -q kernel-smp
         #kernel-smp-2.6.10-1.766_FC3
         #~/>uname -r
         #2.6.10-1.766_FC3smp
         KVER="$(uname -r)"
         # strip the smp 
         KVER=${KVER//smp}
         # if server is not SMP, while client is SMP ? we will refer to 1 CPU kernel
         if rpm -q --quiet kernel${SMP_OPTION}-${KVER}; then
           kernel_to_be_ref="kernel${SMP_OPTION}-${KVER}"
         else
           kernel_to_be_ref="kernel-${KVER}"
         fi
         KARCH="$(rpm -q --qf '%{ARCH}' $kernel_to_be_ref)"
         ;;
       "i386")
         # for i386... this is not available for FC2/3, but we will force it
         # to be i586 before this...
         KARCH=i386
         ;;
       *)
         # for i586
         KARCH=i586
         ;;
      esac
     else
       # For Mandrake
       KARCH=i586
     fi
     for idir in $RPMS_os_update_dir; do
       echo "Try to install $KARCH $latest_drbl_kernel_in_rep_RPM_FORMAT from $url_os_coreroot/${idir}...Downloading..."
       get_inst_rpm $url_os_coreroot/${idir} $latest_drbl_kernel_in_rep_RPM_FORMAT $KARCH "--root /tftpboot/node_root/ --force --nodeps --noscripts"
       rc=$?
       # once it's done, skip the next search
       if [ "$rc" -eq 0 ]; then
         # make a tag in the system for client's kernel arch.
         echo "$KARCH" > /tftpboot/nbi_img/client_kernel_arch.txt
         break
       else
	 echo "$latest_drbl_kernel_in_rep_RPM_FORMAT is not found in $url_os_coreroot/${idir}."
       fi
     done
     # in case when kernel rpm installation fails.
     check_rpm_install $rc $latest_drbl_kernel_in_rep_RPM_FORMAT
     #;;
    #esac

    # 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 terminated!!!"
       exit 1 
    fi
   fi
else 
   echo "$client_archi_set" > /tftpboot/nbi_img/client_kernel_arch.txt
   echo "$msg_latest_kernel_is_already_installed"
fi
} # end of install_client_kernel

#
create_files_for_PXE_clients() {
[ ! -d /tftpboot/nbi_img/pxelinux.cfg ] && mkdir -p /tftpboot/nbi_img/pxelinux.cfg

if [ -f $pxelinux_file ]; then
   cp -f $pxelinux_file /tftpboot/nbi_img
   # for simple menu
   [ -f "/usr/lib/syslinux/menu.c32" ] && cp -f /usr/lib/syslinux/menu.c32 /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

# create the pxelinux default
$DRBL_SCRIPT_PATH/sbin/generate-pxe-menu -v -s "$PXE_SERIAL_OUTPUT" -c "$CONSOLE_OUTPUT"

# 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
   # 2005/4/4 since etherboot 5.4.0 is released, no more NBI.
   # 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
   # clean the unnecessary file
   # [ -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
} # end of create_files_for_PXE_clients

#
create_pxe_nbi_files() {
# make the nbi/pxe files
# 1st, clean the old nbi/pxe files
if [ "$(ls -alF /tftpboot/nbi_img/boot* 2> /dev/null)" != "" ]; then
   echo "$msg_delimiter_star_line"
   echo "$msg_remove_old_nbi"
   rm -f /tftpboot/nbi_img/boot*
fi

echo "$msg_delimiter_star_line"
case "$driver_answer" in
  n|N|[nN][oO])
   continue;;
  *)
   # install the driver for DRBL client, this is the case such as bcm4400 is not
   # included in RH9 2.4.20-8 or others in updates, so we add here.
   # the code here is ugly...

   # check if such driver exists
   # TODO... we need to find a way for yum... so now just skip this.
   if [ "$installer" = "apt" ]; then
     if [ -n "`apt-cache pkgnames drbl-driver |grep $drbl_kernel_ver`" ]; then
       echo "$msg_install_extra_driver"
       if [ -z "$SMP_OPTION" ]; then
        apt-get -y install drbl-driver-'[^(smp)]'.*-$drbl_kernel_ver
       else
        apt-get -y install drbl-driver-smp-.*-"$drbl_kernel_ver"
       fi
     else
        [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
        echo "$msg_no_extra_driver"
        [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
     fi
   fi
esac

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 mknic-nbi is installed or not.
if [ ! -x "$DRBL_SCRIPT_PATH/sbin/mknic-nbi" ]; 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!"
} # end of create_pxe_nbi_files

#
ask_if_setup_proxy() {
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
} # end of ask_if_setup_proxy

#
ask_and_parse_rpm_ayo_repo_options() {
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_drbl_unstable_option"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
echo -n "[y/N] "
read drbl_unstable_answer

# If unstable is chosen, we must set drbl_test_answer to yes.
case "$drbl_unstable_answer" in
  y|Y|[yY][eE][sS])
    drbl_test_answer="y"
    ;;
  *)
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo "$msg_drbl_test_option"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo -n "[y/N] "
    read drbl_test_answer
    ;;
esac

# [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
# echo "$msg_drbl_extra_option"
# [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
# echo -n "[y/N] "
# read drbl_extra_answer

# parse it
case "$drbl_test_answer" in
    [yY]|[yY][eE][Ss])
      DRBL_TEST="drbl-test"
      ;;
    *)
      DRBL_TEST=""
esac
case "$drbl_unstable_answer" in
    [yY]|[yY][eE][Ss])
      DRBL_UNSTABLE="drbl-unstable"
      ;;
    *)
      DRBL_UNSTABLE=""
esac
# case "$drbl_extra_answer" in
#     [yY]|[yY][eE][Ss])
#       DRBL_EXTRA="drbl-extra"
#       ;;
#     *)
#       DRBL_EXTRA=""
# esac

} # end of ask_and_parse_rpm_ayo_repo_options

ask_and_parse_client_extra_setting() {
# netinstall options
echo "$msg_delimiter_star_line"
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_drbl_netinstall_option"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
echo -n "[y/N] "
read drbl_netinstall_answer

# console output
[ "$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
case "$OS_type" in
  RH)
    echo "$msg_smp_clients_RH"
    ;;
  MDK)
    echo "$msg_smp_clients_MDK"
    ;;
esac
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
echo -n "[y/N] "
read SMP_answer

[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_drbl_driver"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
echo -n "[Y/n] "
read driver_answer

# parse it
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

# netinstall
case "$drbl_netinstall_answer" in
    [yY]|[yY][eE][Ss])
      DRBL_NETINSTALL="yes"
      ;;
    *)
      DRBL_NETINSTALL="no"
esac

} # end of ask_and_parse_client_extra_setting

#
backup_apt_sources_list() {
  if [ -f /etc/apt/sources.list ]; then
    echo "$msg_backup_apt_sources"
    mv -v /etc/apt/sources.list /etc/apt/sources.list.orig
  fi
}

#
clean_tftpboot_and_misc() {
  echo "$msg_delimiter_star_line"
  echo "$msg_cleaning_tftpboot_and_misc"
  echo "$msg_delimiter_star_line"
  [ -d "/tftpboot" ] && rm -rf /tftpboot/* 
  [ -d "$drbl_syscfg" ] && rm -rf $drbl_syscfg
  [ -f "$ocsroot/clonezilla.lock" ] && rm -f $ocsroot/clonezilla.lock
  [ -f /etc/yp.conf ] && mv -v /etc/yp.conf /etc/yp.conf.drblsave
  [ -f /etc/ypserv.conf ] && mv -v /etc/ypserv.conf /etc/ypserv.conf.drblsave
  [ -f /var/yp/securenets ] && mv -v /var/yp/securenets /var/yp/securenets.drblsave
  [ -f $drbl_pkgdir/dev.tgz ] && rm -f $drbl_pkgdir/dev.tgz
} # end of clean_tftpboot_and_misc()

append_RH_apt_sources_list_example() {
cat <<-APT_END >> /etc/apt/sources.list
# Examples:
# DRBL for RH9 in drbl.sourceforge.net, only DRBL packages, no RH9 packages
#rpm http://drbl.sourceforge.net/redhat/apt redhat/9/i386 drbl drbl-test
#rpm-src http://drbl.sourceforge.net/redhat/apt redhat/9/i386 drbl drbl-test

# DRBL for FC1 in drbl.sourceforge.net, only DRBL packages, no FC1 packages
#rpm http://drbl.sourceforge.net/fedora/apt/ fedora/linux/1/i386 drbl drbl-test
#rpm-src http://drbl.sourceforge.net//fedora/apt/ fedora/linux/1/i386 drbl drbl-test

# DRBL for RH9 in opensource.nchc.org.tw, including DRBL packages and RH9 pacakges
#rpm http://opensource.nchc.org.tw//redhat/apt/ redhat/9/i386 os updates drbl
#rpm-src http://opensource.nchc.org.tw//redhat/apt/ redhat/9/i386 os updates drbl

# DRBL for FC1 in linux.nchc.org.tw, including DRBL packages and FC1 pacakges
#rpm http://opensource.nchc.org.tw//fedora/apt/ fedora/linux/1/i386 core updates drbl  
#rpm-src http://opensource.nchc.org.tw//fedora/apt/ fedora/linux/1/i386 core updates drbl  

### Dag Apt Repository for Red Hat Fedora Core 1 (rhfc1)
#rpm http://apt.sw.be redhat/fc1/en/i386 dag

### Dag Apt Repository for Red Hat 9 (rh90)
#rpm http://apt.sw.be redhat/9/en/i386 dag

### Dag Apt Repository for Red Hat 8.0 (rh80)
#rpm http://apt.sw.be redhat/8.0/en/i386 dag
APT_END

} # end of append_RH_apt_sources_list_example

parse_os_to_set_repository() {
# If the OS_Version is not supported, exit
if [ -z "$OS_Version" ]; then
  [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
  echo "$msg_not_determine_OS"
  echo "$msg_is_not_supported"
  echo "$msg_press_ctrl_c_stop!"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  read
  exit 1 
fi

case "$OS_Version" in
   "RH8.0"|"RH9")
     # set the official release number... 8.0, 9...
     RH_VER=${OS_Version:2}
     #DIST="redhat"
     echo "$msg_OS_version: $OS_Version"
     # core_dir is for the core program, for RH8 and 9, RPMS.os, set it as "os"
     core_dir="os"
     # RH_RPMS_os_update_dir indicates in apt repository, 
     # where OS and updates pakcage (rpms) exist,
     # We will use it to search glibc & openssl only, not
     # for apt repository (not for /etc/apt/sources.list)
     # freshrpms:
     #http://ayo.freshrpms.net/redhat/9/i386/updates/RPMS/
     #http://ayo.freshrpms.net/redhat/9/i386/os/RPMS
     # opensource (normal)
     #http://opensource.nchc.org.tw/redhat/linux/9/en/os/i386/RedHat/RPMS/
     #http://opensource.nchc.org.tw/redhat/linux/updates/9/en/os/i386
     #http://opensource.nchc.org.tw/redhat/linux/updates/9/en/os/i586
     #http://opensource.nchc.org.tw/redhat/linux/updates/9/en/os/i686
     RH_RPMS_os_update_dir="updates/$RH_VER/en/os/i386 updates/$RH_VER/en/os/i586 updates/$RH_VER/en/os/i686 updates/$RH_VER/en/os/noarch $RH_VER/en/os/i386/RedHat/RPMS $RH_VER/i386/updates/RPMS $RH_VER/i386/os/RPMS"
     ;;
   FC*)
     FC_VER=${OS_Version:2}
     #DIST="fedora"
     echo "$msg_OS_version: $OS_Version"
     # core_dir is for the core program, for FC1, RPMS.core, set it as "core"
     core_dir="core"
     # RH_RPMS_os_update_dir indicates in apt repository, 
     # where OS and updates pakcage (rpms) exist,
     # We will use it to search glibc & openssl only, not
     # for apt repository (not for /etc/apt/sources.list)
     # freshrpms:
     #http://ayo.freshrpms.net/fedora/linux/3/i386/updates/RPMS/
     #http://ayo.freshrpms.net/fedora/linux/3/i386/core/RPMS/
     RH_RPMS_os_update_dir="updates/$FC_VER/$ARCH/ $FC_VER/$ARCH/os/Fedora/RPMS/ $FC_VER/$ARCH/updates/RPMS/ $FC_VER/$ARCH/core/RPMS/"
     ;;
   CO4)
     CO_VER=${OS_Version:2}
     echo "$msg_OS_version: $OS_Version"
     # RH_RPMS_os_update_dir indicates in apt repository, 
     # where OS and updates pakcage (rpms) exist,
     # We will use it to search glibc & openssl only, not
     # for apt repository (not for /etc/apt/sources.list)
     RH_RPMS_os_update_dir="$CO_VER/updates/$ARCH/RPMS $CO_VER/os/$ARCH/CentOS/RPMS/"
     ;;
   MDK9.2|MDK10.0)
     [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
     echo "$msg_OS_version: $OS_Version"
     [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
     #http://opensource.nchc.org.tw/mandrake/apt/ mandrake/linux/9.2/i586 core updates drbl drbl-test drbl-unstable

     # sources.list
     # rpm $url_os/official/$MDK_VER/i586/Mandrake/ base/hdlist RPMS
     # Mandrake updates
     # rpm $url_os/official/updates/$MDK_VER/ base/hdlist RPMS
     MDK_VER=${OS_Version:3}
     media="Mandrake"
     media_info="base"
     main_rpmdir="RPMS"
     contrib_rpmdir="RPMS2"
     jpackage_rpmdir="RPMS3"
     main_updates="base"
     update_rpmdir="RPMS"
     # MDK_RPMS_os_update_dir indicates in rpm repository, 
     # where OS and update rpms exists
     # We will use MDK_RPMS_os_update_dir for search glibc & openssl only, not
     # for apt repository (not for /etc/apt/sources.list)
     MDK_RPMS_os_update_dir="updates/$MDK_VER/$update_rpmdir $MDK_VER/i586/$media/$main_rpmdir"
     ;;
   MDK10.1)
     [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
     echo "$msg_OS_version: $OS_Version"
     [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
     # sources.list
     # rpm http://opensource.nchc.org.tw//mandrake/official/10.1/i586/media media_info/hdlist main
     # Mandrake contrib
     # rpm http://opensource.nchc.org.tw//mandrake/official/10.1/i586/media media_info/hdlist2 contrib
     # Mandrake jpackage
     # rpm http://opensource.nchc.org.tw//mandrake/official/10.1/i586/media media_info/hdlist3 jpackage
     # Mandrake updates
     # rpm http://opensource.nchc.org.tw//mandrake/official/updates/10.1/ main_updates/media_info/hdlist main_updates
     MDK_VER=${OS_Version:3}
     media="media"
     media_info="media_info"
     main_rpmdir="main"
     contrib_rpmdir="contrib"
     jpackage_rpmdir="jpackage"
     main_updates="main_updates/media_info"
     update_rpmdir="main_updates"
     # MDK_RPMS_os_update_dir indicates in rpm repository, 
     # where OS and update rpms exists
     # We will use MDK_RPMS_os_update_dir for search glibc & openssl only, not
     # for apt repository (not for /etc/apt/sources.list)
     MDK_RPMS_os_update_dir="updates/$MDK_VER/$update_rpmdir $MDK_VER/i586/$media/$main_rpmdir"
     ;;
   *)
     [ "$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

#
ask_if_setup_proxy

} # parse_os_to_set_repository

#
parse_client_archi_setting() {
# Apply the client_archi_ans for x86_64 and SMP
# x86_64 added, we will use best_optimization for x86_64.
[ "$ARCH" = "x86_64" ] && client_archi_ans=2

# if SMP for client -> best_optimization.
# Not SMP -> ask user.
case "$SMP_answer" in
 [yY]|[yY][eE][Ss])
   [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
   echo "$msg_delimiter_star_line"
   [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
   echo "$msg_smp_optimization_kernel"
   client_archi_ans="2"
   echo "$msg_press_enter_to_continue"
   read 
   ;;
esac

# if $client_archi_ans is not set (i.e. NOT x86_64, NOT SMP), ask user.
if [ -z "$client_archi_ans" ]; then
   [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
   echo "$msg_delimiter_star_line"
   echo "$msg_apt_optimization_question"
   echo "$msg_optimization_level_0"
   echo "$msg_optimization_level_1"
   echo "$msg_optimization_level_2"
   [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
   echo "$msg_N_note"
   [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
   echo "$msg_note!!! $msg_different_level_machine_prompt"
   echo "$msg_diff_arch_explain"
   [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
   echo "$msg_not_sure_better_1"
   echo -n "[1] "
   read client_archi_ans
   echo "$msg_delimiter_star_line"
fi

# check if the answer fits to the distribution
# for RH8/9, FC1 -> i386, i586, i686 are available
# for FC2/3 -> i586, i686 are available, i386 is not available
if [ "$client_archi_ans" = "0" ]; then
  case "$OS_Version" in
  FC[2-3])
        [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
        echo "$msg_change_opt_from_i386_to_i586"
        [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
        client_archi_ans="1"
        ;;
  esac
fi
# 
case "$client_archi_ans" in
 2)
   # use default, let apt-rpm decide, so we do not have to change anything in
   # /etc/apt/apt.conf
   [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
   echo "$msg_same_optimization"
   [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
   client_archi_set="best_optimization"
   ;;
 0)
   # for i386... this is not available for FC2...
   [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
   echo "$msg_no_optimization"
   [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
   [ -f "/etc/apt/apt.conf" ] && perl -p -i -e "s/^.*Install-Options.*\"\".*;/    Install-Options \"\"; Architecture \"i386\";/" /etc/apt/apt.conf
   client_archi_set="i386"
   ;;
 *)
   # for apt to use upto i586, the change will be in /etc/apt/apt.conf
   [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
   echo "$msg_i586_optimization"
   [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
   [ -f "/etc/apt/apt.conf" ] && perl -p -i -e "s/^.*Install-Options.*\"\".*;/    Install-Options \"\"; Architecture \"i586\";/" /etc/apt/apt.conf
   client_archi_set="i586"
   ;;
esac

} # end of parse_client_archi_setting

#
install_client_archi_glibc_openssl() {
echo "$msg_delimiter_star_line"
case "$client_archi_set" in
    "best_optimization")
      [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
      echo "$msg_optimization_is_on"
      [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
      ;;
    *)
    # for i586 and i386, we force to use i386 version: glibc and openssl
      [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
      echo "$msg_optimization_is_off"
      [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
      if [ $glibc_ARCH != "i386" ]; then 
       installed_glibc=`rpm -qa |grep ^glibc-[0-9]`
       [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
       echo "$msg_install_i386_of $installed_glibc..."
       echo "$msg_searching_glibc_in_ayo..."
       [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
       for irpm in $RH_RPMS_os_update_dir; do
         echo "Try to install glibc from $url_os_coreroot/$irpm/${installed_glibc}.i386.rpm..." 
         rpm -Uvh --force --quiet $url_os_coreroot/$irpm/${installed_glibc}.i386.rpm 2>/dev/null
         RETVAL=$?
         [ $RETVAL -eq 0 ] && break
       done
       # sleep to make rpm db ok.
       sleep 5
       # to mv the i686 lib which should not exists in i386 glibc packags
       # if they are not cleaned.
       lib_bk="/lib/i686 /lib/tls /usr/lib/i686"
       for idir in $lib_bk; do
         if [ -d "$idir" ]; then
           [ -d "$idir.bak" ] && rm -rf $idir.bak
           mv -f $idir $idir.bak
         fi
       done
      fi
      if [ $openssl_ARCH != "i386" ]; then 
       installed_openssl=`rpm -qa |grep ^openssl-[0-9]`
       [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
       echo "$msg_install_i386_of $installed_openssl..."
       echo "$msg_searching_openssl_in_ayo..."
       [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
       for irpm in $RH_RPMS_os_update_dir; do
         # search the openssl rpms in $RH_RPMS_os_update_dir
         echo "Try to install openssl from $url_os_coreroot/$irpm/${installed_openssl}.i386.rpm..." 
         rpm -Uvh --force --quiet $url_os_coreroot/$irpm/${installed_openssl}.i386.rpm 2>/dev/null
         RETVAL=$?
         [ $RETVAL -eq 0 ] && break
       done
      fi
esac
} # end of install_client_archi_glibc_openssl

# TODO, maybe merge parse_rh_yum_repo_answer() and parse_rh_apt_repo_answer()
parse_RH_os_yum_repo_answer() {
local os_name="$1"
local answer="$2"
case "$answer" in
    1)
      # download.fedora.redhat.com
      url_os="http://download.fedora.redhat.com"
      os_ayo_path="/pub/fedora/linux/core"
      url_os_coreroot="$url_os/$os_ayo_path"
      ;;
    2) # TODO
      # mirrors.kernel.org
      url_os="http://mirrors.kernel.org"
      os_ayo_path="/fedora/core/"
      url_os_coreroot="$url_os/$os_ayo_path"

      # TODO
      # mirrorlist from fedora.redhat.com, but how to install glibc/openssl ?
      # or enter by user himeself
      ;;
    4)
      # skip the yum config, but we will use the following url_os... for glibc/kernel inst
      use_existing_yum_config="yes"

      url_os="http://opensource.nchc.org.tw"
      os_ayo_path="/fedora/linux/core/"
      url_os_coreroot="$url_os/$os_ayo_path"
      ;;
    5)
      #enter by user
      url_os_default="http://mirrors.kernel.org"
      os_ayo_path_default="/fedora/core/"
      echo "Please enter the hostname or IP address of yum reposity with http or ftp prefix..."
      echo -n "[$url_os_default] "
      read url_os
      [ -z "$url_os" ] && url_os="$url_os_default"

      echo "Enter the path where directory \"$FC_VER\" and \"updates\" exist..."
      echo -n "[$os_ayo_path_default] "
      read os_ayo_path
      [ -z "$os_ayo_path" ] && os_ayo_path="$os_ayo_path_default"
      url_os_coreroot="$url_os/$os_ayo_path"
      ;;
    *)
      # default one, use opensource.nchc.org.tw
      url_os="http://opensource.nchc.org.tw"
      case "$os_name" in
	FC*)
          os_ayo_path="/fedora/linux/core/"
	  ;;
	CO*)
          os_ayo_path="/centos/"
	  ;;
      esac
      url_os_coreroot="$url_os/$os_ayo_path"
esac
echo "------------------------------------------------------"
echo "$msg_select_url_path: $url_os, $os_ayo_path"
echo "------------------------------------------------------"

} # end of parse_RH_os_yum_repo_answer

#
parse_RH_drbl_yum_repo_answer() {
local answer="$1"
# TODO x86_64: change i386 -> x86_64 ? or it works ?
case "$answer" in
    1)
      # diskless.nchc.org.tw
      url_drbl="http://diskless.nchc.org.tw"
      drbl_ayo_path="fedora/apt/fedora/linux/$FC_VER/i386"
      url_drbl_rpmroot="$url_drbl/$drbl_ayo_path/"
      ;;
    2)
      # drbl.sf.net
      url_drbl="http://drbl.sourceforge.net"
      drbl_ayo_path="apt/fedora/apt/fedora/linux/$FC_VER/i386"
      url_drbl_rpmroot="$url_drbl/$apt_paht/"
      ;;
    5)
      #enter by user
      url_drbl_default="http://drbl.sourceforge.net"
      drbl_ayo_path_default="/apt/fedora/apt/fedora/linux/$FC_VER/i386/"
      echo "Please enter the hostname or IP address of yum reposity with http or ftp prefix where DRBL packages exists..."
      echo -n "[$url_drbl_default] "
      read url_drbl
      [ -z "$url_drbl" ] && url_drbl="$url_drbl_default"

      echo "Enter the path where directory \"RPMS.drbl\" exists..." 
      echo -n "[$drbl_ayo_path_default] "
      read drbl_ayo_path
      [ -z "$drbl_ayo_path" ] && drbl_ayo_path="$drbl_ayo_path_default"
      url_drbl_coreroot="$url_drbl/$drbl_ayo_path/"
      ;;
    *)
      # default one, use opensource.nchc.org.tw
      url_drbl="http://opensource.nchc.org.tw"
      drbl_ayo_path="fedora/apt/fedora/linux/$FC_VER/i386"
      url_drbl_rpmroot="$url_drbl/$drbl_ayo_path/"
esac
echo "------------------------------------------------------"
echo "$msg_select_url_path: $url_drbl, $drbl_ayo_path"
echo "------------------------------------------------------"

} # parse_RH_drbl_yum_repo_answer

#
parse_RH_os_apt_repo_answer() {
local os_ver="$1"
local answer="$2"
local ver_no="${os_ver:2}"
case "$answer" in
    1)
      # freshrpms
      url_os="http://ayo.freshrpms.net"
      case "$os_ver" in
        RH*)
          url_os_coreroot="$url_os/redhat/"
          os_ayo_path="redhat/$RH_VER/i386"
          ;;
        FC*)
          url_os_coreroot="$url_os/fedora/linux/"
          os_ayo_path="fedora/linux/$FC_VER/i386"
  	  ;;
      esac
      FRESHRPMS="freshrpms"
      ;;
    3) 
      # local repository
      url_os="/"
      url_os_coreroot_default="/opt/mirror/fedora/linux/core"
      os_ayo_path_default="/opt/mirror/fedora/apt/fedora/linux/$ver_no/i386"
      echo "Enter the path where directory \"$ver_no\" and \"updates\" exist."
      echo -n "[$url_os_coreroot_default] "
      read url_os_coreroot
      [ -z "$url_os_coreroot" ] && url_os_coreroot="$url_os_coreroot_default"
      while [ ! -e "$url_os_coreroot/$ver_no" ]; do
	echo "No such directory \"$url_os_coreroot/$ver_no\" or \"$url_os_coreroot/updates/$ver_no\"!" 
	echo "Please enter it again!"
        read url_os_coreroot
      done

      echo "Enter the path where directory RPMS.$core_dir, RPMS.updates... exist."
      echo -n "[$os_ayo_path_default] "
      read os_ayo_path
      [ -z "$os_ayo_path" ] && os_ayo_path="$os_ayo_path_default"
      while [ ! -e "$os_ayo_path/RPMS.$core_dir" ] || [ ! -e "$os_ayo_path/RPMS.drbl" ]; do
	echo "No such directory $os_ayo_path/RPMS.$core_dir or $os_ayo_path/RPMS.drbl!" 
	echo "Please enter it again!"
        read os_ayo_path
      done
      ;;
    5) 
      # enter by user
      url_os_default="http://ayo.freshrpms.net"
      os_coreroot_default="/fedora/linux/"
      os_ayo_path_default="/fedora/linux/$ver_no/i386"
      echo "Enter the hostname or IP address of $os_ver packages reposity with http or ftp prefix."
      echo -n "[$url_os_default] "
      read url_os
      [ -z "$url_os" ] && url_os="$url_os_default"

      echo "Enter the path where directory \"$ver_no\" and \"updates\" exist."
      echo -n "[$os_coreroot_default] "
      read os_coreroot
      [ -z "$os_coreroot" ] && os_coreroot="$os_coreroot_default"
      url_os_coreroot="$url_os/$os_coreroot"

      echo "Enter the path where directory RPMS.$core_dir, RPMS.updates... exist."
      echo -n "[$os_ayo_path_default] "
      read os_ayo_path
      [ -z "$os_ayo_path" ] && os_ayo_path="$os_ayo_path_default"
      ;;
    *)
      # default one, use opensource.nchc.org.tw
      url_os="http://opensource.nchc.org.tw"
      case "$os_ver" in
        RH*)
          url_os_coreroot="$url_os/redhat/linux/"
          os_ayo_path="redhat/apt/redhat/linux/$RH_VER/i386"
          ;;
        FC*)
          url_os_coreroot="$url_os/fedora/linux/core/"
          os_ayo_path="fedora/apt/fedora/linux/$FC_VER/i386"
  	  ;;
      esac
esac
echo "------------------------------------------------------"
echo "$msg_select_url_path: $url_os, $url_os_coreroot, $os_ayo_path"
echo "------------------------------------------------------"

} # parse_RH_os_apt_repo_answer

parse_RH_drbl_apt_repo_answer() {
# url_drbl_rpmroot is where the RPMS.drbl, RPMS.drbl-test, RPMS.drbl-unstable... exist
# url_os_rpmroot is where the RPMS.os, RPMS.core, RPMS.update... exist
# try to set url_drbl_rpmroot and url_os, we need 
# url_drbl_rpmroot to get wget and apt
# url_os_rpmroot to get glibc/openssl/kernel
# os_ayo_path is under $url_os where RPMS.os/RPMS.core exists
# drbl_ayo_path is under $url_drbl where RPMS.drbl exists
local answer="$1"
case "$answer" in
    1)
      # diskless.nchc.org.tw
      url_drbl="http://diskless.nchc.org.tw"
      case "$OS_Version" in
        RH*)
          drbl_ayo_path="redhat/apt/redhat/linux/$RH_VER/i386"
          ;;
        FC*)
          drbl_ayo_path="fedora/apt/fedora/linux/$FC_VER/i386"
  	  ;;
      esac
      url_drbl_rpmroot="$url_drbl/$drbl_ayo_path/"
      ;;
    2)
      # drbl.sf.net
      url_drbl="http://drbl.sourceforge.net"
      case "$OS_Version" in
        RH*)
          drbl_ayo_path="apt/redhat/apt/redhat/linux/$RH_VER/i386"
          ;;
        FC*)
          drbl_ayo_path="apt/fedora/apt/fedora/linux/$FC_VER/i386"
  	  ;;
      esac
      url_drbl_rpmroot="$url_drbl/$drbl_ayo_path/"
      ;;
    3) 
      # local repository
      url_drbl_default="/"
      drbl_ayo_path_default="/apt/fedora/apt/fedora/linux/${OS_Version:2}/i386"

      echo "Enter the path where directory RPMS.$core_dir, RPMS.updates... exist."
      echo -n "[$drbl_ayo_path_default] "
      read drbl_ayo_path
      [ -z "$drbl_ayo_path" ] && os_ayo_path="$drbl_ayo_path_default"
      while [ ! -e "$drbl_ayo_path/RPMS.$core_dir" ] || [ ! -e "$drbl_ayo_path/RPMS.drbl" ]; do
	echo "No such directory $drbl_ayo_path/RPMS.$core_dir or $drbl_ayo_path/RPMS.drbl!" 
	echo "Please enter it again!"
        read drbl_ayo_path
      done
      url_drbl_rpmroot="$url_drbl/$drbl_ayo_path/"
      ;;
    5) 
      # enter by user
      url_drbl_default="http://drbl.sourceforge.net"
      drbl_ayo_path_default="/apt/fedora/apt/fedora/linux/${OS_Version:2}/i386"

      echo "Enter the hostname or IP address of DRBL packages reposity with http or ftp prefix."
      echo -n "[$url_drbl_default] "
      read url_drbl
      [ -z "$url_drbl" ] && url_drbl="$url_drbl_default"
      echo "Enter the path where directory RPMS.$core_dir, RPMS.updates... exist."
      echo -n "[$drbl_ayo_path_default] "
      read drbl_ayo_path
      [ -z "$drbl_ayo_path" ] && drbl_ayo_path="$drbl_ayo_path_default"
      url_drbl_rpmroot="$url_drbl/$drbl_ayo_path/"
      ;;
    *)
      # default one, use opensource.nchc.org.tw
      url_drbl="http://opensource.nchc.org.tw"
      case "$OS_Version" in
        RH*)
          drbl_ayo_path="redhat/apt/redhat/linux/$RH_VER/i386"
          ;;
        FC*)
          drbl_ayo_path="fedora/apt/fedora/linux/$FC_VER/i386"
  	  ;;
      esac
      url_drbl_rpmroot="$url_drbl/$drbl_ayo_path/"
esac
echo "------------------------------------------------------"
echo "$msg_select_url_path: $url_drbl, $drbl_ayo_path"
echo "------------------------------------------------------"
} # parse_RH_drbl_apt_repo_answer

#
parse_MDK_os_ayo_repo_answer() {
# url_drbl_rpmroot is where the RPMS.drbl, RPMS.drbl-test, RPMS.drbl-unstable... exist
# url_os_rpmroot is where the rpm files (lernel-2.6.8-24mdk-1-1mdk.i586.rpm)... exist
# try to set url_drbl_rpmroot and url_os, we need 
# url_drbl_rpmroot to get wget and apt
# url_os_rpmroot to get glibc/openssl/kernel
# url_os_rpmroot is to the path where "official" exists.
local answer="$1"
case "$answer" in
    1)
      # mdk.linux.org.tw
      url_os="ftp://mdk.linux.org.tw"
      os_ayo_path="/pub/mandrake-linux/official/"
      url_os_coreroot="$url_os/$os_ayo_path"
      ;;
    2)
      # distro.ibiblio.org
      url_os="http://distro.ibiblio.org"
      os_ayo_path="/pub/Linux/distributions/mandrake/Mandrakelinux/official/"
      url_os_coreroot="$url_os/$os_ayo_path"
      ;;
    4)
      # TODO... make $use_existing_yum_config work in urpmi.addmedia
      # skip the setting of yum, but we will add this for glibc/kernel inst.
      use_existing_urpmi_config="yes"
      url_os="http://opensource.nchc.org.tw"
      os_ayo_path="/mandrake/official/"
      url_os_coreroot="$url_os/$os_ayo_path"
      ;;
    5)
      #enter by user
      url_os_default="http://distro.ibiblio.org"
      os_ayo_path_default="/pub/Linux/distributions/mandrake/Mandrakelinux/official/"
      echo "Please enter the hostname or IP address of OS packages reposity with http or ftp prefix..."
      echo -n "[$url_os_default] "
      read url_os
      [ -z "$url_os" ] && url_os="$url_os_default"

      echo "Enter the path where directories \"${OS_Version:3}\" and \"updates\"exist..." 
      echo -n "[$os_ayo_path_default] "
      read os_ayo_path
      [ -z "$os_ayo_path" ] && os_ayo_path="$os_ayo_path_default"

      url_os_coreroot=$url_os/$os_ayo_path
      ;;
    *)
      # default one, use opensource.nchc.org.tw
      url_os="http://opensource.nchc.org.tw"
      os_ayo_path="/mandrake/official/"
      url_os_coreroot="$url_os/$os_ayo_path"
esac
echo "------------------------------------------------------"
echo "$msg_select_url_path: $url_os, $url_os_coreroot"
echo "------------------------------------------------------"

} # end of parse_MDK_os_ayo_repo_answer

#
parse_MDK_drbl_ayo_repo_answer() {
# url_drbl_rpmroot is where the RPMS.drbl, RPMS.drbl-test, RPMS.drbl-unstable... exist
# url_os_rpmroot is where the rpm files (lernel-2.6.8-24mdk-1-1mdk.i586.rpm)... exist
# try to set url_drbl_rpmroot and url_os, we need 
# url_drbl_rpmroot to get wget and apt
# url_os_rpmroot to get glibc/openssl/kernel
# url_os_rpmroot is to the path where "official" exists.
local answer="$1"
case "$answer" in
    1)
      # diskless.nchc.org.tw
      url_drbl="http://diskless.nchc.org.tw"
      drbl_ayo_path="mandrake/apt/mandrake/linux/$MDK_VER/i586"
      url_drbl_rpmroot="$url_drbl/$drbl_ayo_path/"
      ;;
    2)
      # drbl.sf.net
      url_drbl="http://drbl.sourceforge.net"
      drbl_ayo_path="apt/mandrake/apt/mandrake/linux/$MDK_VER/i586"
      url_drbl_rpmroot="$url_drbl/$drbl_ayo_path/"
      ;;
    5)
      #enter by user
      url_drbl_default="ftp://opensource.nchc.org.tw"
      drbl_ayo_path_default="/distributions/mandrake/apt/mandrake/linux/$MDK_VER/i586"
      echo "Please enter the hostname or IP address of apt reposity with http or ftp prefix..."
      echo -n "[$url_drbl_default] "
      read url_drbl
      [ -z "$url_drbl" ] && url_drbl="$url_drbl_default"

      echo "Enter the path where directory RPMS.drbl exist..." 
      echo -n "[$drbl_ayo_path_default] "
      read drbl_ayo_path
      [ -z "$drbl_ayo_path" ] && drbl_ayo_path="$drbl_ayo_path_default"
      url_drbl_rpmroot="$url_drbl"/"$drbl_ayo_path"
      ;;
    *)
      # default one, use opensource.nchc.org.tw
      url_drbl="http://opensource.nchc.org.tw/"
      drbl_ayo_path="mandrake/apt/mandrake/linux/$MDK_VER/i586"
      url_drbl_rpmroot="$url_drbl/$drbl_ayo_path/"
esac
echo "------------------------------------------------------"
echo "$msg_select_url_path: $url_drbl, $drbl_ayo_path"
echo "------------------------------------------------------"

} # end of parse_MDK_drbl_ayo_repo_answer
#

generate_fedora_yum_conf() {
# backup old file
echo "$msg_delimiter_star_line"
echo "Backuping the repo files..."
if [ "$use_existing_yum_config" = "yes" ]; then
  # we won't touch the existing fedora.repo fedora-updates.repo
  for ifile in drbl.repo drbl-testing.repo drbl-unstable.repo drbl-extra.repo ; do
   [ -f "/etc/yum.repos.d/$ifile" ] && mv -f /etc/yum.repos.d/$ifile /etc/yum.repos.d/$ifile.drblsave
  done
else
  for ifile in fedora.repo fedora-updates.repo drbl.repo drbl-testing.repo drbl-unstable.repo ; do
   [ -f "/etc/yum.repos.d/$ifile" ] && mv -f /etc/yum.repos.d/$ifile /etc/yum.repos.d/$ifile.drblsave
  done
fi
echo "done!"

# Turn off the testing and devel repository
echo -n "Turn off the testing and devel repository..."
for ifile in fedora-updates-testing.repo fedora-devel.repo; do
 [ -f "$/etc/yum.repos.d/$ifile" ] &&  perl -p -i -e "s/^enabled=.*/enabled=0/g" /etc/yum.repos.d/$ifile
done
echo "done!"

if [ "$use_existing_yum_config" != "yes" ]; then
  # overwrite the existing fedora.repo and fedora-updates.repo
  #
  echo "Creating the fedora core packages repository list..."
  cat <<-YUM_END > /etc/yum.repos.d/fedora.repo
[base]
name=Fedora Core \$releasever - \$basearch - Base
#baseurl=http://download.fedora.redhat.com/pub/fedora/linux/core/\$releasever/\$basearch/os/
#mirrorlist=http://fedora.redhat.com/download/mirrors/fedora-core-\$releasever
baseurl=$url_os_coreroot/\$releasever/\$basearch/os
enabled=1
gpgcheck=1
YUM_END

  #
  echo "Creating the fedora updates packages repository list..."
  cat <<-YUM_END > /etc/yum.repos.d/fedora-updates.repo
[updates-released]
name=Fedora Core \$releasever - \$basearch - Released Updates
#baseurl=http://download.fedora.redhat.com/pub/fedora/linux/core/updates/\$releasever/\$basearch/
#mirrorlist=http://fedora.redhat.com/download/mirrors/updates-released-fc\$releasever
baseurl=$url_os_coreroot/updates/\$releasever/\$basearch/
enabled=1
gpgcheck=1
YUM_END

fi
} # end of generate_fedora_yum_conf

#
generate_drbl_yum_conf() {
# DRBL stable
echo "$msg_delimiter_star_line"
echo "Creating the DRBL stable packages repository list..."
cat <<-YUM_END > /etc/yum.repos.d/drbl.repo
[drbl]
name=DRBL stable packages
baseurl=$url_drbl/$drbl_ayo_path/RPMS.drbl
enabled=1
gpgcheck=0
YUM_END

# DRBL testing
if [ -n "$DRBL_TEST" ]; then
  echo "Creating the DRBL testing packages repository list..."
  cat <<-YUM_END > /etc/yum.repos.d/drbl-testing.repo
[drbl-testing]
name=DRBL testing packages
baseurl=$url_drbl/$drbl_ayo_path/RPMS.drbl-test
enabled=1
gpgcheck=0
YUM_END
fi

# DRBL testing
if [ -n "$DRBL_UNSTABLE" ]; then
  echo "Creating the DRBL unstable packages repository list..."
  cat <<-YUM_END > /etc/yum.repos.d/drbl-unstable.repo
[drbl-unstable]
name=DRBL unstable packages
baseurl=$url_drbl/$drbl_ayo_path/RPMS.drbl-unstable
enabled=1
gpgcheck=0
YUM_END
fi

# DRBL extra
# if [ -n "$DRBL_EXTRA" ]; then
#   echo "Creating the DRBL extra packages repository list..."
#   cat <<-YUM_END > /etc/yum.repos.d/drbl-extra.repo
# [drbl-extra]
# name=DRBL extra packages
# baseurl=$url_drbl/$drbl_ayo_path/RPMS.drbl-extra
# enabled=1
# gpgcheck=0
# YUM_END
# fi

echo "done!"
} # end of generate_drbl_yum_conf

#
do_upgrade_system_for_RH() {
echo "$msg_delimiter_star_line"
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_glibc_openssl_upgrade_question"
echo "$msg_glibc_openssl_keep"
echo "$msg_keep_glibc_upgrade_openssl"
echo "$msg_upgrade_glibc_keep_openssl"
echo "$msg_upgrade_glibc_openssl"
echo "$msg_warning_glibc_upgrade"
echo "$msg_upgrade_glibc_make_you_cry"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
echo -n "[0] "
read RH_upgrade_option

echo "$msg_delimiter_star_line"
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_upgrade_whole_system"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
echo "$msg_delimiter_star_line"

# we must keep drbl 
APT_KEEP_OPT='-o RPM::Hold::=drbl'
YUM_KEEP_OPT='--exclude=drbl'
case "$RH_upgrade_option" in
  1)
     APT_KEEP_OPT="$APT_KEEP_OPT -o RPM::Hold::=glibc"
     YUM_KEEP_OPT="$YUM_KEEP_OPT --exclude=glibc --exclude=glibc-common --exclude=glibc-devel --exclude=glibc-headers"
     ;;
  2)
     APT_KEEP_OPT="$APT_KEEP_OPT -o RPM::Hold::=openssl"
     YUM_KEEP_OPT="$YUM_KEEP_OPT --exclude=openssl"
     ;;
  *)
     APT_KEEP_OPT="$APT_KEEP_OPT -o RPM::Hold::=openssl -o RPM::Hold::=glibc"
     YUM_KEEP_OPT="$YUM_KEEP_OPT --exclude=openssl --exclude=glibc --exclude=glibc-common --exclude=glibc-devel --exclude=glibc-headers"
esac

# do it
[ "$installer" = "apt" ] && apt-get dist-upgrade $APT_KEEP_OPT 
[ "$installer" = "yum" ] && yum $YUM_KEEP_OPT update
} # end of do_upgrade_system_for_RH

#
import_rpm_key() {
echo "$msg_delimiter_star_line"
case "$OS_Version" in
   FC*)
    # import GPG key if not imported.
    if ! rpm -qi --quiet gpg-pubkey-db42a60e-37ea5438; then
      echo -n "Importing the RPM-GPG-KEY from /usr/share/doc/fedora-release-${OS_Version:2}/RPM-GPG-KEY ..."
      rpm --import /usr/share/doc/fedora-release-${OS_Version:2}/RPM-GPG-KEY
      echo "done!"
    fi
    if ! rpm -qi --quiet gpg-pubkey-4f2a6fd2-3f9d9d3b; then
      echo -n "Importing the RPM-GPG-KEY-fedora from /usr/share/doc/fedora-release-${OS_Version:2}/RPM-GPG-KEY-fedora ..."
      rpm --import /usr/share/doc/fedora-release-${OS_Version:2}/RPM-GPG-KEY-fedora
      echo "done!"
    fi
    ;;
  CO*)
    if ! rpm -qi --quiet gpg-pubkey-443e1821-421f218f; then
      # centos seems to only have one key
      echo -n "Importing the RPM-GPG-KEY from /usr/share/doc/centos-release-${OS_Version:2}/RPM-GPG-KEY ..."
      rpm --import /usr/share/doc/centos-release-${OS_Version:2}/RPM-GPG-KEY
      echo "done!"
    fi
    ;;
esac
} # end of import_rpm_key

#
do_upgrade_system_for_MDK() {
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_delimiter_star_line"
echo "$msg_upgrade_whole_system"
echo "$msg_delimiter_star_line"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL

APT_KEEP_OPT='-o RPM::Hold::=drbl'
case "$installer" in
  "apt")
    apt-get upgrade $APT_KEEP_OPT
    ;;
  "urpmi")
    # backup the original skip.list
    [ -f /etc/urpmi/skip.list ] && mv -f /etc/urpmi/skip.list /etc/urpmi/skip.list.drblsave
    # generate the skip list, we want to keep drbl
    cat <<EOF > /etc/urpmi/skip.list
drbl
EOF
    urpmi --auto-select

    [ -f /etc/urpmi/skip.list.drblsave ] && mv -f /etc/urpmi/skip.list.drblsave /etc/urpmi/skip.list
    ;;
esac
} # end of do_upgrade_system_for_MDK

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

#############
### main ####
#############

#
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"
	;;
   -s|--skip-select-repository)
        shift; select_repository="no"
	;;
   -y|--yum)
        shift; preferred_installer="yum"
	;;
   -a|--apt)
        shift; preferred_installer="apt"
	;;
   -m|--urpmi)
        shift; preferred_installer="urpmi"
	;;
   *)
	Usage
	exit 1
  esac
done
     
# mode is essential
[ -z "$mode" ] && Usage && exit 1

#
ask_and_load_lang_set $specified_lang

#
echo "$msg_delimiter_star_line"
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "$msg_hint_for_answer"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL

echo "$msg_delimiter_star_line"
# get the distribution name
OS_Version=`check_distribution_name`
echo "$msg_delimiter_star_line"

# try to find the OS_type, we put RedHat/Fedora as "RH", Mandrake as "MDK"
case "$OS_Version" in
   RH*)
      # For RH/FC, $client_archi_set will be decided by user or system.
      OS_type="RH"
      installer="apt"
      ARCH="i386"
      ;;
   FC*|CO*)
      OS_type="RH"
      # For RH/FC, $client_archi_set will be decided by user or system.
      # Yum is better is FC3 then that in FC2/FC1, we can use it as one of our
      # installer.
      case "$OS_Version" in
        FC3|CO*)
         # TODO x86_64: CPU arch -> rpm package, which one is real ?
         # "uname -m" or "rpm -q --qf '%{arch\n}' kernel..."
         if [ "$(uname -m)" = "x86_64" ]; then
             ARCH="x86_64"
         else
             ARCH="i386"
         fi
	 #
	 if [ "$preferred_installer" = "apt" ]; then
           installer="apt"
         else
           installer="yum"
         fi
	 ;;
	*)
	 # we only support x86 version and use apt for FC2/FC1
         ARCH="i386"
         installer="apt"
	 ;;
      esac
      ;;
   MDK*)
      OS_type="MDK"
      # For MDK, the arch is only i586
      ARCH="i586"
      client_archi_set="i586"
      # default installer for MDK9.2/10.0 is apt, while 10.1 it's urpmi
      # It seems that in MDK 9.2 the contrib urpmi repository has some problems.
      # so we just use apt
      case "$OS_Version" in
        MDK9.2|MDK10.0)
	 # for MDK 9.2/10.0, the default installer is apt
         if [ "$preferred_installer" = "urpmi" ]; then
           installer="urpmi"
         else
           installer="apt"
         fi
	 ;;
	*)
	 # for MDK 10.1, the default installer is urpmi
         if [ "$preferred_installer" = "apt" ]; then
           installer="apt"
         else
           installer="urpmi"
         fi
	 ;;
      esac
      ;;
   *)
   echo "This distribution version is NOT supported by DRBL, maybe you can try to use the drbl in testing or unstable repository. Program terminated!"
      exit 1 
esac

# for yum and apt, the regular expression for pkg is different.
netinstall_for_yum="rh-*-netinstall rh-FC*-netinstall mdk-*-netinstall woody-netinstall CentOS-*-netinstall"
netinstall_for_apt="rh-.*-netinstall rh-FC.*-netinstall mdk-.*-netinstall woody-netinstall CentOS-.*-netinstall"
# urpmi does not accept the package names with regular expression,
# so $netinstall_for_urpmi and $net_install_pkgs will be decided when urpmi source media is set.

eval net_install_pkgs=\$netinstall_for_${installer}

#
case "$installer" in
  "apt")
     inst_prog="apt-get"
     ;;
  "yum")
     inst_prog="yum"
     ;;
  "urpmi")
     inst_prog="urpmi"
     ;;
  *)
     echo "Unknown installer!!! Program terminated!"
     exit 1
     ;;
esac

# for CentOS, we force to make select_repository="no", we will not put centos 
# yum config in this file
# for some distributions, we have to force user select the repository
# for FC3 and newer version, the question is open
# in the future, maybe we will set all the distribution select_repository="no"
case "$OS_Version" in
     CO*)
       select_repository="no"
       ;;
     RH*|FC[1-2]|MDK*)
       select_repository="yes"
       ;;
esac

# do it
case "$mode" in
   install)
        [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
	eval msg=\$msg_install_${OS_type}
	echo $msg
        [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
	install_drbl_${OS_type}
	;;
   uninstall)
        [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
	eval msg=\$msg_uninstalling_DRBL_${OS_type}
	echo $msg
	echo "$msg_analyzing_rpm_info"
        [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
	uninstall_drbl_${OS_type}
	;;
   *)
	Usage
	exit 1
esac
