#!/bin/sh

# 
# @HP_COPYRIGHT@
#
# HISTORY
# $NOHISTORY:$
# $EndNOHISTORY$
# 
# @(#)$RCSfile: InstallSC,v $ $Revision: 1.42 $ (HP) $Date: 2003/10/21 23:12:51 $
# 
# Load SRA kit and then restart using expect to complete the work \
PATH=/usr/sra/bin:/usr/sbin:$PATH ; \
export PATH ; \
cd `dirname $0` ; \
echo " $* " | grep ' -install ' > /dev/null ; \
if [ $? -eq 0 ] ; then \
   MSARGS=0 ; \
   for ARG in $@ ; do \
      if [ $ARG = "-ms" -o $ARG = "-noms" ] ; then \
         MSARGS=`expr $MSARGS + 1` ; \
      fi ; \
   done ; \
   if [ $MSARGS -eq 0 ] ; then \
      echo "Usage: InstallSC -install {-ms | -noms} [-notcr]" ; \
      echo "       InstallSC {-remove | -list} [-ms | -noms] [-notcr]" ; \
      echo "" ; \
      echo "Use -install to install subsets, -remove to remove existing" ; \
      echo "subsets, or -list to list those subsets which should be installed" ; \
      echo "on this machine. Use -ms when run on a management server, or" ; \
      echo "-noms when run on a cluster member. Use -notcr to specify that" ; \
      echo "TruCluster subsets should not be installed, removed or listed." ; \
      exit 1 ; \
   fi ; \
   /usr/sbin/clu_get_info 2> /dev/null | grep DOWN > /dev/null ; \
   if [ $? -eq 0 ] ; then \
      echo "Some cluster members are down. Please boot them and re-run ${0}." ; \
      exit 1 ; \
   fi ; \
   echo "\nUsing SC kit located in `pwd`" ; \
   LOGDIR="/var/sra/adm/log/InstallSC/`/sbin/hostname -s`" ; \
   echo "\nInstallSC logs will be written to ${LOGDIR}" ; \
   HASHES="##############################################################" ; \
   if [ ! -d $LOGDIR ] ; then \
      /bin/mkdir -p ${LOGDIR} ; \
      /bin/chmod 755 ${LOGDIR} ${LOGDIR}/.. ; \
   fi ; \
   TEMPSTR="Z`/sbin/find /usr/.smdb. -name 'SRATCL*.lk'`" ; \
   if [ $TEMPSTR = "Z" ] ; then \
      echo "\nInstalling SRATCL subset" ; \
      KIT="`find . -name SRATCL`" ; \
      [ -z "$KIT" ] && echo "SRATCL kit could not be found!" && exit 1 ; \
      KITS="`cd $KIT/instctrl > /dev/null ; ls *.ctrl | cut -d '.' -f 1 | sort -u`" ; \
      LOGFILE="${LOGDIR}/SRATCL.log" ; \
      echo $HASHES >> ${LOGFILE} ; \
      echo "[`date` install start]\nsetld -l $KIT $KITS" >> ${LOGFILE} ; \
      /usr/sbin/setld -l $KIT $KITS >> ${LOGFILE} 2>&1 ; \
      [ $? -ne 0 ] && echo "Installation of SRATCL kit failed!" && \
               echo "Installation of SRATCL kit failed!\n[`date` finish]\n" >> ${LOGFILE} && \
               exit 1 ; \
      echo "[`date` finish]\n" >> ${LOGFILE} ; \
   else \
      echo "\nSubset SRATCL is already installed, skipping" ; \
   fi ; \
   TEMPSTR="Z`/sbin/find /usr/.smdb. -name 'SRABASE*.lk'`" ; \
   if [ $TEMPSTR = "Z" ] ; then \
      echo "\nInstalling SRABASE subset" ; \
      KIT="`find . -name SRA`" ; \
      [ -z "$KIT" ] && echo "SRA kit could not be found!" && exit 1 ; \
      KITS="`cd $KIT/instctrl > /dev/null ; ls SRABASE*.ctrl | cut -d '.' -f 1 | sort -u`" ; \
      LOGFILE="${LOGDIR}/SRA.log" ; \
      echo $HASHES >> ${LOGFILE} ; \
      echo "[`date` install start]\nsetld -l $KIT $KITS" >> ${LOGFILE} ; \
      /usr/sbin/setld -l $KIT $KITS >> ${LOGFILE} 2>&1 ; \
      [ $? -ne 0 ] && echo "Installation of SRABASE kit failed!" && \
               echo "Installation of SRABASE kit failed!\n[`date` finish]\n" >> ${LOGFILE} && \
               exit 1 ; \
      echo "[`date` finish]\n" >> ${LOGFILE} ; \
   else \
      echo "\nSubset SRABASE is already installed, skipping" ; \
   fi ; \
