#!/bin/sh  
# \
exec oagwish "$0" "$@"

#
# $Log: not supported by cvs2svn $
# Revision 1.3  2005/02/25 15:34:13  shang
# added SF and SD
#
# Revision 1.2  2004/12/15 18:54:06  shang
# updated the action list
#
# Revision 1.1  2004/12/10 16:47:34  shang
# review tool for booster automatic ramp correction, first version
#


set auto_path [linsert $auto_path 0 /usr/local/oag/apps/lib/$env(HOST_ARCH)]
set auto_path [linsert $auto_path 0  /usr/local/oag/lib_patch/$env(HOST_ARCH)]
APSDebugPath

set log ""
set args $argv
APSParseArguments {log}

set logDir /home/helios/oagData/logDaemonData

set CVSRevisionAuthor "\$Revision: 1.4 $ \$Author: shang $"

set args $argv

proc SetStatus {text} {
    global statusText
    set statusText "$text ([clock format [clock seconds] -format %H:%M:%S])"
    update
}

proc APSCheckButtonAndEntryBoxFrame { widget args } {
    global apsContextHelp
    set parent ""
    set noPack 0
    set packOption "-side top"
    set label "NoLabel"
    set buttonList ""
    set variableList ""
    set entryVariableList ""
    set commandList ""
    set orientation vertical
    set allNone 0
    set contextHelp ""
    set relief ridge
    set limitPerRow 0
    set buttonNameList ""
    set gridPack ""
    set width 20
    APSStrictParseArguments {parent noPack packOption label buttonList  variableList orientation allNone commandList  contextHelp relief limitPerRow gridPack width entryVariableList}

    if {$commandList != "" &&
        [llength $buttonList] != [llength $commandList]} {
        puts stderr "commandList must be same length as buttonList"
        return
    }
    if {$contextHelp != ""} {
        set apsContextHelp($parent$widget) $contextHelp    
    }
    if {$orientation == "vertical"} {
        set packside top
        set opackside left
        set oanchor n
        set packOption "$packOption -fill y"
    } else {
        set packside left
        set opackside top
        set oanchor w
        set packOption "$packOption -fill x"
    }
    APSFrame $widget -parent $parent -packOption $packOption -noPack $noPack -label $label -orientation $orientation -relief $relief -gridPack $gridPack
    
    set variableIndex 0
    set buttonNumber 1
    set numberInRow $limitPerRow
    set row 0
    foreach button $buttonList {
        if {$limitPerRow && $numberInRow>=$limitPerRow} {
            set numberInRow 0
            frame $parent$widget.frame.row$row 
            pack $parent$widget.frame.row$row -fill y -fill x -side $opackside  -anchor $oanchor
            set parent1 $parent$widget.frame.row$row
            incr row
        } elseif !$limitPerRow {
            set parent1 $parent$widget.frame
        }
        set cmd [lindex $commandList $variableIndex]
        checkbutton $parent$widget.frame.button$buttonNumber -text $button  -variable [lindex $variableList $variableIndex] -anchor w  -command $cmd
        pack $parent$widget.frame.button$buttonNumber -side $packside -fill x  -in $parent1
        entry $parent$widget.frame.entry$buttonNumber -relief sunken -width $width -textvariable [lindex $entryVariableList $variableIndex]
        pack $parent$widget.frame.entry$buttonNumber -side $packside -fill x  -in $parent1
	lappend buttonNameList $parent$widget.frame.button$buttonNumber
        incr variableIndex
        incr buttonNumber
        incr numberInRow
    }
    if {$allNone} {
        set setBody {
            global $var
	    if {[set $var] == 0} {
            	$buttonName invoke
	    }
        }
        set setCmd [list foreach var $variableList buttonName $buttonNameList $setBody]
        set clrBody {
            global $var
	    if {[set $var] != 0} {
            	$buttonName invoke
	    }
        }
        set clrCmd [list foreach var $variableList buttonName $buttonNameList $clrBody]
        APSButton .all -parent $parent$widget.frame -text All -size small  -command $setCmd
        APSButton .none -parent $parent$widget.frame -text None -size small  -command $clrCmd
    }
}

