#!/bin/ksh
# Copyright 2003 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# ident  "@(#)se6000configure 1.46     04/12/20 SMI"
#

WATCHDOG_OFF=/opt/se6x20/watchdog_no_restart

#####
# validateAddress()
# Check to make sure a string is formatted correctly
# to be and IP address.
#####

validateAddress()
{
  p1=$(echo $1|cut -f1 -d.)
  p2=$(echo $1|cut -f2 -d.)
  p3=$(echo $1|cut -f3 -d.)
  p4=$(echo $1|cut -f4 -d.)
  p5=$(echo $1|cut -f5 -d.)

  #
  # expr $x + 1000 is used throughout the script 
  # to make sure that the field being tested is 
  # a number. The only time this would fail is
  # if the number being tested is -1000, and for
  # all cases where this is used, -1000 is never
  # valid.
  #
  if ! expr $p1 + 1000 1>/dev/null 2>&1 ||
     ! expr $p2 + 1000 1>/dev/null 2>&1 ||
     ! expr $p3 + 1000 1>/dev/null 2>&1 ||
     ! expr $p4 + 1000 1>/dev/null 2>&1 
  then
    return 1
  fi

  if [ -n "$p1" ] && [ $p1 -ge 1 ] && [ $p1 -le 255 ] &&
     [ -n "$p2" ] && [ $p2 -ge 0 ] && [ $p2 -le 255 ] &&
     [ -n "$p3" ] && [ $p3 -ge 0 ] && [ $p3 -le 255 ] &&
     [ -n "$p4" ] && [ $p4 -ge 0 ] && [ $p4 -le 255 ] &&
     [ -z "$p5" ]
  then
    return 0
  fi
  return 1
}

#####
# validateTZ()
# validates the timezone value passed to it. Every timezone is
# associated with a timezone file under /usr/share/lib/zoneinfo
# Therefore, if the file does not exist, then the user can not
# enter the timezone.
#
# Returns 0 if the file exists and 1 otherwise
#####

validateTZ()
{
  tzFile=$(echo "/usr/share/lib/zoneinfo/$1")
  if [ -f $tzFile ]
  then
    return 0
  else
    return 1
  fi
}

#####
#findExistingSps()
#####

findExistingSps()
{
  if [ alreadyFoundSps -eq 0 ]
  then
    alreadyFoundSps=1
  else
    return 0
  fi

  myecho "$YOUR_CURRENT_SP_IS $currentSpName."
  myecho "$LOOK_FOR_EXISTING_SP"
  for i in 0 1 2 3 4 5 6 7
  do
    if [ "$currentSpName" != "sp$i" ]
    then
      myecho "$PING_SP sp$i ..."
      if ping sp$i 5 1>/dev/null 2>&1
      then
        if [ -z "$existingSps" ]
        then
          existingSps="$i"
          existingSpNames="sp$i"
        else
          existingSps="$existingSps,$i"
          existingSpNames="$existingSpNames,sp$i"
        fi
      fi
    fi
  done
  return 0
}


#####
# uncfgFindSps()
#
# It differs from findExistingSps by the names
# in the list that it searches for.  It checks
# for an added name of "new_sp".
#####

uncfgFindSps()
{
  myecho "$YOUR_CURRENT_SP_IS $currentSpName."
  myecho "$LOOK_FOR_EXISTING_SP"

  existingSpNames=""
  for spName in sp0 sp1 sp2 sp3 sp4 sp5 sp6 sp7 new_sp
  do
    if [ "$currentSpName" != "$spName" ]
    then
      myecho "$PING_SP $spName ..."
      if ping $spName 5 1>/dev/null 2>&1
      then
        if [ -z "$existingSpNames" ]
        then
          existingSpNames="$spName"
        else
          existingSpNames="$existingSpNames, $spName"
        fi
      fi
    fi
  done
  return 0
}


#####
# testNetwork()
#####

testNetwork()
{
  echoheader "$TEST_HOST_HEADER"
  gotit=0
  while [ $gotit -eq 0 ]
  do
    myprintf "$TEST_HOST_PROMPT "
    ans=$(myread)
    if validateAddress $ans
    then
      testHost=$(echo $ans | cut -f1,2,3,4 -d.)

      myecho "$TEST_HOST_WARNING"
      if ping $testHost 1>/dev/null 2>&1
      then
        myecho "$TEST_HOST_SUCCESS"
        return 0
      else
        if $FW_CONFIG -d --ping $testHost 1>/dev/null 2>$1
        then
            # ping from SP failed but ping from Firewall works
            myecho "$TEST_HOST_ISSUE" $testHost
        else
            # ping from SP and Firewall both failed
            myecho "$TEST_HOST_FAILURE" $testHost
        fi
        myprintf "$TEST_HOST_AGAIN"
        ans=$(myread)
        if [ "$ans" != "Y" ] && [ "$ans" != "y" ]
        then
      return 1
        fi
      fi
    else
      myecho "$INVALID_VALUE"
    fi
  done
}