fi ; \
[ ! -f /usr/opt/sratcl/bin/expect ] && echo "SRA is not installed!\nIf this is an install, specify -install" && exit 0 ; \
exec /bin/expect -f "./`basename $0`" -- "$@"

proc prompt_shell {} {
   return "(%|\\>|#|\\$) $"
}

proc load_sra {} {
   #global newsra_flag
   #set newsra_flag 1
   package require sra
   package require sradb
   log_user 0
}

proc Exit {status code reason} {
   set subsetgroup [getsubsetgroupname $reason]
   logmessage $subsetgroup "$reason"
   logmessage $subsetgroup "\[[timestamp -format "%a %b %d %X %Z %Y"]\
              finish\]\n"
   puts "$reason"
   exit $code
}

proc createlogdir {dir} {
   if [catch {exec /bin/mkdir -p $dir} err] {
      return 0
   }
   # chmod the InstallSC/machinename dir, and the InstallSC dir itself
   if [catch {exec /bin/chmod 755 $dir $dir/..} err] {
      return 0
   }
  
   return 1
}

proc logmessage {subsetgroup message} {
   # getsubsetgroupname returns UNKNOWN if it can't figure out the subsetgroup
   # but we don't want to log to UNKNOWN.log!
   if {$subsetgroup == "UNKNOWN"} {
      return
   }
   set logdir [getlogdir]
   if ![file isdirectory $logdir] {
      return
   }

   set logfile $logdir/${subsetgroup}.log
   catch {exec echo "$message" >> $logfile}
}

proc getkits {msflag notcrflag nosra noupg} {
    DbSystemGet sc_subsets subset_list

    # If this is a management server or they specified to not install/remove tcr, remove tcr from the list
    if {$notcrflag || $msflag} {
       set idx [lsearch $subset_list "TCR*"]
       if {$idx >= 0} {
          set subset_list [lreplace $subset_list $idx $idx]
       }
    }
    # If this is the management server, do not install the PFS bits
    if {$msflag} {
       set idx [lsearch $subset_list "PFS*"]
       if {$idx >= 0} {
          set subset_list [lreplace $subset_list $idx $idx]
       }
    }
    # If this is the management server, do not install the SRATCR bits
    if {$msflag} {
       set idx [lsearch $subset_list "SRATCR*"]
       if {$idx >= 0} {
          set subset_list [lreplace $subset_list $idx $idx]
       }
    }
    # If nosra is set then don't deinstall SRATCL, SRABASE & SRAUPG
    if {$nosra} {
        foreach subset {SRATCL SRABASE SRAUPG} {
            set idx [lsearch $subset_list "${subset}*"]
            if {$idx >= 0} {
               set subset_list [lreplace $subset_list $idx $idx]
            }
        }
    }

    # If noupg is set then don't install/deinstall SRAUPG
    if {$noupg} {
        set subsets_idx 0
        foreach subsets $subset_list {
            set idx [lsearch $subsets "SRAUPG*"]
            if {$idx >= 0} {
                # Remove subset from $subsets
                set new_subsets [lreplace $subsets $idx $idx]
                # Update subset_list
                set subset_list [lreplace $subset_list $subsets_idx $subsets_idx $new_subsets]
            }
            incr subsets_idx
        }
    }

    return $subset_list
}

proc listsckits {kitdir msflag notcrflag nosra noupg} {
    set subset_list [getkits $msflag $notcrflag $nosra $noupg]
    foreach subsets $subset_list {
        foreach subset $subsets {
           # If this is the management server, do not list the SCFSBIN bits
           if {[regexp -nocase "SCFSBIN" $subset] && $msflag} {
              set SkippingThisKit 1
           } else {
              puts "${subset}"
           }
        }
    }
}