proc SearchAndDisplayActivity {} {
    global startDay startMonth startYear startHour log
    global stopDay stopMonth stopYear stopHour logDir
    global actionList supply executions

    if [catch {APSConvertTimeToHours $startHour} hour] {
        SetStatus "Invalid starting hour: $startHour"
        return
    }
    if [catch {exec timeconvert \
                 -breakdown=year=$startYear,month=$startMonth,day=$startDay,hour=$hour} startTime] {
        SetStatus "Invalid starting time: $startTime"
        return
    }

    if [catch {APSConvertTimeToHours $stopHour} hour] {
        SetStatus "Invalid stopping hour: $stopHour"
        return
    }
    if [catch {exec timeconvert \
                 -breakdown=year=$stopYear,month=$stopMonth,day=$stopDay,hour=$hour} stopTime] {
        SetStatus "Invalid stopping time: $stopTime"
        return
    }
    
    set fileList  \
      [APSFindFilesBetweenDates -tailsOnly 0 -extensionList {"*"}\
         -directory $logDir/${supply}AutoCorrection \
         -startDateList [APSFormatDate -year $startYear -month $startMonth \
                           -day $startDay -dateFormat list] \
         -endDateList [APSFormatDate -year $stopYear -month $stopMonth \
                         -day $stopDay -dateFormat list] ]
    if ![llength $fileList] {
        SetStatus "Log files for $log not found."
        return
    }
    
    set tmpFile /tmp/[APSTmpString]
    APSAddToTempFileList $tmpFile $tmpFile.sdds
    global actions display
    set option ""
    foreach name [array name actions] {
        if {$actions($name)} {
            if {![llength $option]} {
                set option "-match=column,action=$name"
            } else {
                append option ",action=$name,|"
            }
        }
    }
    set option1 ""
    foreach name [array name executions] {
        if {$executions($name)} {
            if {![llength $option1]} {
                set option1 "-match=column,execution=$name"
            } else {
                append option1 ",execution=$name,|"
            }
        }
    }
    set option2 ""
    set option3 ""
    foreach name {execution TimeStamp user host action description} {
        if {$display($name)} {
            lappend option2 "-parameter=$name"
            if {$name != "TimeStamp"} {
                if {![llength $option3]} {
                    set option3 "-match=column,$name=$display(${name}Text)"
                } else {
                    append option3 ",$name=$display(${name}Text),&"
                }
            }
        }
    }
    set option2 [join $option2 ",end "]
    set option4 "-column=Time,decr"
    
    if [catch {eval exec sddscombine $fileList -merge -pipe=out \
                 | sddsprocess -pipe -filter=column,Time,$startTime,$stopTime \
                 $option $option1 $option3 \
                 | sddssort -pipe $option4 \
                 | sddstimeconvert -pipe -break=column,Time,text=TimeStamp \
                 | sddsexpand -pipe \
                 | tee $tmpFile.sdds \
                 | sddsprintout -pipe=in $tmpFile $option2} result] {
        SetStatus "$result"
        return
    }
    catch {exec sddscollapse $tmpFile.sdds $tmpFile.sdds.1}
    APSFileDisplayWindow [APSUniqueName .] -comment \
      "$log log from $startYear/$startMonth/$startDay@$startHour to $stopYear/$stopMonth/$stopDay@$stopHour" \
      -width 132 -height 20 -deleteOnClose 1 -fileName $tmpFile \
      -sddsExportableFile $tmpFile.sdds.1
}

proc SupplySelectionWidget {widget args} {
    set parent .userFrame
    set menuParent .menu
    APSParseArguments {parent menuParent}
    global supply
    APSLabeledOutput $widget -parent $parent -label "Current supply choice: " \
      -textVariable supply -width 14 \
      -contextHelp "Select a suppy (BM, QF, QD, SF, or SD) from the Supply menu for log review"
    APSMenubarAddMenu .supplychoice -text "Supply" -parent $menuParent
    set w $menuParent.supplychoice.menu
    $w add command -label BM -command "set supply BM"
    $w add command -label QF -command "set supply QF"
    $w add command -label QD -command "set supply QD"
    $w add command -label SF -command "set supply SF"
    $w add command -label SD -command "set supply SD"
}

set supply BM

APSApplication . -name "BRampAutoCorrectionReview" -version $CVSRevisionAuthor \
  -overview "Displays logdaemon entries for the $log log."

set statusText Working...
APSScrolledStatus .status -parent .userFrame -textVariable statusText \
  -width 80

SupplySelectionWidget .supply -parent .userFrame

APSDateTimeAdjEntry .startTime -parent .userFrame \
    -dayVariable startDay -yearVariable startYear \
    -monthVariable startMonth -hourVariable startHour \
    -label "Start date/time: " -twoDigitYear 0 -defaultHour 0
set startHour 0
APSDateTimeAdjEntry .stopTime -parent .userFrame \
    -dayVariable stopDay -yearVariable stopYear \
    -monthVariable stopMonth -hourVariable stopHour \
    -label "Stop date/time: " -twoDigitYear 0 -defaultHour 24
set stopHour 24

set actionList {Error Abort Start End Completed Enable Suspended Resumed NotRunning Failed Normal VcorrectCompleted}
foreach action $actionList {
    set actions($action) 1
    lappend actionVarList actions($action)
}
set execList {VCorrectAndCheck LoadSafetyRamp AutCorrection BControlState SlopeErrorState}
foreach exec $execList {
    set executions($exec) 1
    lappend execVarList executions($exec)
}
pack [frame .userFrame.f1]
APSCheckButtonFrame .actions -parent .userFrame.f1 -label "Search Actions:" -limitPerRow 5 -allNone 1 \
  -orientation horizontal  -buttonList $actionList -variableList $actionVarList  
APSCheckButtonFrame .execs -parent .userFrame.f1 -label "Search Executions:" -allNone 1 -orientation horizontal \
    -buttonList $execList -variableList $execVarList -limitPerRow 3

set display(execution) 1
set display(TimeStamp) 1
set display(user) 1
set display(host) 0
set display(action) 1
set display(description) 1

set display(executionText) *
set display(TimeStampText) *
set display(userText) *
set display(hostText) *
set display(actionText) *
set display(descriptionText) *

pack [frame .userFrame.f2]
APSCheckButtonAndEntryBoxFrame .display -parent .userFrame.f2 \
  -label "Display:" \
  -limitPerRow 1 \
  -allNone 1 \
  -orientation horizontal \
  -buttonList {"TimeStamp   " "User        " "Host        " "Action      " "Execution   " "Description "} \
  -variableList "display(TimeStamp) display(user) display(host) display(action) display(execution) display(description)" \
  -entryVariableList "display(TimeStampText) display(userText) display(hostText) display(actionText) display(executionText) display(descriptionText)"
.userFrame.f2.display.frame.entry3 configure -state disabled -relief ridge


APSButton .search -parent .userFrame -text "Search" \
  -contextHelp \
  "Searches for and displays activity for the system and date/time range of interest." \
  -command SearchAndDisplayActivity

SetStatus Ready.