#####
# upgradeSystem
#####
upgradeSystem()
{
  CDdrive=/cdrom

  ans=$(ckyorn -Q \
       -p "$UPGRADE_RE_INSTALL_MSG" \
       -e "Invalid response.  Enter (y or n)" | \
       awk '{ if ( $1 ~ /^[yY]/) { print "y"} else { print "n"} }')
  if [[ $ans = "n" ]]; then
    exit 1
  fi
  
  ans=$(ckkeywd -Q -d continue \
       -p "$UPGRADE_INSERT_CD_MSG" \
       -e "Invalid response.  Press <Enter> to continue or quit to exit" \
       continue quit)
  if [[ $ans = "quit" ]]; then
    exit 2
  else
#
#  The CD has a file (name TBD using CD_version for now) that contains the 
#  version of the storage system.  If the file is not there or cannot be read 
#  then exit out of the upgrade with an error.
#
    cd_version_file=$(find $CDdrive -name CD_version)
    if [[ -z $cd_version_file ]]; then
      myecho "$UPGRADE_CD_READ_ERROR_MSG"
      exit 3
    else
#********
#  May need to do some processing here to get the major, mid and minor parts
#  of the CD version.  For now assuming the contents is identical to the
#  output of the iam command...
#********
      upgradeGetUSBVersion
      ret=$?
      if [[ $ret -ne 0 ]]; then
        myecho "$UPGRADE_USB_VERSION_ERROR_MSG"
        exit 4
      else
        usb_major=$(echo $usb_version | cut -f1 -d.)
        usb_mid=$(echo $usb_version | cut -f2 -d.)
        usb_minor=$(echo $usb_version | cut -f3 -d.)
        #print "USB info: $usb_version $usb_major $usb_mid $usb_minor"
        cd_version=$(cat $cd_version_file | grep -i version | cut -f2 -d:)
        cd_major=$(echo $cd_version | cut -f1 -d.)
        cd_mid=$(echo $cd_version | cut -f2 -d.)
        cd_minor=$(echo $cd_version | cut -f3 -d.)
        #print "CD info: $cd_version $cd_major $cd_mid $cd_minor"
#
# A storage system cannot be upgraded if it's current version is greater
# than the version on the CD.
#
        if [[ $cd_major < $usb_major || \
              $cd_mid < $usb_mid || \
              $cd_minor < $usb_minor ]]; then
          myecho "$UPGRADE_INVALID_VERSION_MSG"
          print "Local version is $usb_version, restore version is $cd_version"
          umount /mnt
          exit 5
        else
          #print "OK to upgrade"
          upgradeBackupPersistentData
          if [[ $? -ne 0 ]]; then
            myecho "$UPGRADE_PERSISTENT_DATA_BACKUP_ERROR_MSG"
            exit 6
          else
#
#  Install new platform
#
            print "Would reboot using cdrom - install now"
            exit 0
            #reboot "cdrom - install"
          fi
        fi
      fi
    fi
  fi
}


#####
# upgradeGetUSBVersion()
#####
upgradeGetUSBVersion()
{
#
# Stop the cron entry that executes the fbr backup every 2 minutes.  Need to
# mount the USB device and don't want to interfere with backups.  Also at
# this point the contents will be copied to the DSP for safe keeping and
# the state must not change after that.
#
  SAVE_EDITOR=$EDITOR
  while crontab -l | grep "fbr -b" > /dev/null ; do
    EDITOR=ex; export EDITOR
    crontab -e << EOF > /dev/null
/fbr -b
d
.
w
q
EOF
  done
  EDITOR=$SAVE_EDITOR; export EDITOR
#
# Wait for any fbr processes to terminate.
#
  let first=1
  while ps -aef | grep "fbr -b"; do
    if (( first )); then
      print "Waiting for fbr to terminate.\c"
      let first=0
    else
      print ".\c"
    fi
    sleep 5
  done
  print ""

  RFLASH=/dev/rdsk/c1t0d0s2
  FLASH=/dev/dsk/c1t0d0s2
#
# Sometimes the usb flash disk goes into some funky state and will
# output a Corrupt Label error.  This cannot be easily reproduced
# due to an unknown root cause.  For now check to see if it is
# suitable for mounting, and if not execute the rmformat command that
# will relabel it.  This does NOT affect the contents of the device.
#
  status=$(fsck -m ${RFLASH} > /dev/null 2>&1; echo $?)
  if [[ $status -ne 0 ]]; then
    #print "writing a new label"
    /usr/bin/rmformat -b SUN ${FLASH}
  fi
  mkdir -p /mnt
  status=$(mount ${FLASH} /mnt > /dev/null 2>&1; echo $?)
  if [[ $status -eq 0 ]]; then
#
# usb_version is global to the upgrade functionality
#
    usb_version=$(cat /mnt/iam.txt | grep -i version | cut -f2 -d:)
  else
    myecho "$UPGRADE_USB_MOUNT_ERROR_MSG"
    return 1
  fi
  return 0
}

#####
# upgradeBackupPersistentData()
#####
upgradeBackupPersistentData()
{
#
# Backup system information
#
# DSP information
#
  DSP_IP="192.168.0.10"
  HOMEDIR="$HOME"
  FTPUSER="root"
  FTPPW="sun1"
  TMPNETRC=/tmp/netrc.$$    # Backup copy of existing .netrc

#
# See if the DSP is accessible
#
  ping $DSP_IP 1 1> /dev/null 2>&1
  ERRCODE=$?
  if [[ $ERRCODE -ne 0 ]]; then
    myecho "$UPGRADE_DSP_UNREACHABLE_MSG"
    umount /mnt
    return 1
  else
    if [ -f $HOMEDIR/.netrc ]; then
      mv $HOMEDIR/.netrc $TMPNETRC    # Preserve any existing .netrc
    fi
#
# Create the resource file that will transfer the persistent files to
# the DSP for safe keeping
#
    print "machine $DSP_IP login $FTPUSER password $FTPPW" > $HOMEDIR/.netrc
    print "macdef init" >> $HOMEDIR/.netrc
    print "bin"  >> $HOMEDIR/.netrc
    print "prompt"  >> $HOMEDIR/.netrc
#
# mkdir not recognized on DSP
#
    #print "mkdir $UPGRADEDIR" >> $HOMEDIR/.netrc
    #print "cd $UPGRADEDIR" >> $HOMEDIR/.netrc
#
# filenames on DSP must be in 8.3 format
# Also, cannot use absolute path for target on DSP
#
    print "put /mnt/SP_Personality.tar.Z SPERSIST.TAR" >> $HOMEDIR/.netrc
    print "put /mnt/iam.txt IAM.TXT" >> $HOMEDIR/.netrc
    print "quit"  >> $HOMEDIR/.netrc
    print ""  >> $HOMEDIR/.netrc
    chmod 600 $HOMEDIR/.netrc
#
# Start ftp process
#
    ftp $DSP_IP 1> /dev/null 2>&1
#
# Clean up
#
    cd $HOMEDIR
    rm -f $HOMEDIR/.netrc         # Remove .netrc file
    if [[ -f $TMPNETRC ]]; then
      mv $TMPNETRC $HOMEDIR/.netrc  # Restore previous .netrc
    fi
#
# unmount the USB device
#
    umount /mnt
  fi
  return 0
}