# this used to be part of sra setup but fits better here.
proc copyElanDiagsToRis { noris } {

  if { $noris == 0 } {
    puts ""

    #
    # Patch RIS database for Elan diagnostics (sra elancheck command)
    # Only do this if this system had JOIND set to 'yes'
    #
    set pwd [pwd]

      # /usr/opt/elan and /usr/opt/sra were just created by subset install
      cd /usr/opt
      if {[catch {set elandirs [lsort -dictionary [glob elan]]} msg]} {
          puts "Error - could not update RIS database for Elan diagnostics"
          puts "        Is Elan installed?"
          puts "        If not the sra elancheck command will not work."
      } else {
          set elandir [lindex $elandirs end]
          if {[catch {set sradirs [lsort -dictionary [glob sra]]} msg]} {
              puts "Info - could not update RIS database for Elan diagnostics"
              puts "Is SRA installed?"
          } else {
              set sradir [lindex $sradirs end]
              if {![elancheck_patch_ris $elandir $sradir]} {
                  puts "Error - could not update RIS database Elan diagnostics."
                  puts "        As a consequence the sra elancheck command will"
                  puts "        not work."
              } else {
                  puts "Copied Elan Diagnostics to RIS area."
              }
          }
      }
      cd $pwd
  }
}

#
# Copy createdisklabel to the RIS area
#
proc copyCreateDiskLabelToRis {} {
    set ver [lindex [Default_OS] 0]
    set rev [lindex [Default_OS] 1]

    if {[find_ris "Tru64(.*)Rev ${rev}(.*)" risarea risprod]} {
        # Unconditionally copy createdisklabel to the RIS area
        set src "/usr/sra/bin/createdisklabel"
        set dest "/var/adm/ris/$risarea/$risprod/isl"
        if {[catch {exec cp -p $src $dest} msg]} {
            puts "Error - could not copy $src to $dest"
            return 0
        }
        if {[catch {exec chmod 755 $dest/createdisklabel} msg]} {
            puts "Error - could not chmod $dest/createdisklabel"
            return 0
        }
    } else {
        puts "Error - could not locate Tru64 UNIX in RIS database"
    }
}

# this proc would be written to dynamically figure out what subset group
# corresponds to what subsets - except that when uninstalling, we're not
# guaranteed to know where the kits directory structure is.
proc getsubsetgroupname {subset} {
    switch -regexp $subset {
        "ELNMOD" {
            return Elan
        }
        "JTGMOD" {
            return JTG
        }
        "SRAMPI" {
            return MPI
        }
        "PFSMOD" {
            return PFS
        }
        "PPM" {
            return Performance_Visualizer
        }
        "QSWNETDIAGS" {
            return QSWDIAGS
        }
        "RMS" {
            # this will match any of the six RMS subsets
            return RMS
        }
        "SWMSUP" {
            return SWM
        }
        "SCFS" {
            return SCFS
        }
        "SRABASE" -
        "SRAUPG" {
            return SRA
        }
        "SRACFENGINE" {
            return SRACFENGINE
        }
        "SRAGXEXEC" {
            return SRAGXEXEC
        }
        "SRAOSFPATCH" -
        "SRASCRUNLVL" -
        "SRATCRBASE" {
            return SRAOS
        }
        "SRATCL" {
            return SRATCL
        }
        "SRASYSMAN" {
            return Sysman
        }
        "TCRBASE" -
        "TCRMAN" -
        "TCRMIGRATE" {
            return TruCluster
        }
        default {
            return "UNKNOWN"
        }
    }
}

proc getlogdir {} {
    set host [lindex [split [info hostname] .] 0]
    set logdir "/var/sra/adm/log/InstallSC/$host"
    return $logdir
}

