#!/bin/bash
#
# tcs_firstboot:   Starts the final stages of the TCS Linux build process
#
# chkconfig: 345 59 91
# description: TCS FirstBoot
#
#

unset LC_MESSAGES
[ -f /etc/sysconfig/i18n ] && . /etc/sysconfig/i18n
export LANG

. /etc/init.d/functions

cd /tmp

log()
{
  #echo $* | tee -a ${LOGFILE}
  echo $* >> ${LOGFILE}
}

#
# Global variables
#
ARCH=`uname -m`
CONFIG=/etc/sysconfig/tcs_firstboot
LOGFILE=/root/tcs_firstboot.log
RUN_FIRSTBOOT='yes'
BASE_URL="http://rhn.cos.agilent.com/pub/ks/profiles"


RH=$(
  awk '
    /release 3/{print "3"}
    /release 4/{print "4"}
    /release 5/{print "5"}
    /release 6/{print "6"}
    /release 8/{print "8"}
    /release 9/{print "9"}
  ' /etc/redhat-release
)
RH_CH=$(/bin/awk '{print $5}' /etc/redhat-release)

date >> ${LOGFILE} 

if [ -f ${CONFIG} ]; then
  . ${CONFIG}
  export CONFIG
  log "The file ${CONFIG} exists"
else 
  log "The file ${CONFIG} does not exists"
  RUN_FIRSTBOOT='yes'
fi

start() {
  log "Running TC_FIRSTBOOT"


  for conf in Site All BuildType ProfileName
  do
     case ${conf} in
        All         ) URL="${BASE_URL}/all";
        ;;
        BuildType   ) URL="${BASE_URL}/${BuildType}";
        ;;
        ProfileName ) URL="${BASE_URL}/${ProfileName}";
        ;;
        Site        ) URL="${BASE_URL}/site/${Site}";
                      URL=$(echo "${URL}" | sed 's/\s/%20/g')
        ;;
     esac

     #echo wget -q -O /tmp/tcs_firstboot_files.txt ${URL}/firstboot/files.txt
     wget -q -O /tmp/tcs_firstboot_files.txt ${URL}/firstboot/files.txt

     cnt=$(awk 'END{printf("%d", NR)}' /tmp/tcs_firstboot_files.txt)

     if (( ${cnt} > 0 ))
       then
         for file in $(cat /tmp/tcs_firstboot_files.txt)
         do
           if [ "${file}" != "" ]
            then 
              wget -q -O ${file} ${URL}/firstboot/${file}
              chmod 550 ./${file}
              log "Running ${conf} firstboot script ${file}"
              ./${file} 
     #         rm -rf ${file}
           fi
         done
       else
         echo "There are no ${conf} scripts to run"
         echo "${conf} debug info: URL=${URL}"
     fi
        
  done

  echo RUN_FIRSTBOOT=no >> ${CONFIG}

  log "Exiting TC_Firstboot"
}

case "$1" in
  start)
    if [ "${RUN_FIRSTBOOT}" = 'no' ] && [ "$2" != "now" ]
      then
        log "Not Running TC_FIRSTBOOT, RUN_FIRSTBOOT flag is set to NO"
        exit 0
      else
        start
    fi
  ;;
esac

exit $RETVAL