#####
# restoreConfig()
#####

restoreConfig()
{
  echoheader "$RESTORE_HEADER"
  gotit=0
  while [ $gotit -eq 0 ]
  do
    myecho "$RESTORE_WARNING"
    myprintf "$CONFIRM_OPERATION_PROMPT"
    ans=$(myread)

    if [ "$ans" = "Y" ]  || [ "$ans" = "y" ]
    then
      restore_flag=1
      gotit=1
      myecho "$RESTORE_OPERATION_RESULT"
      myecho "$RUNNING_STEP_ONE_OF_ONE"
      /opt/SUNWsefbru/bin/fbr -r
      rc=$?
      if [ $rc -eq 0 ]
      then
        myecho "$RESTORE_OPERATION_SUCCESS"
        myecho ""
        myecho "$UPDATE_RASAGENT_CONFIG"
        /bin/nohup /opt/SUNWstade/sysbin/config_solution -m 6920
      else
        myecho "$RESTORE_OPERATION_FAILURE $rc."
	restore_flag=2
      fi

    elif [ "$ans" = "N" ] || [ "$ans" = "n" ]
    then 
      restore_flag=2
      gotit=1
    else
      myecho "$INVALID_VALUE"
    fi
  done
  myprintf "\n$PRESS_ENTER"
  ans=$(myread)
  return 0
}

#####
# unConfig()
#####

unConfig()
{
  echoheader "$UNCONFIG_HEADER"
  gotit=0
  while [ $gotit -eq 0 ]
  do
    myecho "$UNCONFIG_WARNING"
    myprintf "$CONFIRM_OPERATION_PROMPT"
    ans=$(myread)
    if [ "$ans" = "Y" ]  || [ "$ans" = "y" ]
    then
      storEdgeId=-1
      networkSetting="Fixed"
      newSpName="new_sp"
      newSpAddress=$(grep -w $newSpName /etc/hosts | grep -v "-" | cut -f1 -d' ')
      newRouterAddress=$(grep new_firewall /etc/hosts | cut -f1 -d' ')
      newNTCAddress=$(grep new_ntc /etc/hosts | cut -f1 -d' ')
      ipAddress="127.0.0.1"
      gatewayAddress="127.0.0.1"
      netmaskAddress="255.0.0.0"
      nameServerAddress=""
      domainNameAddress=""

      # Timezone is set to GMT
      # The date is set to 01/01/2000
      # The time is set to 00:00
      tzToSet=GMT
      dateToSet=01/01/2000
      timeToSet=00:00


      gotit=1
    elif [ "$ans" = "N" ] || [ "$ans" = "n" ]
    then 
      return 1
    else
      myecho "$INVALID_VALUE"
    fi
  done

  gotit=0
  while [ $gotit -eq 0 ]
  do
    uncfgFindSps
    if [ -z "$existingSpNames" ]
    then
      myecho "$NO_SPS_FOUND"
      gotit=1
    else
      myecho "$FOLLOWING_SPS_FOUND $existingSpNames\n"
      myprintf "$currentSpName $DISCONNECT_SP_LAN1$existingSpNames$DISCONNECT_SP_LAN2"
      read $ans
    fi
  done
  
  return 0
  
}

#####
# configPower()
#####

configPower()
{
  storEdgeId=-1
  echoheader "$CONFIG_POWER_HEADER"
  gotit=0
  while [ $gotit -eq 0 ]
  do
    if [ -f $POWER_SEQUENCER_FILE ]
    then
       myecho "$DISABLE_POWER_WARNING"
    else
       myecho "$ENABLE_POWER_WARNING"
    fi
    myprintf "$CONFIRM_OPERATION_PROMPT"
    ans=$(myread)
    if [ "$ans" = "Y" ]  || [ "$ans" = "y" ]
    then
      if [ -f $POWER_SEQUENCER_FILE ]
      then
         $VMCFG unconfigure -t ps
      else
         $VMCFG configure -t ps
      fi
      rc=$?
      gotit=1
    elif [ "$ans" = "N" ] || [ "$ans" = "n" ]
    then 
      return 1
    else
      myecho "$INVALID_VALUE"
    fi
  done
  return $rc
  
}


#####
# initialConfig()
#####

