#!/bin/sh
# Author: Blake, Kuo-Lien Huang
# License: GPL
# Description: 
#
#


## function: removeentries
## $1 - Tag for START
## $2 - Tag for End
## $3 - File to read
removeentries() {
  while read line; do
    case "$line" in $1)
      while read line; do
        if [ "$line" = "$2" ]; then break; fi
      done
    esac
    if [ "$line" = "$2" ]; then continue; fi
    echo "$line"
  done < $3
}
START_TAG="# Added by DRBL"
END_TAG="# Added by DRBL Done."

echo "This script will add a repository for DRBL and"
echo "install needed packages for DRBL installation"
echo -n "Do you want to continue [Y|n]? "
read ANS
if [ "$ANS" = "N" -o "$ANS" = "n" ]; then exit 0; fi

ANS=""
while [ -z "$ANS" ]; do
  echo -n "Which release of your Debian system [woody|sarge|sid]? "
  read ANS
  if [ "$ANS" != "woody" -a "$ANS" != "sarge" -a "$ANS" != "sid" ]; then ANS=""; fi
done

R=""
case "$ANS" in
  "woody") R="deb http://opensource.nchc.org.tw/apt/drbl woody drbl" ;;
  "sarge"|"sid") R="deb http://opensource.nchc.org.tw/apt/drbl sarge drbl" ;;
esac

echo "I got it!! The repository"
echo " '$R'"
echo "is added in your /etc/apt/sources.list"
removeentries "$START_TAG" "$END_TAG" /etc/apt/sources.list > /tmp/sources.list.$$
echo "$START_TAG" >> /tmp/sources.list.$$
echo "$R" >> /tmp/sources.list.$$
echo "$END_TAG" >> /tmp/sources.list.$$
mv /tmp/sources.list.$$ /etc/apt/sources.list

echo "Some packages will be installed for DRBL installation"
echo -n "Press any key to continue..."
read PAUSE

apt-get update
apt-get install drbl-installer drbl-script

if [ -f /opt/drbl/sbin/drblsrv -a -f /opt/drbl/sbin/drblpush ]; then
  echo "Now, you have got the packages for DRBL installation"
  echo "All the scripts are located at /opt/drbl"
  echo "/opt/drbl/sbin/drblsrv will help you to setup DRBL server and"
  echo "/opt/drbl/sbin/drblpush will help you to setup DRBL clients"
  echo "You could do them by yourself or"
  echo -n "Let me to help you [Y|n]? "
  read ANS
  if [ "$ANS" = "N" -o "$ANS" = "n" ]; then exit 0; fi
  
  echo "Now, setup DRBL server"
  echo "Some services (tftpd,nfs,nis,ntp,ssh) will be installed and"
  echo "the DRBL clients template will be created at /var/lib/diskless/default/root"
  echo "Press any key to continue..."
  read PAUSE
  /opt/drbl/sbin/drblsrv

  export GPL=0;
  echo "Now, setup DRBL clients"
  echo "Two modes (starter,advanced) are provided to setup DRBL clients"
  echo "Choose one (S for starter mode, A for advanced mode) [S|a]? "
  read ANS
  case "$ANS" in
    "a"|"A") /opt/drbl/sbin/drblpush ;;
    *) /opt/drbl/sbin/drblpush --auto ;;
  esac

else
  echo "Something wrong when install the needed packages"
  echo "If it is not caused by you, please email the problem to drbl@opensource.nchc.org.tw"
  echo "Thank you very much!!"
fi
