#!/bin/sh
#
# eccheckenv - check for various environmental issues and warn about them.
#
# Copyright (c) 2005-2026 Electric Cloud, Inc.
# All rights reserved
#
# This comment hides the next line from tclsh -*-Tcl-*- \
exec tclsh "$0" "${@}"

package require cmdline
package require tdom
package require http
package require base64
catch {package require registry}

variable gOptions {};                   # The command line option list
 
# Windows check  
proc check_i686_win32_cygwinVersion {} {
    set status 0
    set title "Checking for cygwin version."
    set description "
  The following machines have an installation of cygwin that is not officially
  supported. There are known issues with older versions of cygwin,
  so it is suggested that you contact Electric Cloud."
    set solution "
  Please contact Electric Cloud and/or upgrade to
  a supported version of cygwin (1.5.18 or later)."
    set links [list http://www.cygwin.com http://www.electric-cloud.com/support support@electric-cloud.com]

    set cmdStatus [registryKeyExists {HKEY_LOCAL_MACHINE\SOFTWARE\Cygnus Solutions\Cygwin}]
    if {$cmdStatus == 1} {
        # There is a cygwin here...
        set cmdResult [runCommand "" "" "exec uname -r"]
        set cmdStatus [lindex $cmdResult 0]
        set result [lindex $cmdResult 1]
        if {$cmdStatus != 0} {
            append description "<br>
  Host: local<br>
  This machine appears to have a cygwin installation but we have
  been unable to locate the uname executable to determine the 
  version. There are known issues with older versions of cygwin."
            set status 1
        } else {
            if {![regexp {(\d+)\.(\d+)\.(\d+)} $result ignore major minor subminor]} {
                set description "<br>
  Host: local<br>
  This machine appears to have a cygwin installation but we have
  been unable to parse the version string returned by uname -r to
  determine the cygwin version. There are known issues with older
  versions of cygwin.<br>
  Found version string: [fixHtml $result]."
                set status 1
            } else {
                if {!(($major > 1) ||
                      ($major == 1 && $minor > 5) ||
                      ($major == 1 && $minor == 5 && $subminor >= 18))} {
                    append description "<br>
  Host: local<br>
  &nbsp;&nbsp; cygwin $major.$minor.$subminor"
                    set status 1
                }
            }
        }
    }

    if {"$::gConfig(cm)" != ""} {
        set agentList [getAgentUniqueList]
        if {[lindex $agentList 0] != 0} {
            print "Unable to connect to cluster manager."
            return [list $status $title $description $solution $links]
        }

        # Run the test
        print $title 1
        foreach {host ip port} [lindex $agentList 1] {
            set cmdStatus [registryKeyExists {HKEY_LOCAL_MACHINE\SOFTWARE\Cygnus Solutions\Cygwin} $ip $port]
            if {$cmdStatus == 0} {
                set cmdResult [runCommand $ip $port "exec uname -r"]
                set cmdStatus [lindex $cmdResult 0]
                set result [lindex $cmdResult 1]
                if {$cmdStatus == 0} {
                    if {![regexp {(\d+)\.(\d+)\.(\d+)} $result ignore major minor subminor]} {
                        set description "<br>
  &nbsp;&nbsp;Host: $host ($ip):<br>
  This machine appears to have a cygwin installation but we have
  been unable to parse the version string returned by uname -r to
  determine the cygwin version. There are known issues with older
  versions of cygwin.<br>
  Found version string: [fixHtml $result]."
                        set status 1
                    } else {
                        if {!(($major > 1) ||
                              ($major == 1 && $minor > 5) ||
                              ($major == 1 && $minor == 5 &&
                               $subminor >= 18))} {
                            append description "<br>
  &nbsp;&nbsp;Host: $host ($ip): cygwin $major.$minor.$subminor"
                            set status 1
                        }
                    }
                }
            }
        }
    }

    # Return the result
    return [list $status $title $description $solution $links]
}

proc check_i686_win32_nmakeVersion {} {
    set status 0
    set title "Checking for nmake version."
    set description "
  This machine has a version of nmake that is not officially supported."
    set solution "
  Please contact Electric Cloud."
    set links [list http://www.electric-cloud.com/support support@electric-cloud.com]

    # Find the executables.
    set nmakePath ""
    set pathSep ";"
    set exeExt ".exe"
    foreach path [split $::env(PATH) $pathSep] {
        if {$nmakePath == "" &&
            [file exists [file join $path nmake$exeExt]]} {
            set nmakePath [file join $path nmake$exeExt]
        }
    }

    if {$::gConfig(faillevel) == 2} {
        # Make sure we have easily testable test data
        set nmakePath nmake
    }

    # Run the test
    print $title 1
    set cmdResult [runCommand "" "" "exec nmake /help"]
    set cmdStatus [lindex $cmdResult 0]
    set result [lindex $cmdResult 1]
    if {$cmdStatus == 0} {
        if {![regexp {Version (\d+)\.(\d+)\.(\d+)} $result ignore major minor subminor]} {
            set description "
  This machine appears to have a nmake installation but we have
  been unable to determine the version. There are known issues 
  with older versions of nmake.<br>
  Found nmake help output:<br>
<pre>[fixHtml $result]</pre>"
            set status 1
        } else {
            set description "
  Found nmake executable: $nmakePath"
            if {!(($major > 7) ||
                  ($major == 7 && $minor > 0) ||
                  ($major == 7 && $minor == 0 && $subminor >= 9955))} {
                append description "<br>
  This machine has a version of nmake that is not officially supported.<br>
  Version: $major.$minor.$subminor"
                set status 1
            } else {
                append description "<br>
  Version: $major.$minor.$subminor<br>
  Emake flags:<br>
  --emake-emulation-table=nmake=nmake"
                set status 2
            }
        }
    }

    # Return the result
    return [list $status $title $description $solution $links]
}

proc check_i686_win32_VSVersion {} {
    set status 0
    set title "Checking for Visual Studio."
    set description "
  This machine has an installation of Visual Studio. There are known
  issues when using Visual Studio with emake. Please contact Electric Cloud."
    set links [list http://www.electric-cloud.com/support support@electric-cloud.com]

    # Run the test
    print $title 1
    set cmdStatus1 [registryKeyExists {HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio?\7.0\VC\VC_OBJECTS_PLATFORM_INFO\Win32\Directories\Path Dirs}]
    set cmdStatus2 [registryKeyExists {HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio?\7.1\VC\VC_OBJECTS_PLATFORM_INFO\Win32\Directories\Path Dirs}]
    if {$cmdStatus1 == 1 || $cmdStatus2 == 1} {
        set status 2
    }

    # Return the result
    return [list $status $title $description "" $links]
}

proc check_i686_win32_ephemeral {} {
    if {"$::gConfig(cm)" == ""} {
        return [list 1000]
    }
    set agentList [getAgentUniqueList]
    if {[lindex $agentList 0] != 0} {
        print "Unable to connect to cluster manager."
        return [list 1000]
    }

    set status 0
    set title "Checking for ephemeral port number on agents."
    set description "
  The following machines have an ephemeral setting that is potentially
  too small. This may mean that the agent is not able to open sockets
  quickly enough in large enough quantities. We recommend a value of 60000."
    set solution "
  Please contact Electric Cloud. You can set the registry
  key HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\MaxUserPort."
    set links [list http://www.electric-cloud.com/support support@electric-cloud.com]

    # Run the test
    print $title 1
    foreach {host ip port} [lindex $agentList 1] {
        set cmdResult [getRegistryKey {HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters} MaxUserPort $ip $port]
        set cmdStatus [lindex $cmdResult 0]
        set result [lindex $cmdResult 1]
        if {$cmdStatus == 0} {
            if {$result < 60000} {
                append description "<br>
  Host: $host ($ip): ephemeral value = $result"
                set status 1
            }
        }
    }

    # Return the result
    return [list $status $title $description $solution $links]
}

proc check_i686_win32_virusScanners {} {
    if {"$::gConfig(cm)" == ""} {
        return [list 1000]
    }
    set agentList [getAgentUniqueList]
    if {[lindex $agentList 0] != 0} {
        print "Unable to connect to cluster manager."
        return [list 1000]
    }

    set status 0
    set title "Checking for virus scanners on agents."
    set description "
  The following machines have a visrus scanner installed. This may
  potentially interfere with the Agent operation."
    set solution "
  Please contact Electric Cloud."
    set links [list http://www.electric-cloud.com/support support@electric-cloud.com]

    # Run the test
    print $title 1
    foreach {host ip port} [lindex $agentList 1] {
        set cmdStatus [registryKeyExists {HKEY_LOCAL_MACHINE\\SOFTWARE\\TrendMicro} $ip $port]
        if {$cmdStatus == 1} {
            append description "<br>
  Host: $host ($ip): Has TrendMicro(c) installed"
            set status 1
        }
        set cmdStatus [registryKeyExists {HKEY_LOCAL_MACHINE\\SOFTWARE\\Symantec\\Norton AntiVirus} $ip $port]
        if {$cmdStatus == 1} {
            append description "<br>
  Host: $host ($ip): Has Norton AntiVirus(c) installed"
            set status 1
        }
        set cmdStatus [registryKeyExists {HKEY_LOCAL_MACHINE\\SOFTWARE\\Network Associates\\VirusScan} $ip $port]
        if {$cmdStatus == 1} {
            append description "<br>
  Host: $host ($ip): Has McAfee Virus Scan(c) installed"
            set status 1
        }
    }

    # Return the result
    return [list $status $title $description $solution $links]
}


# Solaris checks
proc check_sun4u_SunOS_SunCC {} {
    set status 0
    set title "Checking for Sun Forte compiler."
    set description "
  This machine has a version of Sun's CC compiler installed. There
  are known issues with this version of the compiler."
    set solution "
  Please contact Electric Cloud."
    set links [list http://www.electric-cloud.com/support support@electric-cloud.com]

    # Run the test
    print $title 1
    set cmdResult [runCommand "" "" "exec CC -V"]
    set cmdStatus [lindex $cmdResult 0]
    set result [lindex $cmdResult 1]
    if {$cmdStatus == 0} {
        if {[regexp {Forte} $result]} {
            append description "<br>
Output:<br>
<pre>[fixHtml $result]</pre>"
            set status 1
        }
    }

    # Return the result
    return [list $status $title $description $solution $links]
}

# Linux checks


# Generic tests
proc check_all_info {} {
    set status 2
    set title "Showing machine information for cluster."
    set description "
  The following machines exist in the cluster:"
    set solution ""
    set links [list ]

    # Run the test
    print $title 1
    append description "<br>
  Host: local<br>"
    set result [get_$::gConfig(arch)_osString]
    if {[lindex $result 0] == 1} {
        append description "
  Unable to determine the OS version.<br>
  Output:<br>
  <pre>[fixHtml [lindex $result 1]]</pre>"
        set status 1
    } else {
        append description "
  &nbsp;&nbsp;OS: [lindex $result 1]<br>"
    }
    set result [get_$::gConfig(arch)_processors]
    if {[lindex $result 0] == 1} {
        append description "
  Unable to determine processor list.<br>
  Output:<br>
  <pre>[fixHtml [lindex $result 1]]</pre>"
        set status 1
    } else {
        # Go through the processors
        foreach processor [lindex $result 1] {
            append description "<br>
  &nbsp;&nbsp;Processor: $processor"
        }
    }

    if {"$::gConfig(cm)" != ""} {
        set agentList [getAgentUniqueList]
        if {[lindex $agentList 0] != 0} {
            print "Unable to connect to cluster manager."
            return [list $status $title $description $solution $links]
        }

        foreach {host ip port} [lindex $agentList 1] {
            append description "<br>
  Host: $host ($ip)<br>"
            set result [get_$::gConfig(arch)_osString $ip $port]
            if {[lindex $result 0] == 1} {
                append description "
  Unable to determine the OS version.<br>
  Output:<br>
  <pre>[fixHtml [lindex $result 1]]</pre>"
                set status 1
            } else {
                append description "
  &nbsp;&nbsp;OS: [lindex $result 1]<br>"
            }
            set result [get_$::gConfig(arch)_processors $ip $port]
            if {[lindex $result 0] == 1} {
                append description "
  Unable to determine processor list.<br>
  Output:<br>
  <pre>[fixHtml [lindex $result 1]]</pre>"
                set status 1
            } else {
                # Go through the processors
                foreach processor [lindex $result 1] {
                    append description "<br>
  &nbsp;&nbsp;Processor: $processor"
                }
            }
        }
    }

    # Return the result
    return [list $status $title $description $solution $links]
}

proc check_all_OS {} {
    set status 0
    set title "Checking for os versions."
    set description "
  The following machines are running an unsupported OS. There are known
  issues with certain versions of the OS."
    set solution "
  Please contact Electric Cloud."
    set links [list http://www.electric-cloud.com/support support@electric-cloud.com]

    # Run the test
    print $title 1
    set mismatched [list ]
    set localOS $::tcl_platform(os)
    set localMachine $::tcl_platform(machine)
    set localOSVersion $::tcl_platform(osVersion)
    set result [get_tclOS]
    set platform [lindex $result 1]
    if {![test_$::gConfig(arch)_tclOS $localOS $localMachine \
              $localOSVersion]} {
        append description "<br>
  Host: local<br>
  &nbsp;&nbsp;Machine: $localMachine<br>
  &nbsp;&nbsp;OS: $localOS<br>
  &nbsp;&nbsp;OS Version: $localOSVersion<br>"
        set status 1
    }
    
    if {"$::gConfig(cm)" != ""} {
        set agentList [getAgentUniqueList]
        if {[lindex $agentList 0] != 0} {
            print "Unable to connect to cluster manager."
            return [list $status $title $description $solution $links]
        }
        
        foreach {host ip port} [lindex $agentList 1] {
            set result [get_tclOS $ip $port]
            set platform [lindex $result 1]
            if {[lindex $result 0] == 1} {
                append description "
  Unable to determine the OS version.<br>
  Output:<br>
  <pre>[fixHtml [lindex $result 1]]</pre>"
                set status 1
            } else {
                if {![test_$::gConfig(arch)_tclOS [lindex $platform 0] \
                          [lindex $platform 1] [lindex $platform 2]]} {
                    append description "<br>
  Host: $host ($ip)<br>
  &nbsp;&nbsp;Machine: [lindex $platform 1]<br>
  &nbsp;&nbsp;OS: [lindex $platform 0]<br>
  &nbsp;&nbsp;OS Version: [lindex $platform 2]"
                    set status 1
                }
                if {"[lindex $platform 0]" != "$localOS" ||
                    "[lindex $platform 1]" != "$localMachine" ||
                    "[lindex $platform 2]" != "$localOSVersion"} {
                    lappend mismatched "<br>
  Host: $host ($ip)<br>
  &nbsp;&nbsp;Machine: [lindex $platform 1]<br>
  &nbsp;&nbsp;OS: [lindex $platform 0]<br>
  &nbsp;&nbsp;OS Version: [lindex $platform 2]"
                }
            }
        }

        # Mismatched OS versions
        if {!$status && [llength $mismatched] > 0} {
            set description "
  Some machines use mismatched (yet supported) OS versions.<br>
  Host: local<br>
  &nbsp;&nbsp;Machine: $localMachine<br>
  &nbsp;&nbsp;OS: $localOS<br>
  &nbsp;&nbsp;OS Version: $localOSVersion"
            foreach host $mismatched {
                append description "$host"
            }
            set status 1
        }
    }

    # Return the result
    return [list $status $title $description $solution $links]
}

proc check_all_memory {} {
    set status 0
    set title "Checking for available memory."
    set description "
  The following machines may not have enough memory. We recommend a minimum of
  2000 MB (2 GB) for an emake build machine and 1000 MB (1 GB) for an
  agent machine, but these machine have:"
    set solution "
  Please contact Electric Cloud."
    set links [list http://www.electric-cloud.com/support support@electric-cloud.com]

    # Run the test
    print $title 1
    append description "<br>
  Host: local: "
    set result [get_$::gConfig(arch)_memory]
    set memory [lindex $result 1]
    if {[lindex $result 0] == 1} {
        append description "<br>
  Unable to determine the available memory. We recommend a minimum
  of 2000 MB (2 GB) for an emake build machine. Please check that
  you have at least that much memory.<br>
  Output:<br>
  <pre>[fixHtml [lindex $result 1]]</pre>"
        set status 1
    } else {
        # We are overflowing our integers (Tcl is not very well prepared for
        # large integers. I have been unable to get the binary scan routine
        # to return a 64 bit value or treat the result as an unsigned).
        if {!($memory >= 2000 || $memory <= 0)} {
            append description "$memory MB."
            set status 1
        }
    }

    if {"$::gConfig(cm)" != ""} {
        set agentList [getAgentUniqueList]
        if {[lindex $agentList 0] != 0} {
            print "1Unable to connect to cluster manager."
            return [list $status $title $description $solution $links]
        }

        foreach {host ip port} [lindex $agentList 1] {
            set result [get_$::gConfig(arch)_memory $ip $port]
            set memory [lindex $result 1]
            if {[lindex $result 0] == 1} {
                append description "<br>
  Host: $host ($ip):<br>
  Unable to to determine the available memory. We recommend a minimum
  of 2000 MB (2 GB) for an emake build machine. Please check that you
  have at least that much memory.<br>
  Output:<br>
  <pre>[fixHtml [lindex $result 1]]</pre>"
                set status 1
            } else {
                if {!($memory >= 1000 || $memory <= 0)} {
                    append description "<br>
  Host: $host ($ip): $memory MB"
                    set status 1
                }
            }
        }
    }

    # Return the result
    return [list $status $title $description $solution $links]
}

proc check_all_diskspace {} {
    set status 0
    set title "Checking for available diskspace."
    set description "
  The current drive may not have enough capacity. We recommend a minimum of
  10 GB for an emake build machine, but this machine has "
    set solution "
  Please contact Electric Cloud."
    set links [list http://www.electric-cloud.com/support support@electric-cloud.com]

    # Run the test
    print $title 1
    set result [get_$::gConfig(arch)_diskspace]
    if {[lindex $result 0] == 1} {
        set description "
  Unable to determine the available disk space. We recommend a
  minimum of 10 GB for an emake build machine. Please check that 
  you have at least that much disk space.<br>
  Output:<br>
  <pre>[fixHtml [lindex $result 1]]</pre>"
        set status 1
    } else {
        set free [lindex $result 1]
        if {!($free >= 10)} {
            append description "$free GB."
            set status 1
        }
    }

    # Return the result
    return [list $status $title $description $solution $links]
}

proc check_all_gmakeVersion {} {
    set status 0
    set title "Checking for make version."
    set description ""
    set solution "
  Please contact Electric Cloud."
    set links [list http://www.electric-cloud.com/support support@electric-cloud.com]

    # Find the executables.
    set gmakePath ""
    set makePath ""
    if {"$::tcl_platform(platform)" == "unix"} {
        set pathSep ":"
        set exeExt ""
    } else {
        set pathSep ";"
        set exeExt ".exe"
    }
    foreach path [split $::env(PATH) $pathSep] {
        if {$gmakePath == "" &&
            [file exists [file join $path gmake$exeExt]]} {
            set gmakePath [file join $path gmake$exeExt]
        }
        if {$makePath == "" &&
            [file exists [file join $path make$exeExt]]} {
            set makePath [file join $path make$exeExt]
        }
    }

    if {$::gConfig(faillevel) == 2} {
        # Make sure we have easily testable test data
        set gmakePath gmake
        set makePath make
    }

    # Run the test
    print $title 1
    set cmdResult [runCommand "" "" "exec gmake --version"]
    set cmdStatus [lindex $cmdResult 0]
    set result [lindex $cmdResult 1]
    if {$cmdStatus == 0} {
        append description "
  Found gmake executable: $gmakePath"
        if {[string match "*Windows32*" $result]} {
            if {[string match "*Symbian*" $result]} {
                append description "<br>
  This machine has Symbian Make installed.<br>
  Emake flags:<br>
    --emake-emulation-table=gmake=symbian"
            } else {
                append description "<br>
  This machine has native Windows GNU Make installed.<br>
  Emake flags:<br>
    --emake-emulation-table=gmake=symbian"
            }
            set status 2
        } elseif {[string match "*GNU Make version 3.79.1*" $result]} {
            append description "<br>
  This machine has GNU Make 3.79.1 installed.<br>
  Emake flags:<br>
    --emake-emulation-table=gmake=gmake"
            set status 2
        } elseif {[string match "*GNU Make 3.80*" $result]} {
            append description "<br>
  This machine has GNU Make 3.80 installed.<br>
  Emake flags:<br>
    --emake-emulation-table=gmake=gmake"
            set status 2
        } elseif {[string match "*GNU Make 3.81*" $result]} {
            append description "<br>
  This machine has GNU Make 3.81 installed.<br>
  Emake flags:<br>
    --emake-emulation-table=gmake=gmake"
            set status 2
        } else {
            append description "<br>
  This machine has an unsupported version of make installed.<br>
  Output:<br>
<pre>[fixHtml $result]</pre>"
            set status 1
        }
        append description "<br>
  <br>"
    }

    set cmdResult [runCommand "" "" "exec make --version"]
    set cmdStatus [lindex $cmdResult 0]
    set result [lindex $cmdResult 1]
    if {$cmdStatus == 0} {
        append description "
  Found make executable: $makePath"
        if {[string match "*Windows32*" $result]} {
            if {[string match "*Symbian*" $result]} {
                append description "<br>
  This machine has Symbian Make installed.<br>
  Emake flags:<br>
    --emake-emulation-table=make=symbian"
            } else {
                append description "<br>
  This machine has native Windows GNU Make installed.<br>
  Emake flags:<br>
    --emake-emulation-table=make=symbian"
            }
            set status 2
        } elseif {[string match "*GNU Make version 3.79.1*" $result]} {
            append description "<br>
  This machine has GNU Make 3.79.1 installed.<br>
  Emake flags:<br>
    --emake-emulation-table=make=gmake"
            set status 2
        } elseif {[string match "*GNU Make 3.80*" $result]} {
            append description "<br>
  This machine has GNU Make 3.80 installed.<br>
  Emake flags:<br>
    --emake-emulation-table=make=gmake"
            set status 2
        } elseif {[string match "*GNU Make 3.81*" $result]} {
            append description "<br>
  This machine has GNU Make 3.81 installed.<br>
  Emake flags:<br>
    --emake-emulation-table=make=gmake"
            set status 2
        } else {
            append description "<br>
  This machine has an unsupported version of make installed.<br>
  Output:<br>
<pre>[fixHtml $result]</pre>"
            set status 1
        }
    }
    # Return the result
    return [list $status $title $description $solution $links]
}

proc check_all_agentVersion {} {
    if {"$::gConfig(cm)" == ""} {
        return [list 1000]
    }
    set agentList [getAgentList]
    if {[lindex $agentList 0] != 0} {
        print "Unable to connect to cluster manager."
        return [list 1000]
    }

    set status 0
    set title "Checking for emake/agent/efs version on agents."
    set description "
  The following machines have an inconsistent emake/agent/efs installation."
    set solution "
  Please make sure that all machines use the same emake/agent/efs version."
    set links [list http://www.cygwin.com http://www.electric-cloud.com/support support@electric-cloud.com]

    # Run the test
    print $title 1
    set emakeVersion ""
    set agentVersion ""
    set efsVersion ""

    # Find the executables.
    set emakePath ""
    if {"$::tcl_platform(platform)" == "unix"} {
        set pathSep ":"
        set exeExt ""
    } else {
        set pathSep ";"
        set exeExt ".exe"
    }
    foreach path [split $::env(PATH) $pathSep] {
        if {$emakePath == "" &&
            [file exists [file join $path emake$exeExt]]} {
            set emakePath [file join $path emake$exeExt]
        }
    }

    if {"$emakePath" == ""} {
        set description "Unable to locate emake in your path."
        set status 1
    } else { 
        set cmdResult [runCommand "" "" "exec $emakePath --version"]
        set cmdStatus [lindex $cmdResult 0]
        set result [lindex $cmdResult 1]
        if {$cmdStatus != 0} {
            set description "Unable to determine the version of emake.<br>
Output:<br>
<pre>[fixHtml $emakeVersion]</pre>"
            set status 1
        }
        regexp {version (\d+\.\d+\.\d+\.\d+)} $emakeVersion ignore emakeVersion
        append description "<br>
  Host: local<br>
  &nbsp;&nbsp;emake: $emakeVersion"
        foreach {host ip port} [lindex $agentList 1] {
            set cmdResult [runCommand $ip $port "exec $emakePath --version"]
            set cmdStatus [lindex $cmdResult 0]
            set res1 [lindex $cmdResult 1]
            if {$cmdStatus == 0} {
                regexp {version (\d+\.\d+\.\d+\.\d+)} $res1 ignore res1
                set cmdResult [runCommand $ip $port "getVersion"]
                set cmdStatus [lindex $cmdResult 0]
                if {$cmdStatus == 0} {
                    set res2 [lindex $cmdResult 1]
                    set res3 ""
                    regexp {EFS (\d+\.\d+\.\d+\.\d+)} $res2 ignore res3
                    regexp {Agent (\d+\.\d+\.\d+\.\d+)} $res2 ignore res2
                    if {"$agentVersion" == ""} {
                        set agentVersion $res2
                    }
                    if {"$efsVersion" == ""} {
                        set efsVersion $res3
                    }
                    if {!("$emakeVersion" == "$res1" ||
                          "$agentVersion" == "$res2" ||
                          "$efsVersion" == "$res3")} {
                        append description "<br>
  Host: $host ($ip):<br>
  &nbsp;&nbsp;emake: $res1<br>
  &nbsp;&nbsp;agent: $res2<br>
  &nbsp;&nbsp;efs: $res3"
                        set status 1
                    }
                }
            }
        }
    }

    # Return the result
    return [list $status $title $description $solution $links]
}

proc check_all_ecdiskperf {} {
    set status 0
    set title "Checking for disk performance."
    set description "
  This machine has a relatively slow disk performance."
    set solution "
  Please contact Electric Cloud."
    set links [list http://www.electric-cloud.com/support support@electric-cloud.com]

    # Run the test
    print $title 1
    catch {file delete -force __ecdiskperf__}
    set cmdResult [runCommand "" "" "exec $::gConfig(ecdiskperf)"]
    set cmdStatus [lindex $cmdResult 0]
    set result [lindex $cmdResult 1]
    if {$cmdStatus != 0} {
        set description "
  Unable to run the ecdiskperf executable:<br>
    $::gConfig(ecdiskperf)<br>
  Output:<br>
<pre>[fixHtml $result]</pre>"
        set status 1
    } else {
        if {![regexp {Write bandwidth:\s*([0-9.]+) MB/s} $result ignore wbw] ||
            ![regexp {Read bandwidth:\s*([0-9.]+) MB/s} $result ignore rbw]} {
            set description "
  Unable to extract the read/write bandwidth.<br>
  <br>
  Output:<br>
<pre>[fixHtml $result]</pre>"
            set status 1
        } else {
            if {!($wbw > 15 && $rbw > 10)} {
                append description "<br>
<br>
<pre>[fixHtml $result]</pre>"
                set status 1
            } else {
                set description "
  This machines disk performance was ok:<br>
  Output:<br>
<pre>[fixHtml $result]</pre>"
                set status 2
            }
        }
    }

    # Return the result
    return [list $status $title $description $solution $links]
}

proc check_all_cmConnect {} {
    if {"$::gConfig(cm)" == ""} {
        return [list 1000]
    }

    set status 0
    set title "Checking for cluster manager connectivity."
    set description "
  This cluster manager can not be reached."
    set solution "
  Please contact Electric Cloud."
    set links [list http://www.electric-cloud.com/support support@electric-cloud.com]

    # Run the test
    print $title 1
    # Make sure we reconnect...
    set ::gConfig(agents) ""
    set ::gConfig(agentsUnique) ""
    set agentList [getAgentList]
    if {[lindex $agentList 0] != 0 || $::gConfig(faillevel) != 0} {
        append description "<br>
  Output:<br>
<pre>[fixHtml [lindex $agentList 1]]</pre>"
        set status 1
    }

    # Return the result
    return [list $status $title $description $solution $links]
}

proc check_all_ecnetperf {} {
    if {"$::gConfig(cm)" == ""} {
        return [list 1000]
    }

    set status 0
    set title "Checking for net performance."
    set description "
  This cluster has a relatively slow net performance."
    set solution "
  Please contact Electric Cloud."
    set links [list http://www.electric-cloud.com/support support@electric-cloud.com]

    # Run the test
    print $title 1
    set cmdResult [runCommand "" "" "exec $::gConfig(ecnetperf)  -cm $::gConfig(cm)"]
    set cmdStatus [lindex $cmdResult 0]
    set result [lindex $cmdResult 1]
    if {$cmdStatus != 0} {
        set description "
  Unable to run the ecnetperf executable:<br>
    $::gConfig(ecnetperf)<br>
  Output:<br>
<pre>[fixHtml $result]</pre>"
        set status 1
    } else {
        set description "
  This cluster network performance was:<br>
  Output:<br>
<pre>[fixHtml $result]</pre>"
        set status 2
    }

    # Return the result
    return [list $status $title $description $solution $links]
}

proc check_all_clearcase {} {
    set status 0
    set title "Checking for ClearCase."
    set description "
  This machine has a version of ClearCase installed."
    set solution "
  For best performance, consider the following:
    * Static views generally provide better performance than dynamic views.
    * The disk, memory and network configuration of your view and VOB servers
      will have a significant impact on your build performance.  Ensure that
      these resources are adequately provisioned for your requirements.
    * You may wish to use the --emake-clearcase option when invoking builds.
      See the ElectricAccelerator ElectricMake Users Guide for information 
      about this option.

  For additional information, contact Electric Cloud support."

    set links [list http://www.electric-cloud.com/support support@electric-cloud.com https://electriccloud.zendesk.com/entries/105079-kbea-00067-diagnosing-a-slow-clearcase-server]

    # Run the test
    print $title 1
    set cmdResult [runCommand "" "" "exec cleartool -ver"]
    set cmdStatus [lindex $cmdResult 0]
    set result [lindex $cmdResult 1]
    if {$cmdStatus == 0} {
        append description "<br>
  Output:<br>
<pre>[fixHtml $result]</pre>"
        set status 1
    }

    # Return the result
    return [list $status $title $description $solution $links]
}


# Information retrieval functions

# Generic
proc get_tclOS {{ip ""} {port ""}} {
    set cmdResult [runCommand $ip $port "list \$tcl_platform(os) \$tcl_platform(machine) \$tcl_platform(osVersion)"]
    set cmdStatus [lindex $cmdResult 0]
    set result [lindex $cmdResult 1]
    if {$cmdStatus != 0} {
        return [list 1 $result]
    }
    return [list 0 $result]
} 


# Windows
proc test_i686_win32_tclOS {os machine osVersion} {
    if {"$os" == "Windows NT" &&
        "$machine" == "intel" &&
        ("$osVersion" == "5.0" || 
         "$osVersion" == "5.1" ||
         "$osVersion" == "5.2")} {
        return 1
    } else {
        return 0
    }
}

proc get_i686_win32_osString {{ip ""} {port ""}} {
    set result ""

    set cmdResult [getRegistryKey "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion" ProductName $ip $port]
    set cmdStatus [lindex $cmdResult 0]
    set product [lindex $cmdResult 1]
    if {$cmdStatus == 0} {
        append result "$product"
    }
    set cmdResult [getRegistryKey "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion" CSDVersion $ip $port]
    set cmdStatus [lindex $cmdResult 0]
    set servicePack [lindex $cmdResult 1]
    if {$cmdStatus == 0} {
        append result " ($servicePack)"
    }
    if {"$result" == ""} {
        return [list 1 "Unable to get os version ($result)"]
    }
    return [list 0 $result]
}

proc get_i686_win32_processors {{ip ""} {port ""}} {
    set processorList [list ]

    set cmdResult [getRegistryKey {HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment} NUMBER_OF_PROCESSORS $ip $port]
    set cmdStatus [lindex $cmdResult 0]
    set result [lindex $cmdResult 1]
    if {$cmdStatus == 0} {
        for {set counter 0} {$counter < $result} {incr counter} {
            set processor ""
            set cmdResult [getRegistryKey "HKEY_LOCAL_MACHINE\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\$counter" VendorIdentifier $ip $port]
            set cmdStatus [lindex $cmdResult 0]
            set vendor [lindex $cmdResult 1]
            if {$cmdStatus == 0} {
                append processor "$vendor"
            }
            set cmdResult [getRegistryKey "HKEY_LOCAL_MACHINE\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\$counter" ~MHZ $ip $port]
            set cmdStatus [lindex $cmdResult 0]
            set mhz [lindex $cmdResult 1]
            if {$cmdStatus == 0} {
                append processor " ($mhz Mhz)"
            }
            if {[string length $processor] == 0} {
                lappend processorList "unknown processor"
            } else {
                lappend processorList $processor
            }
        }
    } else {
        return [list 1 "Unable to get processor list ($result)"]
    }
    return [list 0 $processorList]
}

proc get_i686_win32_memory {{ip ""} {port ""}} {
    set memory 0

    set cmdResult [getRegistryKey {HKEY_LOCAL_MACHINE\HARDWARE\RESOURCEMAP\System Resources\Physical Memory} .Translated $ip $port]
    set cmdStatus [lindex $cmdResult 0]
    set result [lindex $cmdResult 1]
    if {$cmdStatus == 0} {
        binary scan $result i* first
        set result [lindex $first end]
        set memory [expr int($result / 1000.0 / 1000.0)]
    } else {
        return [list 1 "Unable to get memory size ($result)"]
    }
    return [list 0 $memory]
}

proc get_i686_win32_diskspace {} {
    set free 0

    # Run the command to get the data
    set cmdResult [runCommand "" "" "exec cmd /c dir"]
    set cmdStatus [lindex $cmdResult 0]
    set result [lindex $cmdResult 1]
    if {$cmdStatus != 0} {
        return [list 1 [lindex $cmdResult 1]]
    }

    # extract the value...
    if {![regexp {Dir\(s\)\s*([0-9,]+) bytes free} $result ignore free]} {
        # Error extracting... return the original result
        return [list 1 $result]
    } else {
        regsub -all {,} $free {} free
        set free [expr int((($free / 1000.0) / 1000.0) / 1000.0)]
    }
    return [list 0 $free]
}


# Solaris
proc test_sun4u_SunOS_tclOS {os machine osVersion} {
    set supported(os)           [list "SunOS"]
    set supported(mach)         [list "sun4u" "sun4v"]
    set supported(version)      [list "5.8" "5.9" "5.10"]

    if { [lsearch -exact $supported(os) $os] != -1
         && [lsearch -exact $supported(mach) $machine] != -1
         && [lsearch -exact $supported(version) $osVersion] != -1 } {
        return 1
    }
    return 0
}

proc get_sun4u_SunOS_osString {{ip ""} {port ""}} {
    set result "unknown"

    # Run the command to get the data
    set cmdResult [runCommand $ip $port "exec /bin/uname -a"]
    set cmdStatus [lindex $cmdResult 0]
    set result [lindex $cmdResult 1]
    if {$cmdStatus != 0} {
        return [list 1 [lindex $cmdResult 1]]
    }
    return [list 0 $result]
}

proc get_sun4u_SunOS_processors {{ip ""} {port ""}} {
    set processorList [list ]

    # Run the command to get the data
    set cmdResult [runCommand $ip $port "exec /usr/sbin/psrinfo -v"]
    set cmdStatus [lindex $cmdResult 0]
    set result [lindex $cmdResult 1]
    if {$cmdStatus != 0} {
        return [list 1 [lindex $cmdResult 1]]
    }

    # Go through the results and extract processor info
    foreach line [split $result "\n"] {
        if {[regexp {The (.*) processor operates at (\d+)} $line ignore processor speed]} {
            lappend processorList "$processor ($speed MHz)"
        }
    }
    return [list 0 $processorList]
}

proc get_sun4u_SunOS_memory {{ip ""} {port ""}} {
    set memory 0

    # Run the command to get the data
    set cmdResult [runCommand $ip $port "exec /usr/sbin/prtconf"]
    set cmdStatus [lindex $cmdResult 0]
    set result [lindex $cmdResult 1]
    if {$cmdStatus != 0} {
        return [list 1 [lindex $cmdResult 1]]
    }

    if {![regexp {Memory size: (\d+) Megabytes} $result ignore memory]} {
        return [list 1 [lindex $cmdResult 1]]
    } else {
        regsub -all {,} $memory {} memory
    }
    return [list 0 $memory]
}

proc get_sun4u_SunOS_diskspace {} {
    set free 0

    # Run the command to get the data
    set cmdResult [runCommand "" "" "exec /usr/bin/df -b [pwd]"]
    set cmdStatus [lindex $cmdResult 0]
    set result [lindex $cmdResult 1]
    if {$cmdStatus != 0} {
        return [list 1 [lindex $cmdResult 1]]
    }

    # extract the value...
    if {![regexp {\s+([0-9,]+)} $result ignore free]} {
        # Error extracting... return the original result
        return [list 1 $result]
    } else {
        set free [expr int(($free / 1000.0) / 1000.0)]
    }
    return [list 0 $free]
}


# Linux
proc test_i686_Linux_tclOS {os machine osVersion} {
    if { "$os" != "Linux" } {
        return 0
    }

    if { [lsearch -exact [list i586 i686 x86_64] $machine] == -1 } {
        # We only support i586, i686 and x86_64 systems.

        return 0
    }

    set kernel24 [string match "2.4.*" "$osVersion"]
    set kernel26 [string match "2.6.*" "$osVersion"]

    if { !$kernel24 && !$kernel26 } {
        # We only support 2.4.x and 2.6.x kernels.

        return 0
    }

    if { "$machine" == "x86_64" && !$kernel26 } {
        # 64-bit is only supported on 2.6.x kernels.

        return 0
    }

    return 1
}

proc get_i686_Linux_osString {{ip ""} {port ""}} {
    set result "unknown"

    # Run the command to get the data
    set cmdResult [runCommand $ip $port "exec /bin/uname -a"]
    set cmdStatus [lindex $cmdResult 0]
    set result [lindex $cmdResult 1]
    if {$cmdStatus != 0} {
        return [list 1 [lindex $cmdResult 1]]
    }
    return [list 0 $result]
}

proc get_i686_Linux_processors {{ip ""} {port ""}} {
    set processorList [list ]

    # Run the command to get the data
    set cmdResult [runCommand $ip $port "exec /bin/cat /proc/cpuinfo"]
    set cmdStatus [lindex $cmdResult 0]
    set result [lindex $cmdResult 1]
    if {$cmdStatus != 0} {
        return [list 1 [lindex $cmdResult 1]]
    }

    # Go through the results and extract processor info
    foreach line [split $result "\n"] {
        regexp {model name\s*: (.*)} $line ignore processor
        if {[regexp {flags\s*:} $line]} {
            if {[regexp {[ ht | ht$]} $line]} {
                lappend processorList "$processor (hyperthreaded)"
            } else {
                lappend processorList "$processor (not hyperthreaded)"
            }
            set processor "unknown"
        }
    }
    return [list 0 $processorList]
}

proc get_i686_Linux_memory {{ip ""} {port ""}} {
    set memory 0

    # Run the command to get the data
    set cmdResult [runCommand $ip $port "exec /bin/cat /proc/meminfo"]
    set cmdStatus [lindex $cmdResult 0]
    set result [lindex $cmdResult 1]
    if {$cmdStatus != 0} {
        return [list 1 [lindex $cmdResult 1]]
    }

    if {![regexp {MemTotal:\s*(\d+) kB} $result ignore memory]} {
        return [list 1 [lindex $cmdResult 1]]
    } else {
        set memory [expr int($memory / 1000.0)]
    }
    return [list 0 $memory]
}

proc get_i686_Linux_diskspace {} {
    set free 0

    # Run the command to get the data
    set cmdResult [runCommand "" "" "exec /bin/df -k [pwd]"]
    set cmdStatus [lindex $cmdResult 0]
    set result [lindex $cmdResult 1]
    if {$cmdStatus != 0} {
        return [list 1 [lindex $cmdResult 1]]
    }

    # extract the value...
    if {![regexp {\s+[0-9]+\s+[0-9]+\s+([0-9]+)\s+[0-9]+%\s+} $result ignore free]} {
        # Error extracting... return the original result
        return [list 1 $result]
    } else {
        set free [expr int(($free / 1000.0) / 1000.0)]
    }
    return [list 0 $free]
}


# Utility functions
proc print {msg {nonewline 0}} {
    if {"$::gConfig(outputfile)" != ""} {
        if {$nonewline} {
            puts -nonewline $msg
            flush stdout
        } else {
            puts $msg
        }
    } else {
        if {$nonewline} {
            puts -nonewline stderr $msg
            flush stderr
        } else {
            puts stderr $msg
        }
    }
}

proc printResult {msg} {
    if {$::gConfig(fd) != ""} {
        puts $::gConfig(fd) $msg
    } else {
        puts $msg
    }
}

proc readData {s} {
    global gAgentReadData
    global gAgentReadDone

    if {[eof $s]} {
        catch {close $s}
        set gAgentReadDone 1
        return
    }

    # Read the result back.  The other side sends us information in the
    # following form:
    #  - the command-line prompt (output before we sent the command)
    #  - a line consisting of "xyzzy"; this line allows us to skip over
    #    the command-line prompt
    #  - a line containing a decimal number, which is the number of bytes
    #    in the result
    #  - the result (exactly the number of bytes promised)

    while {1} {
        set line [gets $s]
        if {$line == "xyzzy"} {
            break
        }
    }
    set length [gets $s]
    set gAgentReadData [read $s $length]
    catch {close $s}
    set gAgentReadDone 1
    return
}

proc agentReadTimeout {s host port} {
    global gAgentReadDone
    global gAgentTimeout
    global gTimeoutAgents

    catch {close $s}
    if {![info exists gTimeoutAgents($host:$port)]} {
        set gTimeoutAgents($host:$port) 1
    } else {
        incr gTimeoutAgents($host:$port)
    }
    set gAgentTimeout 1
    set gAgentReadDone 1
}

proc agentCommand {host port cmd} {
    global gAgentReadData
    global gAgentReadDone
    global gAgentTimeout
    global gTimeoutAgents

    set gAgentReadData ""
    set gAgentReadDone 0
    set gAgentTimeout 0
    if {[catch {socket $host $port} s]} {
        if {![info exists gTimeoutAgents($host:$port)]} {
            set gTimeoutAgents($host:$port) 1
        } else {
            incr gTimeoutAgents($host:$port)
        }
        return [list 1 ""]
    }
    fconfigure $s -blocking 0 -buffering none
    fileevent $s readable [list readData $s]

    set length [string length $cmd]
    puts $s "DoCommand $length"
    puts -nonewline $s $cmd
    flush $s

    # Register a timeout...
    set id [after 10000 [list agentReadTimeout $s $host $port]]

    # Wait for the socket to become readable or timeout.
    vwait gAgentReadDone
    catch {after cancel $id}

    return [list $gAgentTimeout $gAgentReadData]
}

proc runCommand {ip port cmd} {
    if {$::gConfig(faillevel) == 1} {
        return [list 1 "fail"]
    }
    if {$::gConfig(faillevel) == 2} {
        return [getTestData $cmd]
    }

    if {"$ip" == ""} {
        if {[catch $cmd result]} {
            # Program invocation error
            return [list 1 $result]
        }
    } else {
        set cmdResult [agentCommand $ip $port $cmd]
        if {[lindex $cmdResult 0] != 0} {
            # Program invocation error
            return $cmdResult
        }
        set result [lindex $cmdResult 1]
    }

    if {[regexp {couldn't execute} $result]} {
        # Program invocation error
        return [list 1 $result]
    }
    return [list 0 $result]
}

proc getAgentUniqueList {} {
    if {"$::gConfig(agentsUnique)" != ""} {
        return [list 0 $::gConfig(agentsUnique)]
    }

    set tmpIPList [list ]
    set agentList [getAgentList]
    foreach {host ip port} [lindex $agentList 1] {
        if {[lsearch $tmpIPList $ip] == -1} {
            lappend tmpIPList $ip
            lappend ::gConfig(agentsUnique) $host $ip $port
        }
    }
    return [list [lindex $agentList 0] $::gConfig(agentsUnique)]
}

proc getAgentList {} {
    if {"$::gConfig(agents)" != ""} {
        return [list 0 $::gConfig(agents)]
    }

    if {$::gConfig(faillevel) == 2} {
        set ::gConfig(agents) [list machine1 192.168.0.0 9000 machine2 192.168.0.1 9000 machine3 192.168.0.0 9000]
        return [list 0 $::gConfig(agents)]
    }

    set agents [list ]
    set url http://$::gConfig(cm)/ecloud/service/agent_list.xml?ShowAll=1
    set auth [base64::encode "emake:emake"]
    set headers [list Authorization "Basic $auth"]
    if {[catch {http::geturl $url -headers $headers} tok]} {
        return [list 1 "CM connection failed: $tok"]
    }
    set code [http::ncode $tok]
    if { $code != 200} {
        return [list 1 "CM request returned with code $code"]
    }
    set xml [http::data $tok]
    http::cleanup $tok

    set d [[dom parse $xml] documentElement]
    set agentNodes [$d selectNodes "/ECloud/AgentList/Agent"]
    foreach node $agentNodes {
        set name      [$node selectNodes Name/text()]
        set ipaddress [$node selectNodes IPAddress/text()]
        set port      [$node selectNodes ConsolePort/text()]
        
        set err ""
        if { $name == "" } {
            append err " no agent name"
        }
        if { $ipaddress == "" } {
            append err " no IP address"
        }
        if { $port == "" } {
            append err " no console port"
        }
        if { $err != "" } {
            set idNode [$node selectNodes ID/text()]
            set agentId [$idNode nodeValue]
            
            set message "WARNING:  Skipping invalid agent entry "
            append message "(agent ID $agentId):"
            append message $err
            append message "\n"
            print $message
            continue
        }
        
        lappend agents \
            [$name nodeValue] \
            [$ipaddress nodeValue] \
            [$port nodeValue]
    }
    set ::gConfig(agents) $agents
    return [list 0 $agents]
}

proc getRegistryKey {key name {ip ""} {port ""}} {
    if {$::gConfig(faillevel) == 1} {
        return [list 1 "fail"]
    }
    if {$::gConfig(faillevel) == 2} {
        return [getTestData "$key $name"]
    }

    if {"$ip" == ""} {
        if {[catch {registry get $key $name} result]} {
            return [list 1 $result]
        }
    } else {
        agentCommand $ip $port "package require registry"
        set cmdResult [agentCommand $ip $port [list registry get $key $name]]
        set cmdStatus [lindex $cmdResult 0]
        set result [lindex $cmdResult 1]
        if {$cmdStatus != 0} {
            return [list 1 $result]
        }
    }
    return [list 0 $result]
}

proc registryKeyExists {key {ip ""} {port ""}} {
    if {$::gConfig(faillevel) == 1} {
        return [list 1 "fail"]
    }
    if {$::gConfig(faillevel) == 2} {
        return [getTestData $key]
    }

    if {"$ip" == ""} {
        if {[catch {registry keys $key} result]} {
            return [list 0 0]
        }
    } else {
        agentCommand $ip $port "package require registry"
        set cmdResult [agentCommand $ip $port "registry keys $key"]
        set cmdStatus [lindex $cmdResult 0]
        set result [lindex $cmdResult 1]
        if {$cmdStatus != 0} {
            return [list 1 $result]
        } else {
            if {[string match "unable to open key:*" $result]} {
                return [list 0 0]
            }
        }
    }
    return [list 0 1]
}

proc stripHtml {msg} {
    regsub -all {<br>} $msg {} msg
    regsub -all {<pre>} $msg {} msg
    regsub -all {</pre>} $msg {} msg
    regsub -all {&nbsp;} $msg { } msg

    return $msg
}

proc fixHtml {msg} {
    regsub -all {&} $msg {\&amp;} msg
    regsub -all {<} $msg {\&lt;} msg
    regsub -all {>} $msg {\&gt;} msg

    return $msg
}

proc getTestData {cmd} { 
    switch -glob -- $cmd {
        {exec /usr/sbin/psrinfo -v} {
            return [list 0 {The sparcv9 processor operates at 548 MHz}]
        }
        {exec /usr/sbin/prtconf} { 
            return [list 0 {Memory size: 808 Megabytes}]
        }
        {exec /bin/uname -a} {
            switch -- $::gConfig(arch) {
                {sun4u_SunOS} {
                    return [list 0 {SunOS leo2 5.8 Generic_108528-13 sun4u sparc SUNW,UltraAX-i2}]
                }
                {i686_Linux} {
                    return [list 0 {Linux linb1 2.4.21-32.0.1.ELsmp 1 SMP Tue May 17 17:52:23 EDT 2005 i686 i686 i386 GNU/Linux}]
                }
            }
        }
        {exec uname -r} {
            return [list 0 {CYGWIN_NT-5.1 basis 1.5.17(0.132/4/2) 2005-07-02 20:30 i686 unknown unknown Cygwin}]
        }
        {exec /usr/bin/df -b *} {
            return [list 0 {Filesystem              avail
filer:/vol/vol0/space  9726848}]
        }
        {exec /bin/df -k *} {
            return [list 0 {Filesystem           1K-blocks      Used Available Use% Mounted on
filer:/vol/vol0/space
                4194304   2467456   9726848  59% /net/filer}]
        }
        {exec gmake --version} {
            return [list 0 {GNU Make 3.80}]
        }
        {exec make --version} {
            return [list 0 {GNU Make 3.80}]
        }
        {exec cleartool -ver} {
            return [list 0 {clearcase}]
        }
        {exec CC -V} {
            return [list 0 {Forte}]
        }
        {exec /bin/cat /proc/meminfo} {
            return [list 0 {        total:    used:    free:  shared: buffers:  cached:
Mem:  1049899008 584110080 465788928        0 66899968 315351040
Swap: 2146787328        0 2146787328
MemTotal:       808292 kB
MemFree:        454872 kB
MemShared:           0 kB
Buffers:         65332 kB
Cached:         307960 kB
SwapCached:          0 kB
Active:         212108 kB
ActiveAnon:      39784 kB
ActiveCache:    172324 kB
Inact_dirty:     66132 kB
Inact_laundry:  127876 kB
Inact_clean:     10484 kB
Inact_target:    83320 kB
HighTotal:      130928 kB
HighFree:        33428 kB
LowTotal:       894364 kB
LowFree:        421444 kB
SwapTotal:     2096472 kB
SwapFree:      2096472 kB
CommitLimit:   2609116 kB
Committed_AS:   111984 kB
HugePages_Total:     0
HugePages_Free:      0
Hugepagesize:     2048 kB}]
        }
        {exec /bin/cat /proc/cpuinfo} {
            return [list 0 {processor       : 0
vendor_id       : GenuineIntel
cpu family      : 15
model           : 2
model name      : Intel(R) Xeon(TM) CPU 3.06GHz
stepping        : 9
cpu MHz         : 3056.605
cache size      : 512 KB
physical id     : 0
siblings        : 2
runqueue        : 0
fdiv_bug        : no
hlt_bug         : no
f00f_bug        : no
coma_bug        : no
fpu             : yes
fpu_exception   : yes
cpuid level     : 2
wp              : yes
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov 
pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm
bogomips        : 6094.84
}]
        }
        {list $tcl_platform(os) $tcl_platform(machine) $tcl_platform(osVersion)} {
            return [list 0 [list aaa bbb ccc]]
        }
        {getVersion} {
            if {[info exists ::gConfig(agentVersionMismatch)]} {
                return [list 0 {Agent 2.3.0.4693 build_2.3_4693_OPT_2005.07.25_15:26:23 EFS 2.3.0.4693 build_2.3_4693_OPT_2005.07.25_15:32:31}]
            } else { 
                set ::gConfig(agentVersionMismatch) 1
                return [list 0 {Agent 2.3.0.4694 build_2.3_4694_OPT_2005.07.25_15:26:23 EFS 2.3.0.4694 build_2.3_4694_OPT_2005.07.25_15:32:31}]
            }
        }
        {exec cmd /c dir} {
            return [list 0 {Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\Documents and Settings\test>dir
 Volume in drive C has no label.
 Volume Serial Number is 280A-8445

 Directory of C:\Documents and Settings\test

07/20/2005  07:59 AM    <DIR>          .
07/20/2005  07:59 AM    <DIR>          ..
06/12/2005  02:38 PM                31 .bash_history
06/11/2005  11:01 PM           155,752 .fonts.cache-1
06/11/2005  11:56 PM    <DIR>          .gimp-2.2
07/26/2005  04:43 PM    <DIR>          Desktop
06/21/2005  02:16 PM    <DIR>          My Documents
07/06/2005  10:01 AM    <DIR>          Start Menu
               2 File(s)        155,783 bytes
               6 Dir(s)  9,293,801,984 bytes free}]
        }
        {exec nmake /help} {
            return [list 0 {
Microsoft (R) Program Maintenance Utility Version 7.00.9954
Copyright (C) Microsoft Corporation.  All rights reserved.

Usage:  NMAKE @commandfile
        NMAKE [options] [/f makefile] [/x stderrfile] [macrodefs] [targets]

Options:
}]
        }
        {*emake* --version} {
            return [list 0 {Electric Make version 2.3.0.4693 (build_2.3_4693_OPT_2005.07.25_15:28:44)
Copyright (c) 2002-2026 Electric Cloud, Inc.
All rights reserved.}]
        }
        {*ecdiskperf*} {
            return [list 0 {testdata}]
        }
        {*ecnetperf*} {
            return [list 0 {testdata}]
        }
        {HKEY_LOCAL_MACHINE*Path Dirs} { 
            return [list 1]
        }
        {HKEY_LOCAL_MACHINE*Cygwin} { 
            return [list 1]
        }
        {HKEY_LOCAL_MACHINE*Parameters MaxUserPort} { 
            return [list 0 30000]
        }
        {HKEY_LOCAL_MACHINE*Norton AntiVirus} { 
            return [list 1]
        }
        {HKEY_LOCAL_MACHINE*VirusScan} { 
            return [list 1]
        }
        {HKEY_LOCAL_MACHINE*TrendMicro} { 
            return [list 1]
        }
        {HKEY_LOCAL_MACHINE*Physical Memory .Translated} {
            return [list 0 512000000]
        }
        {HKEY_LOCAL_MACHINE*NUMBER_OF_PROCESSORS} {
            return [list 0 1]
        }
        {HKEY_LOCAL_MACHINE*VendorIdentifier} {
            return [list 0 testvendor]
        }
        {HKEY_LOCAL_MACHINE*~MHZ} {
            return [list 0 1000]
        }
        {HKEY_LOCAL_MACHINE*ProductName} {
            return [list 0 testos]
        }
        {HKEY_LOCAL_MACHINE*CSDVersion} {
            return [list 0 "service pack 1"]
        }
        default {
            puts "TEST COMMAND: $cmd<"
            return [list 0 {unknown}]
        }
    }
}

proc main {} {
    global gTimeoutAgents

    set platform $::tcl_platform(os)

    # Setup commandline options
    set ::gConfig(os) $::tcl_platform(os)
    set ::gConfig(cm) ""
    set ::gConfig(output) "text"
    set ::gConfig(outputfile) ""
    set ::gConfig(fd) ""
    set ::gConfig(faillevel) 0
    set ::gConfig(test) ""
    set ::gConfig(agents) ""
    set ::gConfig(agentsUnique) ""
    lappend ::gOptions [list os.arg $::gConfig(os) "The os to check for."]
    lappend ::gOptions [list cm.arg $::gConfig(cm) "The cluster manager to use."]
    lappend ::gOptions [list output.arg $::gConfig(output) "The output format (text|html)"]
    lappend ::gOptions [list outputfile.arg $::gConfig(outputfile) "The output file to use (or stdout)"]
    lappend ::gOptions [list test.arg $::gConfig(test) "The test to run."]
    lappend ::gOptions [list faillevel.arg.secret $::gConfig(faillevel) "Simulate test failures."]

    # read commandline arguments...
    if {[llength $::argv] > 0} {
        if {[catch {cmdline::getoptions ::argv $::gOptions} opts]} {
            puts stderr $opts
            exit 1
        }
        array set ::gConfig $opts
    }

    set result [list ]
    switch -- $::gConfig(os) {
        {Windows NT} {
            set ::gConfig(arch) "i686_win32"
            set ::gConfig(instdir) "[file dirname [file dirname [info script]]]"
            set ::gConfig(ecdiskperf) \
                "$::gConfig(instdir)/i686_win32/unsupported/ecdiskperf.exe"
            if {![file exists ::gConfig(ecdiskperf)]} {
                set ::gConfig(ecdiskperf) "c:/ECloud/i686_win32/unsupported/ecdiskperf.exe"
            }
            set ::gConfig(ecnetperf) \
                "$::gConfig(instdir)/i686_win32/unsupported/ecnetperf.exe"
            if {![file exists ::gConfig(ecnetperf)]} {
                set ::gConfig(ecnetperf) "c:/ECloud/i686_win32/unsupported/ecnetperf.exe"
            }
        }
        {SunOS} {
            set ::gConfig(arch) "sun4u_SunOS"
            set ::gConfig(instdir) "/opt/ecloud"
            set ::gConfig(ecdiskperf) \
                "$::gConfig(instdir)/sun4u_SunOS/unsupported/ecdiskperf"
            set ::gConfig(ecnetperf) \
                "$::gConfig(instdir)/sun4u_SunOS/unsupported/ecnetperf"
        }
        {Linux} {
            set ::gConfig(arch) "i686_Linux"
            set ::gConfig(instdir) "/opt/ecloud"
            set ::gConfig(ecdiskperf) \
                "$::gConfig(instdir)/i686_Linux/unsupported/ecdiskperf"
            set ::gConfig(ecnetperf) \
                "$::gConfig(instdir)/i686_Linux/unsupported/ecnetperf"
        }
    }

    if {"$::gConfig(test)" != ""} {
        set testName "check_$::gConfig(arch)_$::gConfig(test)"
        if {[llength [info procs $testName]] == 0} {
            set testName "check_all_$::gConfig(test)"
            if {[llength [info procs $testName]] == 0} {
                puts stderr "Unknown test: $::gConfig(test)"
                puts stderr "Available tests:"
                set len 10
                set testList [list ]
                foreach test [info procs check_all_*] {
                    lappend testList [string range $test $len end]
                }
                set len [expr 7 + [string length $::gConfig(arch)]]
                foreach test [info procs check_$::gConfig(arch)_*] {
                    lappend testList [string range $test $len end]
                }
                foreach test [lsort $testList] {
                    puts stderr "  $test"
                }
                exit 1
            }
        }
        set item [$testName]
        if {[lindex $item 0] == 1} {
            print " (failed)"
            lappend result $item
        } elseif {[lindex $item 0] == 2} {
            print " (info)"
            lappend result $item
        } elseif {[lindex $item 0] == 0} {
            print " (ok)"
        }
    } else {
        switch -- $::gConfig(os) {
            {Windows NT} {
                foreach check [lsort [info procs check_i686_win32_*]] {
                    set item [$check]
                    if {[lindex $item 0] == 1} {
                        print " (failed)"
                        lappend result $item
                    } elseif {[lindex $item 0] == 2} {
                        print " (info)"
                        lappend result $item
                    } elseif {[lindex $item 0] == 0} {
                        print " (ok)"
                    }
                } 
            }
            {SunOS} {
                foreach check [lsort [info procs check_sun4u_SunOS_*]] {
                    set item [$check]
                    if {[lindex $item 0] == 1} {
                        print " (failed)"
                        lappend result $item
                    } elseif {[lindex $item 0] == 2} {
                        print " (info)"
                        lappend result $item
                    } elseif {[lindex $item 0] == 0} {
                        print " (ok)"
                    }
                }
            } 
            {Linux} {
                foreach check [lsort [info procs check_i686_Linux_*]] {
                    set item [$check]
                    if {[lindex $item 0] == 1} {
                        print " (failed)"
                        lappend result $item
                    } elseif {[lindex $item 0] == 2} {
                        print " (info)"
                        lappend result $item
                    } elseif {[lindex $item 0] == 0} {
                        print " (ok)"
                    }
                }
            }
            default {
                puts stderr "Unknown operating system ($::tcl_platform(os))."
                exit 1
            }
        }
        
        # Platform independent checks
        foreach check [lsort [info procs check_all_*]] {
            set item [$check]
            if {[lindex $item 0] == 1} {
                print " (failed)"
                lappend result $item
            } elseif {[lindex $item 0] == 2} {
                print " (info)"
                lappend result $item
            } elseif {[lindex $item 0] == 0} {
                print " (ok)"
            }
        }
    }

    # Report failed agents
    if {[array size gTimeoutAgents] > 0} {
        set description "The following agents did not respond to requests."
        foreach name [array names gTimeoutAgents] {
            append description "<br>
&nbsp;&nbsp;Host: $name"
        }
        lappend result [list 1 "Agent connectivity." $description "You may want to check the agent logs on the affected machines. Usually restartin the agent will resolve the issue. Please contact Electric Cloud." [list http://www.electric-cloud.com/support support@electric-cloud.com]]
    }

    # Write result
    if {"$::gConfig(outputfile)" != ""} {
        if {[catch {open $::gConfig(outputfile) w} ::gConfig(fd)]} {
            set ::gConfig(fd) ""
        }
    }

    # The header of the report
    if {"$::gConfig(output)" == "text"} {
        printResult "ECCheckEnv Report:\n==================\n" 
    } else {
        printResult "<html>"
        printResult "<header><title>ECCheckEnv Report:</title></header>"
        printResult "<body><h1>ECCheckEnv Report:</h1>" 
        printResult "<hr>" 
    }

    foreach item $result {
        if {"$::gConfig(output)" == "text"} {
            printResult "Test: [stripHtml [lindex $item 1]]" 
            if {[lindex $item 0] == 1} {
                printResult "Problem: [stripHtml [lindex $item 2]]" 
                printResult "Solution: [stripHtml [lindex $item 3]]" 
                if {[llength [lindex $item 4]] > 0} {
                    printResult "Links:"
                    foreach link [lindex $item 4] {
                        printResult "  $link" 
                    }
                }
            } else {
                printResult "Information: [stripHtml [lindex $item 2]]" 
            }
            printResult "------------------\n"
        } else {
            printResult "<h2>Test: [lindex $item 1]</h2>" 
            printResult "<table>" 
            if {[lindex $item 0] == 1} {
                printResult "<tr><td colspan=\"2\">Problem:</td></tr>"
                printResult "<tr><td>&nbsp;&nbsp;</td><td>[lindex $item 2]</td></tr>" 
                printResult "<tr><td colspan=\"2\">Solution:</td></tr>"
                printResult "<tr><td>&nbsp;&nbsp;</td><td>[lindex $item 3]</td></tr>" 
            } else {
                printResult "<tr><td colspan=\"2\">Information:</td></tr>"
                printResult "<tr><td>&nbsp;&nbsp;</td><td>[lindex $item 2]</td></tr>" 
            }
            if {[llength [lindex $item 4]] > 0} {
                printResult "<tr><td colspan=\"2\">Links:</td></tr>"
                foreach link [lindex $item 4] {
                    if {[string match "*@*" $link]} {
                        printResult "<tr><td>&nbsp;&nbsp;</td><td><a href=\"mailto:$link\">$link</a></td></tr>" 
                    } else {
                        printResult "<tr><td>&nbsp;&nbsp;</td><td><a href=\"$link\">$link</a></td></tr>" 
                    }
                }
            }
            printResult "</table>" 
        }
    }

    # The footer of the report
    if {"$::gConfig(output)" == "text"} {
    } else {
        printResult "</body></html>" 
    }

    if {$::gConfig(fd) != ""} {
        close $::gConfig(fd)
    }

    exit 0
}

if {![info exists ::ECLOUD_TEST_HOOK]} {
    if {[catch {main} result]} {
        puts stderr "$result"
        exit 1
    }
}