initialConfig()
{
  echoheader "$INITIAL_CONFIG_HEADER"
  myecho "$INITIAL_CONFIG_WARNING"

  findExistingSps

  gotit=0
  while [ $gotit -eq 0 ]
  do
    if [ -z "$existingSps" ]
    then
      myecho "$NO_SPS_FOUND"
      myecho "$STOREDGE_ID"
    else
      myecho "$FOLLOWING_SPS_FOUND $existingSpNames"
      myecho "$STOREDGE_ID_EXCLUDE $existingSps"
    fi
    
    myprintf "$YOUR_CHOICE"
    ans=$(myread)
    if expr $ans + 1000 1>/dev/null 2>&1 &&
       [ $ans -ge 0 ] && [ $ans -le 7 ] &&
       [ -z "$(echo $existingSps | grep $ans)" ]
    then
      gotit=1
    else
      myecho "$INVALID_VALUE"
    fi
  done
  storEdgeId=$ans
  newSpName="sp"$ans
  newSpAddress=$(grep -w $newSpName /etc/hosts | grep -v "-" | cut -f1 -d' ')
  newRouterAddress=$(grep -w $newSpName-firewall /etc/hosts | cut -f1 -d' ')
  newNTCAddress=$(grep -w $newSpName-ntc /etc/hosts | cut -f1 -d' ')
   
  echosubheader "$NETWORK_SETTINGS :"
  
  gotit=0
  while [ $gotit -eq 0 ]
  do
    myecho "$DHCP_OR_FIXED"
    myecho "$DHCP_PROMPT"
    myecho "$FIXED_PROMPT"
    myprintf "$YOUR_CHOICE"
    ans=$(myread)
    if expr $ans + 1000 1>/dev/null 2>&1 &&
       [ $ans -ge 1 ] && [ $ans -le 2 ]
    then
      gotit=1
    else
      myecho "$INVALID_VALUE"
    fi
  done
  if [ $ans -eq 1 ] 
  then
    networkSetting="DHCP"
    netmaskAddress="255.255.255.0"
  else
    networkSetting="Fixed"
  fi
   
  
  if [ "$networkSetting" = "Fixed" ]
  then
    gotit=0
    while [ $gotit -eq 0 ]
    do
      myprintf "$IP_ADDRESS_PROMPT"
      ans=$(myread)
      if validateAddress $ans
      then
        gotit=1
      else
        myecho "$INVALID_VALUE"
      fi
    done
    ipAddress=$(echo $ans | cut -f1,2,3,4 -d.)
   
    gotit=0
    while [ $gotit -eq 0 ]
    do
      myprintf "$GATEWAY_PROMPT"
      ans=$(myread)
      if validateAddress $ans
      then
        gotit=1
      else
        myecho "$INVALID_VALUE"
      fi
    done
    gatewayAddress=$(echo $ans | cut -f1,2,3,4 -d.)
   
    gotit=0
    while [ $gotit -eq 0 ]
    do
      myprintf "$MASK_PROMPT"
      ans=$(myread)
      if validateAddress $ans
      then
        gotit=1
      else
        myecho "$INVALID_VALUE"
      fi
    done
    netmaskAddress=$(echo $ans | cut -f1,2,3,4 -d.)
   
  fi

  gotit=0
  while [ $gotit -eq 0 ]
  do
    myprintf "$NAME_SERVER_PROMPT"
    ans=$(myread)
    if validateAddress $ans
    then
      gotit=1
    else
      myecho "$INVALID_VALUE"
    fi
  done
  nameServerAddress=$(echo $ans | cut -f1,2,3,4 -d.)


  gotit=0
  while [ $gotit -eq 0 ]
  do
    myprintf "$DOMAIN_NAME_PROMPT"
    ans=$(myread)
    gotit=1
  done
  domainNameAddress=$ans

  # Timezone settings
  tzToSet="0"

  currentTZ=`echo $TZ`
  myecho ""
  myecho "$DISPLAY_CUR_TZ $currentTZ"

  echosubheader "$TIME_ZONE_SETTINGS"

  gotit=0
  while [ $gotit -eq 0 ]
  do
    myecho "$SELECT_TZ"
    myecho "$ENTER_TZ"
    myecho "$SELECT_DEFAULT_TZ"
    myprintf "$YOUR_CHOICE"
    ans=$(myread)
    #
    # Make sure $ans is an integer before using in a test
    #
    if ! expr $ans + 1000 1>/dev/null 2>&1 
    then
      myecho "$INVALID_VALUE"
    elif [ $ans -eq 1 ] 
    then
      ans=`/usr/bin/tzselect`
      myecho $ans
      tzToSet=$ans
      gotit=1
    elif [ $ans -eq 2 ] 
    then
      while [ $gotit -eq 0 ]
      do
	myprintf "$TZ_REQUEST_PROMPT"
	ans=$(myread)
	if validateTZ $ans
	then
	  tzToSet=$ans
	  gotit=1
	else
	  myecho "$INVALID_VALUE"
	fi
      done
    elif [ $ans -eq 3 ]
    then
      gotit=1
    else
      myecho "$INVALID_VALUE"
    fi
  done

    # Date and Time settings
  dateToSet="0"
  timeToSet="0"

  myecho ""
  myecho "$DISPLAY_CUR_DATE `date`"

  echosubheader "$DATE_TIME_SETTINGS"

  gotit=0
  while [ $gotit -eq 0 ]
  do
    myecho "$CHANGE_DATE_AND_TIME"
    myecho "$SELECT_DEFAULT_DATE"
    myprintf "$YOUR_CHOICE"
    choice=$(myread)

    if [ $choice -eq 1 ]
    then
      getNewDate
      getNewTime
      gotit=1
    elif [ $choice -eq 2 ]
    then
      gotit=1
    else
      myecho "$INVALID_VALUE"
    fi
  done


  # Check if all settings are alright

  myecho "\n*************************************************************"
  echosubheader "$SYSTEM_SETTINGS"
  myecho "$DISPLAY_ID $storEdgeId"
  echosubheader "$NETWORK_SETTINGS"
  myecho "$DISPLAY_NETWORK_SETTING $networkSetting"

  if [ "$networkSetting" = "Fixed" ]
  then
    myecho "$DISPLAY_ADDRESS $ipAddress"
    myecho "$DISPLAY_GATEWAY $gatewayAddress"
    myecho "$DISPLAY_MASK $netmaskAddress"
  fi
  myecho "$DISPLAY_NAME_SERVER $nameServerAddress"
  myecho "$DISPLAY_DOMAIN_NAME $domainNameAddress"

  if [ $tzToSet != "0" ]
  then
    echosubheader "$NEW_TIME_ZONE_SETTINGS"
    myecho "$DISPLAY_TZ $tzToSet"
  fi

  if [ $dateToSet != "0" ] || [ $timeToSet != "0" ]
  then
    echosubheader "$NEW_DATE_TIME_SETTINGS"
    if [ $dateToSet != "0" ]
    then
      myecho "$DISPLAY_DATE $dateToSet"
    fi
    if [ $timeToSet != "0" ]
    then
      myecho "$DISPLAY_TIME $timeToSet"
    fi
  fi

  myecho "\n*************************************************************\n"

  gotit=0
  while [ $gotit -eq 0 ]
  do
    myprintf "$CONFIRM_SETTINGS_PROMPT"
    ans=$(myread)
    if [ "$ans" = "Y" ]  || [ "$ans" = "y" ]
    then
      return 0
    elif [ "$ans" = "N" ] || [ "$ans" = "n" ]
    then 
      return 1
    else
      myecho "$INVALID_VALUE"
    fi
  done

  return 0
}