proc installsc {kitdir msflag notcrflag nosra suflag noris noupg} {

    if {$suflag == 0} {
       spawn /bin/sh
    }

    puts "\nInstalling AlphaServer SC software"

    set subset_list [getkits $msflag $notcrflag $nosra $noupg]

    set hashes "##############################################################"
    set subset_count [llength $subset_list]
    if {$subset_count == "0"} {
        puts "No-Subsets to install"
        Exit failed 10 "Error - No-Subsets to install"
    }

    set logdir [getlogdir]
    if ![file isdirectory $logdir] {
        if ![createlogdir $logdir] {
            puts "Failed to create log directory"
            Exit failed 10 "Error - failed to create log directory"
        }
    }

    set timeout 300

    foreach subsets $subset_list {
        set logdir [getlogdir]
        set subsetgroup [getsubsetgroupname $subsets]
        set logfile $logdir/${subsetgroup}.log
        logmessage $subsetgroup $hashes
        logmessage $subsetgroup\
                   "\[[timestamp -format "%a %b %d %X %Z %Y"] install start\]"
        log_file -a $logfile

        # If this is the management server, do not install the SCFSBIN,
        # SRATCRBASE280 & SRASCRUNLVL280
        if {$msflag} {
           foreach excludeSubset {SCFSBIN* SRATCRBASE* SRASCRUNLVL*} {
               set idx [lsearch $subsets $excludeSubset]
               if {$idx >= 0} {
                  set subsets [lreplace $subsets $idx $idx]
               }
            }
        }
        # Check if subset already installed
        set install 0
        foreach subset $subsets {
            set installed [exec /sbin/find /usr/.smdb. -name ${subset}.lk]
            if { $installed == "/usr/.smdb./${subset}.lk" } {
                # Dont complain about sets we installed during the shell script portion
                if {[regexp -nocase "SRATCL" $subset] == 0 && [regexp -nocase "SRABASE" $subset] == 0} {
                   puts "Subset $subset is already installed, skipping"
                }
                # but do log the fact.
                logmessage $subsetgroup "Subset $subset is already installed, skipping"
                set idx [lsearch $subsets $subset]
                if {$idx >= 0} {
                   set subsets [lreplace $subsets $idx $idx]
                }
            } else {
                set install 1
            }
        }
        set subsetgroup [getsubsetgroupname $subset]
        if { $install } {
            puts "\nAttempting to install subsets: $subsets"
            # Find subset in sckit directory
            set subsetdir [exec /sbin/find $kitdir -name $subset]
            if {$subsetdir == ""} {
                puts "Unable to find subset directory for $subset"
                logmessage $subsetgroup \
                     "Unable to find subset directory for $subset"
            } elseif {$suflag == 0} {
                set dir [string trimright $subsetdir $subset]
                puts "$subsets now installing"

                logmessage $subsetgroup "/usr/sbin/setld -l $dir $subsets"
                send "/usr/sbin/setld -l $dir $subsets\r"

                expect_after eof {
                    puts "Failed installing $subsets"
                    Exit failed 10 "Failed installing $subsets"
                }

                set choices 0
                set timeout_count 0
                expect {
                    -re "Error(.*)\n" {
                        puts "Error$expect_out(1,string)"
                        Exit failed 10 "Failed installing $subsets"
                    }
                    "Installation declined by subset control program " {
                        puts "Failed installing $subsets"
		        Exit failed 10 "Failed installing $subsets"
                    }
                    "There were verification errors for" {
                        puts "Failed installing $subsets"
                        Exit failed 10 "Failed installing $subsets"
                    }
                    "QSW Elan Product Configuration Menu" {
                        set timeout 300
                        expect {
                            "Type the number for your choice" {
                                send "1\r"
                                exp_continue
                            }
                            "Enter a name for the kernel configuration" {
                                send "\r"
                                exp_continue
                            }
                            "Do you want to replace it" {
                                send "y\r"
                                exp_continue
                            }
                            "Enter your choices or press" {
                                send "\r"
                                exp_continue
                            }
                            "Enter your choices\." {
                                expect "Choices" {
                                    DbSystemGet kernel_comp kernel_comp
                                    send "$kernel_comp\r"
                                }
                                exp_continue
                            }
                            "Is that correct" {
                                send "y\r"
                                exp_continue
                            }
                            "Do you want to edit the configuration" {
                                send "n\r"
                            }
                        }
                        exp_continue
                    }
                    -re "Configuring .* on member" {
                        set timeout 180
                        exp_continue
                    }
                    "Working...." {
                        set timeout 180
                        exp_continue
                    }
                    -re [prompt_shell] { }
                    timeout {
                        incr timeout_count
                        if { $timeout_count < 5 } {
                            puts "Working....[clock format [clock seconds] -format "%a %b %d %T %Z %Y"]"
                            #puts "Timeout, send cr and wait some more"
                            send "\r"
                            set timeout 300
                            exp_continue
                        } else {
                            puts "Timeout installing $subsets"
                            Exit failed 10 "Install-Fail"
                        }
                    }
                }
            } else {
                set dir [string trimright $subsetdir $subset]
                puts "$subsets now installing"

                logmessage $subsetgroup "/usr/sbin/setld -l $dir $subsets"

                catch {exec /usr/sbin/setld -l $dir $subsets} result
            }
        }
        #
        # Make sure all the subsets installed correctly
        #
        foreach subset $subsets {
            set installed [exec /sbin/find /usr/.smdb. -name ${subset}.lk]
            if { $installed != "/usr/.smdb./${subset}.lk" } {
                puts "Subset $subset did not install correctly"
                Exit failed 10 "Install-Fail $subset failed to install correctly"
            }
        }
        # turn logging off
        log_file
        # if we haven't just exited, we can write a closing message
        # to the log for this subset group.
        logmessage $subsetgroup\
                  "\[[timestamp -format "%a %b %d %X %Z %Y"] finish\]\n"       
    }

    #
    # Post Install Tasks
    #

    # copy elan diagnostics to ris area
    copyElanDiagsToRis $noris

    # copy createdisklabel script to ris area
    copyCreateDiskLabelToRis

    # The dop -s -W command is necessary to bring the TruCluster CAA components
    # to life under sysman.

    if {[catch {exec /usr/sbin/dop -s -W} err]} {
        puts "Error running dop:"
        puts "$err"
    }

    # Start the srad daemon, only do this if not at single user
    if {$suflag == 0} {
        if {[file exists "/sbin/init.d/sra"]} {
            puts ""
            puts "Starting srad"
            if {[catch {exec /sbin/init.d/sra start} err]} {
                puts "Error starting srad: $err"
            }
        }
    }

    puts "\nInstallation Complete"

}