getNewDate() {
  gotit=0
  while [ $gotit -eq 0 ]
  do
    myprintf "$DATE_PROMPT"
    ans=$(myread)
    if /usr/sadm/bin/valdate -f %m/%d/%Y $ans
    then
      gotit=1
    else
      myecho "$INVALID_VALUE"
    fi
  done
  dateToSet=$ans
}

getNewTime() {
  gotit=0
  while [ $gotit -eq 0 ]
  do
    myprintf "$TIME_PROMPT"
    ans=$(myread)
    if /usr/sadm/bin/valtime -f %H:%M $ans
    then
      gotit=1
    else
      myecho "$INVALID_VALUE"
    fi
  done
  timeToSet=$ans
}

####
# disbleWatchdog
####
disbleWatchdog()
{
  touch $WATCHDOG_OFF
  sleep 2
}

####
# enableWatchdog
####
enableWatchdog()
{
  rm -f $WATCHDOG_OFF
}

####
# restart_wbem
####
restart_wbem() {
	while [ -f /tmp/sleeping ]
	do
		myprintf '.';
		sleep 10
	done &

	# temporarly disable the watchdog to prevent two CIMOMs from running
	disableWatchdog()

	/opt/se6x20/bin/init.wbem_only stop
	/opt/se6x20/bin/init.wbem_only start

	# enable the watchdog now that the CIMOM is running
	enbleWatchdog()

	rm -f /tmp/sleeping
}

####
# restart_tomcat
####
restart_tomcat() {
	while [ -f /tmp/sleeping ]
	do
		myprintf '.';
		sleep 10
	done &

	# temporarly disable the watchdog to prevent two TOMCATs from running
	disbleWatchdog()

	/usr/sbin/smcwebserver stop
	/usr/sbin/smcwebserver start

	# enable the watchdog now that TOMCAT is running
	enbleWatchdog()

	rm -f /tmp/sleeping
}

#####
# setFirewall()
#####

setFirewall()
{

  cmd="$FW_CONFIG -d"

  if [ "$storEdgeId" = "-1" ]
  then
    cmd="$cmd --unconfigure"
  else
	myecho "$UPDATE_FIREWALL_CONFIG_TIME"
    if [ "$storEdgeId" = "0" ]
    then
      cmd="$cmd --dhcp_server en"
      cmd="$cmd --dhcp_dns_server $nameServerAddress"
    else
      cmd="$cmd --dhcp_server dis"
    fi

    cmd="$cmd --lan_ip_addr $newRouterAddress"
    cmd="$cmd --port_fwd_addr $newSpAddress"
  
    if [ "$networkSetting" = "Fixed" ]
    then
      cmd="$cmd --wan_ip_addr $ipAddress"
      cmd="$cmd --wan_gateway $gatewayAddress"
      cmd="$cmd --wan_subnet_mask $netmaskAddress"
      cmd="$cmd --wan_addr_type static"
    else
      cmd="$cmd --wan_addr_type dynamic"
    fi
  fi

  echo "Executing $FW_CONFIG with the following parameters" >> $CONFIGURE_LOG
  echo "$cmd" >> $CONFIGURE_LOG

  if [ "$storEdgeId" = "-1" ]
  then
    # need stdout to console, in case fw ip is not valid.
    $cmd 2>> $CONFIGURE_LOG
    rc=$?
  else
    touch /tmp/sleeping
    while [ -f /tmp/sleeping ]
    do
      myprintf '.';
      sleep 10
    done &

    $cmd >> $CONFIGURE_LOG 2>&1
    rc=$?

    rm -f /tmp/sleeping
  fi

  myecho "\n$RETURN_CODE (${rc}) : ${FW_ERROR[$rc]}"

  if [ $rc -eq 0 ]
  then
    return 0
  elif [ $rc -eq 16 ] 
  then
    myecho "$FW_WARNING_DHCP"
    rc=0
  elif [ $rc -eq 135 ] 
  then
    myecho "$FW_WARNING_RNID"
    rc=0
  else
    myecho "$FW_ERROR_FAIL"
  fi
  return $rc
}


#####
# setNTC()
#####

setNTC()
{
  touch /tmp/sleeping
  while [ -f /tmp/sleeping ]
  do
    myprintf '.';
    sleep 10
  done &

  cmd="$NTC_CONFIG -d"

  if [ "$storEdgeId" = "-1" ]
  then
    cmd="$cmd --unconfigure"
  else
    cmd="$cmd --new_ip $newNTCAddress"
  fi

  cmd="$cmd --curr_ip $currentNTCAddress"
  cmd="$cmd --sp_ip $newSpAddress"
  cmd="$cmd --reset"

  echo "Executing $NTC_CONFIG with the following parameters" >> $CONFIGURE_LOG
  echo "$cmd" >> $CONFIGURE_LOG
  $cmd >> $CONFIGURE_LOG 2>&1
  rc=$?

  rm -f /tmp/sleeping

  myecho "\n$RETURN_CODE (${rc}) : ${NTC_ERROR[$rc]}"

  if [ $rc -eq 0 ]
  then
    myecho "$NTC_GOOD"
    rc=0
  else
    myecho "$NTC_ERROR_FAIL"
  fi
  return $rc
}

#####
# setHostsFiles()
#####

setHostsFiles()
{
  for hostsFile in $(ls /etc/net/*/hosts)
  do
    grep -wv "$currentSpName" $hostsFile > $hostsFile.bak
    echo "$newSpName\t$newSpName" >> $hostsFile.bak
    mv $hostsFile.bak $hostsFile
  done

  echo "$newSpName" > /etc/hostname.dmfe0 
  echo "$newSpName" > /etc/nodename 
  hostname "$newSpName"
  mkdir /var/crash/$newSpName 2>/dev/null
  dumpadm -s /var/crash/$newSpName >/dev/null
  return 0
}

#####
# setConfig()
#####

setConfig()
{
  echoheader "$SET_CONFIG_HEADER"
  if [ "$newSpName" = "new_sp" ];then
    total_steps=12
  else
    total_steps=13
  fi

  if [ "$newSpName" != "new_sp" ];then
    step=1
    myecho "\n$RUNNING_STEP $step $STEP_OF $total_steps..."
    if [ $tzToSet != 0 ] || [ $dateToSet != 0 ] || [ $timeToSet != 0 ]
    then
      myecho "$UPDATE_TZ"
     
      if setTZDateAndTime
      then
        myecho "$SUCCESS"
      else
        myecho "$FAILURE"
        return 1
      fi
    else
      myecho "$NO_TZ_DATE_TIME_UPDATE"
    fi
  else
    step=0
  fi
  
  step=`expr $step + 1`
  myecho "\n$RUNNING_STEP $step $STEP_OF $total_steps..."
  myecho "$UPDATE_FIREWALL_CONFIG"

  # The firewall must be configured when the CIMOM knows it's correct
  # IP address or RNID will fail.  If the SP's IP address is changed before
  # the firewall is configured then the CIMOM will need to be restarted.
  if ! setFirewall 
  then
    myprintf "$CONTINUE_ON_ERROR" 
    ans=$(myread)
    if [ "$ans" = "N" ]  || [ "$ans" = "n" ]
    then
      return 1
    elif [ "$ans" != "Y" ]  && [ "$ans" != "y" ]
    then
      myecho "$INVALID_VALUE"
    fi
  fi

  step=`expr $step + 1`
  myecho "\n$RUNNING_STEP $step $STEP_OF $total_steps..."
  myecho "$UPDATE_IFCONFIG"

  if ifconfig dmfe0 set $newSpAddress netmask 255.255.255.0
  then
    myecho "$SUCCESS"
  else
    myecho "$FAILURE"
    return 1
  fi

  step=`expr $step + 1`
  myecho "\n$RUNNING_STEP $step $STEP_OF $total_steps..."
  myecho "$UPDATE_HOSTNAME"

  if setHostsFiles 
  then
    myecho "$SUCCESS"
  else
    myecho "$FAILURE"
    return 1
  fi

  step=`expr $step + 1`
  myecho "\n$RUNNING_STEP $step $STEP_OF $total_steps..."
  myecho "$UPDATE_RESOLV_CONF"

  rm -f /etc/resolv.conf
  if [ -n "$nameServerAddress" ]
  then
    echo "nameserver\t$nameServerAddress" >> /etc/resolv.conf
  fi
  if [ -n "$domainNameAddress" ]
  then
    echo "domain\t\t$domainNameAddress" >> /etc/resolv.conf
  fi

  #
  # Refresh Namserver Daemon Cache
  #
  if /etc/init.d/nscd stop
  then
    if /etc/init.d/nscd start
    then
      myecho "$SUCCESS"
    else
      myecho "$FAILURE"
    fi
  else
    myecho "$FAILURE"
  fi
 
  # The CIMOM needs to be restarted after the SP's IP changes
  # so the CIMOM knows what IP address it is at.
  # The CIMOM also needs to be restarted after the firewall's
  # WAN IP changes so SLP is advertised at the correct address.
  step=`expr $step + 1`
  myecho "\n$RUNNING_STEP $step $STEP_OF $total_steps..."
  myecho "$RESTART_WBEM"

  restart_wbem

  step=`expr $step + 1`
  myecho "\n$RUNNING_STEP $step $STEP_OF $total_steps..."
  myecho "$RESTART_TOMCAT"

  restart_tomcat

  step=`expr $step + 1`
  myecho "\n$RUNNING_STEP $step $STEP_OF $total_steps..."
  myecho "$RESTART_SENDMAIL"

  if /etc/init.d/sendmail restart 
  then
    myecho "$SUCCESS"
  else
    myecho "$FAILURE"
  fi

  step=`expr $step + 1`
  myecho "\n$RUNNING_STEP $step $STEP_OF $total_steps..."
  myecho "$RESTART_SE6000"
  rm -f /opt/se6x20/watchdog_no_restart
  if /opt/se6x20/bin/restart_se6000
  then
    myecho "$SUCCESS"
  else
    myecho "$FAILURE"
  fi

  step=`expr $step + 1`
  myecho "\n$RUNNING_STEP $step $STEP_OF $total_steps..."
  myecho "$UPDATE_DSP_CONFIG"

  /bin/nohup $VMCFG configure -t dsp -i dsp00

  step=`expr $step + 1`
  myecho "\n$RUNNING_STEP $step $STEP_OF $total_steps..."
  myecho "$UPDATE_RASAGENT_CONFIG"
  
  /bin/nohup /opt/SUNWstade/sysbin/config_solution -m 6920

  step=`expr $step + 1`
  myecho "\n$RUNNING_STEP $step $STEP_OF $total_steps..."
  myecho "$UPDATE_CRONTABS_LOG"

  if [ "$newSpName" = "new_sp" ];then
    SAVE_EDITOR=$EDITOR
    EDITOR=ex;export EDITOR
    
    while crontab -l | grep "fbr -b" > /dev/null ; do
      /usr/bin/crontab -e << end  > /dev/null
/fbr
d
w
q
end
   done
    EDITOR=$SAVE_EDITOR;export EDITOR
  else
    SAVE_EDITOR=$EDITOR
    EDITOR=ex;export EDITOR
    if ! crontab -l | grep "fbr -b" > /dev/null ; then
      /usr/bin/crontab -e << end  > /dev/null
$
a
0,5,10,15,20,25,30,35,40,45,50,55 * * * * /opt/SUNWsefbru/bin/fbr -b > /dev/null 2>&1
.
w
q
end
    fi

    EDITOR=$SAVE_EDITOR;export EDITOR

    # Clear log/mail files
    LIST="
    /var/adm/messages.dsp
    /var/adm/messages.array 
    "
    for i in $LIST
    do
      cp /dev/null $i > /dev/null 2>&1
    done

    # Delete extra messages
    rm /var/adm/messages.dsp.* > /dev/null 2>&1
    rm /var/adm/messages.array.* > /dev/null 2>&1

    # Truncated /var/mail/root
    cp /dev/null /var/mail/root > /dev/null 2>&1

  fi
  
  step=`expr $step + 1`
  myecho "\n$RUNNING_STEP $step $STEP_OF $total_steps..."
  myecho "$UPDATE_NTC_CONFIG"

  if setNTC
  then
    myecho "$SUCCESS"
  else
    myecho "$FAILURE"
    return 1
  fi

  myecho "\n$ATTN_MSG"

  myprintf "\n$PRESS_ENTER"
  ans=$(myread)
  return 0
}

#####
# setTZDateAndTime()
#####

setTZDateAndTime()
{
  restartDeamons=0
  hold="0"

  if [ $tzToSet != "0" ]
  then

    hold=${tzToSet}
    tzToSet=$(echo $tzToSet|sed 's/\//\\\//g')
    
    cmd=$(echo "cat /etc/default/init | sed 's/^TZ=.*/TZ=${tzToSet}/' > /tmp/etc_default_init.$$")
    eval $cmd
    
    #cp /etc/default/init /etc/default/init.`date +'m%d'`
    mv /tmp/etc_default_init.$$ /etc/default/init

    
    grep "^TZ=${hold}" /etc/default/init 1>/dev/null 2>&1
    if [ $? -ne 0 ]
    then
      return 1
    fi
    
    restartDeamons=1
  fi
  
  if [ $dateToSet != "0" ] && [ $timeToSet != "0" ]; then
    if [ $hold != "0" ]; then
      export TZ="$hold"
    fi
    
    myecho "$UPDATE_DATE_TIME"
    
    # The format for the date command is:
    # date mmddHHMMccyy

    month=$(echo $dateToSet|cut -f1 -d'/')
    day=$(echo $dateToSet|cut -f2 -d'/')
    year=$(echo $dateToSet|cut -f3 -d'/')
    

    hour=$(echo $timeToSet|cut -f1 -d':')
    min=$(echo $timeToSet|cut -f2 -d':')
    
    date ${month}${day}${hour}${min}${year} 1>/dev/null 2>&1

    if [ $? -eq 0 ]
    then
      myprintf "\n$NEW_DATE"
      date
    else
      return 1
    fi
    
    restartDeamons=1
  fi
    
  # If any of TZ, Date, Time changed, then we must restart the daemons
  if [ $restartDeamons -eq 1 ]
  then
    # We are interested in only these three daemons and so we are
    # going to restart only these three. 
    
    # The proper way is to modify the parameter TZ in /etc/default/init
    # reboot and then set the date so that this change is taken into 
    # effect by all processes, daemons.
    if [ $hold != "0" ]; then
      export TZ="$hold"
    fi
    
    # Restart syslogd
    /etc/init.d/syslog stop
    /etc/init.d/syslog start
    
    # Restart inetd
    kill -TERM `pgrep inetd`
    /usr/sbin/inetd -s
    
    # Restart wbem
	restart_wbem
    
    # Restart tomcat
	restart_tomcat
  fi
  
  return 0
}

#####
# myread()
#####

myread()
{
  read readVal
  echo "$readVal"
  echo "$readVal" >> $CONFIGURE_LOG
  return 0
}


#####
# myecho()
#####

myecho()
{
  echo "$*" >> $CONFIGURE_LOG
  echo "$*"
}


#####
# myprintf()
#####

myprintf()
{
  printf "$*" >> $CONFIGURE_LOG
  printf "$*"
}

#####
# echoheader()
#####

echoheader()
{
  STARS=$(echo "$1" | sed -e "s/./*/g")
  myecho "\n**$STARS**"
  myecho "* $1 *"
  myecho "**$STARS**\n"
}

#####
# echosubheader()
#####

echosubheader()
{
  DASHES=$(echo "$1" | sed -e "s/./-/g")
  myecho "\n $1 "
  myecho "-$DASHES-"
}

#####
# setMessages()
#####

setMessages()
{
  if [ ! -f $(dirname $0)/locale/C/messages.properties ]
  then
    myecho "FATAL ERROR : No message files, $0 unable to continue."
    myecho "Exiting."
    exit 1
  fi

  . $(dirname $0)/locale/C/messages.properties 2>/dev/null
  . $(dirname $0)/locale/C/FW_config_errors.properties 2>/dev/null
  . $(dirname $0)/locale/C/NTC_config_errors.properties 2>/dev/null
  if [ "$LANG" != "C" ]
  then
    if [ -f $(dirname $0)/locale/C/messages.properties ]
    then
      . $(dirname $0)/locale/C/messages.properties 2>/dev/null
      . $(dirname $0)/locale/C/FW_config_errors.properties 2>/dev/null
      . $(dirname $0)/locale/C/NTC_config_errors.properties 2>/dev/null
    fi
  fi
}

#############
#############
##
## Main
##
#############
#############

clear

FW_CONFIG=/usr/local/bin/FW_config
NTC_CONFIG=/usr/local/bin/ntc_config
CONFIGURE_LOG=/var/tmp/se6000configure.log
VMCFG=/opt/se6x20/bin/vmcfg 
POWER_SEQUENCER_FILE=/opt/se6x20/PSDATA/PS 

setMessages

if [ `tty` != "/dev/console" ]
then
    myecho "You must be on the console to perform Firewall configuration."
    exit 1
fi

if [ `id | cut -f1 -d\(` != "uid=0" ] ; then
    myecho "You must be 'setup' user to run this command"
    exit 1
fi

alreadyFoundSps=0
currentSpName=$(hostname)
if [ "$currentSpName" = "new_sp" ]
then
  currentNTCAddress=$(grep new_ntc /etc/hosts | cut -f1 -d' ')
else
  currentNTCAddress=$(grep $currentSpName-ntc /etc/hosts | cut -f1 -d' ')
fi


myecho $(date)
echoheader "$HEADER"

rc=1
allDone=0
while [ $allDone -eq 0 ]
do
  gotit=0
  restore_flag=0
  while [ $gotit -eq 0 ]
  do
    myecho "$RESTORE_INIT_OR_UNCONFIG"
    myecho "$INITIAL_PROMPT"
    myecho "$RESTORE_PROMPT"
    myecho "$UNCONFIG_PROMPT"
    if [ -f $POWER_SEQUENCER_FILE ]
    then
      myecho "$DISABLE_POWER_PROMPT"
    else
      myecho "$ENABLE_POWER_PROMPT"
    fi
    myecho "$UPGRADE_SYSTEM"
    myprintf "$YOUR_CHOICE"
    ans=$(myread)
#
# Make sure $ans is an integer before using in a test
#
    if ! expr $ans + 1000 1>/dev/null 2>&1 
    then
      myecho "$INVALID_VALUE"
    elif [ $ans -eq 1 ] 
    then
      parmsOK=1
      while [ $parmsOK -eq 1 ] 
      do
        initialConfig
        parmsOK=$?
      done
      setConfig
      rc=$?
      gotit=1
    elif [ $ans -eq 2 ]
    then 
      restoreConfig
      rc=$?
      gotit=1
    elif [ $ans -eq 3 ]
    then 
      if unConfig
      then
        setConfig
        rc=$?
      fi
      gotit=1
    elif [ $ans -eq 4 ]
    then 
      configPower
    elif [ $ans -eq 5 ]
    then
      upgradeSystem
    elif [ $ans -eq 911 ]
    then 
      gotit=1
      myecho "$RESTART_SE6000"
      myprintf "$CONFIRM_OPERATION_PROMPT"
      ans=$(myread)
      if [ "$ans" = "Y" ]  || [ "$ans" = "y" ]
      then
        /opt/se6x20/bin/restart_se6000
      fi
    else
      myecho "$INVALID_VALUE"
    fi
  done

  # 
  # Only call this if we configured 
  # successfully. Do not test the network in the case
  # of a failure or unconfigure
  #
  if [ $rc -eq 0 -a "$storEdgeId" != "-1" -a $restore_flag -eq 0 ]
  then
    testNetwork 
    value1=$?
    if [ $value1 -eq 0 ]
    then
      myecho "\n$(basename $0) $SUCCESS\n\n\n"
      allDone=1
    else
      myecho "\n$(basename $0) $FAILURE.\n"
      myprintf "$TRY_AGAIN"
      ans=$(myread ans)
      if [ "$ans" != "Y" ]  && [ "$ans" != "y" ]
      then
        allDone=1
      fi
    fi
  else
    allDone=1
  fi
done

if [ $restore_flag -eq 1 ]; then
  if [ $rc -eq 0 ]; then
    echo "Configuration restored from flash - rebooting"
    reboot
  else
    echo "Configuration Restore Error"
    exit $rc
  fi
fi
exit 0