proc deinstallsc {msflag notcrflag nosra suflag noupg} {

    if {$suflag == 0} {
       spawn /bin/sh
    }

    set hashes "##############################################################"

    puts "\nDe-Installing AlphaServer SC software"


    # if we are in a cluster stop any caa amaged applications befor 
    # we deinstall them
    
    set in_cluster 1
    if [ catch { set clu_info [exec clu_get_info -raw] } err ] {
	set in_cluster 0 
    }
    if {$in_cluster && [file exists /usr/bin/caa_stat]} {

        if { [catch {exec /usr/bin/caa_stat -q  SC10cmf}] == 0} {
	    if { [catch {exec /usr/sbin/caa_stop -f -q SC10cmf}] != 0} {
		puts "caa_stop SC15srad failed. Please stop manually"
		Exit failed 10 "Error - caa_stop SC10cmf failed"
	    }
	}
        if { [catch {exec /usr/bin/caa_stat -q SC15srad}] == 0} {
	    if { [catch {exec /usr/sbin/caa_stop -f -q SC15srad}] != 0} {
		puts "caa_stop SC15srad failed. Please stop manually"
		Exit failed 10 "Error - caa_stop SC15srad failed"
	    }
	}
        if { [catch {exec /usr/bin/caa_stat -q SC25scalertd}] == 0} {
	    if { [catch {exec /usr/sbin/caa_stop -f -q SC25scalertd}] != 0} {
		puts "caa_stop SC15srad failed. Please stop manually"
		Exit failed 10 "Error - caa_stop SC25scalertd failed"
	    }
	}
    }


    set subset_list_db [getkits $msflag $notcrflag $nosra $noupg]

    set subset_count [llength $subset_list_db]

    if {$subset_count == "0"} {
        puts "No-Subsets to install"
        Exit failed 10 "Error - No-Subsets to install"
    }

    # 
    # RMSLSFSUPxxx is not in the list in some upgrade situations, so manually
    # add it to the list if it's not there (the number isn't important, as it's
    # stripped out anyway, but there has to be one to match the regexp) 
    #
    set rmslsfsup_list [exec /sbin/find /usr/.smdb. -name "RMSLSFSUP*.lk"]
    if {[string length $rmslsfsup_list] > 0} {
        set newsubsets ""
        foreach group $subset_list_db {
            if {[lsearch -re $group "RMS"] > -1} {
                if {[lsearch -re $group "RMSLSFUP"] == -1} {
                    lappend newsubsets [lappend group "RMSLSFSUP290"]
                } else {
                    lappend newsubsets $group
                }
            } else {
                lappend newsubsets $group
            }
            set subset_list_db $newsubsets
        }
    }

    set logdir [getlogdir]
    if ![file isdirectory $logdir] {
        if ![createlogdir $logdir] {
            puts "Failed to create log directory"
            Exit failed 10 "Error - failed to create log directory"
        }
    }

    #
    # Deinstall in reverse order
    #
    # some subsets don't report *anything* when deleting from cluster members,
    # so need very long timeouts. however timeout * 32 would be a bit much.
    # choosing timeouts is not an exact science.
    set timeout [expr 300 * 16]

    incr subset_count -1
    for {set index $subset_count} {$index >= 0} {incr index -1} {
        set subsets [lindex $subset_list_db $index]
        puts "\nAttempting to deinstall subsets: $subsets"
        set logdir [getlogdir]
        set subsetgroup [getsubsetgroupname $subsets]
        set logfile $logdir/${subsetgroup}.log
        logmessage $subsetgroup $hashes
        logmessage $subsetgroup\
                 "\[[timestamp -format "%a %b %d %X %Z %Y"] deinstall start\]"
        log_file -a $logfile

        # Check if subset is installed
        set subset_list {}
        set deinstall 0
        foreach subset $subsets {
            #
            # Don't assume the subset name will be XXXYYY200, assume it is
            # XXXYYYNNN! i.e. don't assume the subset version number
            #

            # trim off the version number
            regsub {([a-zA-Z]+)([0-9]+)} $subset {\1} subs

            set subset_file_list \
                      [exec /sbin/find /usr/.smdb. -name "${subs}*.lk"]

            if { [string length $subset_file_list] == 0} { 
                puts "Subset $subset is not installed, skipping"
                logmessage $subsetgroup "Subset $subset is not installed, skipping"
            } else {
                # possible that multiple copies (with different revision
                # numbers) are installed - so delete all.
                foreach subset_file $subset_file_list {
                    # Remove path from filename
                    set sub_file [lindex [split $subset_file "/"] end]
                    # Remove .lk to determine subset name
                    set subset_name [lindex [split $sub_file "."] 0]

                    lappend subset_list $subset_name
                    set deinstall 1
                }
            }
        }
        if { $deinstall } {
          puts "De-Installing $subset_list"
          set subsetgroup [getsubsetgroupname [lindex $subset_list 0]]
          
          if {$suflag == 0} {

            logmessage $subsetgroup "/usr/sbin/setld -d $subset_list"
            send "/usr/sbin/setld -d $subset_list\r"

            expect_after eof {
                puts "Failed de-installing $subsets"
                Exit failed 10 "Failed de-installing $subsets"
            }

            set timeout_count 0
            expect {
                -re "Error(.*)\n" {
                    puts "Error$expect_out(1,string)"
                    Exit failed 10 "Failed deinstalling $subsets"
                }
                "QSW Elan Product Configuration Menu" {
                    set timeout [expr 300 * 16]
                    expect {
                        "Type the number for your choice" {
                            send "1\r"
                            exp_continue
                        }
                        "Enter a name for the kernel configuration" {
                            send "\r"
                            exp_continue
                        }
                        "Do you want to replace it" {
                            send "y\r"
                            exp_continue
                        }
                        "Enter your choices or press" {
                            send "\r"
                            exp_continue
                        }
                        "Enter your choices\." {
                            expect "Choices" {
                                DbSystemGet kernel_comp kernel_comp
                                send "$kernel_comp\r"
                            }
                            exp_continue
                        }
                        "Is that correct" {
                            send "y\r"
                            exp_continue
                        }
                        "Do you want to edit the configuration" {
                            send "n\r"
                        }
                    }
                    exp_continue
                }
                -re "The following subsets need" {
                    expect -re "Are you sure.*" {
                        send "y\r"
                    }
                    exp_continue
                }
                -re "setld: (.*) scp failed on member(\[0-9\]+)" {
                    logmessage $subsetgroup "$expect_out(1,string) scp failed on member $expect_out(2,string)"
                    exp_continue
                }
                -re "Deleting (.*) on member" {
                    # if we do get a report from another member can use short
                    # timeout
                    set timeout 180
                    exp_continue
                }
                -re "Done\." {
                    # this message appears for each member for some subsets.
                    # again, can use short timeout.
                    set timeout 180
                    exp_continue
                }
                -re [prompt_shell] { }
                timeout {
                    incr timeout_count
                    if { $timeout_count < 5 } {
                        puts "Working....[clock format [clock seconds] -format "%a %b %d %T %Z %Y"]"
                        #puts "Timeout, send cr and wait some more"
                        send "\r"
                        set timeout 300
                        exp_continue
                    } else {
                        puts "Timeout de-installing $subsets"
                        Exit failed 10 "DE-Install-Fail de-installing $subsets"
                    }
                }
            }
          } else {
            logmessage $subsetgroup "/usr/sbin/setld -f -d $subset_list"
            # In order to handle questions from setld pipe multiple 'yes' to 
            # setld
            catch {exec /usr/bin/yes | head -100 | /usr/sbin/setld -f -d $subset_list} result
          }
        }
        logmessage $subsetgroup\
                   "\[[timestamp -format "%a %b %d %X %Z %Y"] finish\]\n"
        # turn logging off again.
        log_file
    }
    puts "\nDe-Installed"
}

proc ShowUsage {} {
   puts "Usage: InstallSC -install {-ms | -noms} \[-notcr\]"
   puts "       InstallSC {-remove | -list} \[-ms | -noms\] \[-notcr\]"
   puts ""
   puts "Use -install to install subsets, -remove to remove existing"
   puts "subsets, or -list to list those subsets which should be installed"
   puts "on this machine. Use -ms when run on a management server, or"
   puts "-noms when run on a cluster member. Use -notcr to specify that"
   puts "TruCluster subsets should not be installed, removed or listed."
   exit 1
}

set msflag "undefined"
set notcrflag 0
set nosra 0
set noupg 0
set noris 0
set installflag 0
set removeflag 0
set listflag 0
set suflag 0
set kitdir [pwd]
load_sra

for {set i 0} {$i < [llength $argv]} {incr i 1} {
   switch -exact -- [lindex $argv $i] {
      -ms {set msflag 1
           set notcrflag 1}
      -noms {set msflag 0}
      -noris {set noris 1}
      -notcr {set notcrflag 1}
      -nosra {set nosra 1}
      -noupg {set noupg 1}
      -install {set installflag 1}
      -remove {set removeflag 1}
      -list {set listflag 1}
      -singleuser {set suflag 1}
      # InstallSC with no args produces one empty arg {} to the tcl section
      {} {}
      default { puts "invalid argument! [lindex $argv $i]" ; ShowUsage ; exit 1 }
   }
}
if {$msflag == "undefined"} {
   if {$installflag} {
      ShowUsage
   } else {
      set msflag 0
   }
}

if {$installflag && $removeflag} {
   ShowUsage
} elseif { $installflag } {
   puts "\nAlphaServer SC software installation utility"
   installsc $kitdir $msflag $notcrflag $nosra $suflag $noris $noupg
} elseif {$removeflag} {
   if [catch {set oput [exec /usr/sbin/clu_get_info]} err] {
       if [regexp "System not configured to be in a cluster" $err] {    
            # system not in a cluster => ok
       } else {
            puts "\nError running clu_get_info"
            Exit failed 10 "$err"
       }
   } else {
       # clu_get_info ran successfully, but what did it output?
       if [regexp DOWN $oput] {
           puts "Some cluster members are down. Please boot them\
                 and re-run $argv0"
           Exit failed 10 "Cluster not fully booted."
       } else {
            # all members up => ok
       }
   } 

   puts "\nAlphaServer SC software installation utility"
   puts "\nInstallSC logs will be written to [getlogdir]"
   deinstallsc $msflag $notcrflag $nosra $suflag $noupg
} elseif {$listflag} {
   listsckits $kitdir $msflag $notcrflag $nosra $noupg
} else {
   ShowUsage
}

