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

#
# $Log: not supported by cvs2svn $
# Revision 1.17  2007/02/07 23:17:57  shang
# added path of the source file for displaying in the status window.
#
# Revision 1.16  2007/02/07 23:11:43  shang
# modified to display the source file and complete action in the status window when double-clickes on an listed item.
#
# Revision 1.15  2004/08/20 21:37:42  shang
# replaced the file display window for SCR activity review by scrolled window and
# the restored pv and values will be displayed if an restore item is double-clicked.
#
# Revision 1.14  2003/07/18 23:15:59  borland
# Modified the editing sequence that makes the ShortHost column so that
# it works properly when there are several words after the hostname.
#
# Revision 1.13  2002/07/09 15:56:00  shang
# modified to use the log files that are named by dates (saves the searching time)
#
# Revision 1.12  2002/01/31 18:49:50  emery
# Increased format for file in sddsprintout.
#
# Revision 1.11  2002/01/31 17:56:51  emery
# Changed all button defaults to no.
#
# Revision 1.10  2002/01/31 17:54:38  emery
# Replaced action type preferred with install.
#
# Revision 1.9  2000/09/08 13:37:32  borland
# Changed matching condition for actions from <pattern>* to *<pattern>*.
#
# Revision 1.8  2000/06/14 19:47:35  borland
# Now sort the data after filtering to be sure it is in time order.
#
# Revision 1.7  1999/06/16 14:30:11  borland
# Now picks events using a wildcard at the end to catch, e.g.,
# restore-start and restore-end using restore*.
#
# Revision 1.6  1999/04/19 14:28:25  borland
# Now looks for .gz files as well as normal files in save area.
#
# Revision 1.5  1999/02/22 18:32:22  borland
# Added "Preferred" action type.
#
# Revision 1.4  1997/05/02 17:04:25  borland
# Added commandline option to allow retargeting to use a different SCR
# directory.
#
# Revision 1.3  1997/04/24 20:06:37  borland
# Added "alter" and "export" categories for filtering actions.  Added exportable
# SDDS file to file display window.
#
# Revision 1.2  1997/03/20 15:16:50  borland
# Now searches back through all available SCRAudit files.
#
# Revision 1.1  1997/02/28 18:30:52  borland
# 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)]
set apsttk 1
#APSDebugPath

set logDir /home/helios/oagData/logDaemonData/SCRAudit
set restoreTrackDir /home/helios/oagData/SCR/restoreTracking

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

set topDirectory ""
set args $argv
APSStrictParseArguments {topDirectory}
APSSCRDefineVariables -topDirectory $topDirectory

proc SetStatus {text} {
    global statusText
    set statusText "$text ([exec date +%H:%M:%S])"
    update
}

lappend actionList Save Compare Review Restore Remove Alter Export Install
proc SearchAndDisplayActivity {} {
    global startDay startMonth startYear startHour
    global stopDay stopMonth stopYear stopHour
    global apsSCRSystem logDir
    global actionList

    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
    }

    SetStatus "Searching for system $apsSCRSystem"

    set filterList -filter=column,Time,$startTime,$stopTime 
    lappend filterList "-match=column,File=$apsSCRSystem\[12\]*"
    foreach action $actionList {
        global show$action
        if ![subst \$show$action] {
            lappend filterList -match=column,Action=*[string tolower $action]*,!
        }
    }
    set fileList  \
      [APSFindFilesBetweenDates -tailsOnly 0 -extensionList {"*"}\
         -directory $logDir \
         -startDateList [APSFormatDate -year $startYear -month $startMonth \
                           -day $startDay -dateFormat list] \
         -endDateList [APSFormatDate -year $stopYear -month $stopMonth \
                         -day $stopDay -dateFormat list] ]
    set fileList1 [APSFindFilesBetweenDates -tailsOnly 0 -extensionList {"*"}\
         -directory /net/phoebus/oagmgr/logDaemonData.helium/SCRAudit \
         -startDateList [APSFormatDate -year $startYear -month $startMonth \
                           -day $startDay -dateFormat list] \
         -endDateList [APSFormatDate -year $stopYear -month $stopMonth \
                         -day $stopDay -dateFormat list] ]
    
    set fileList [concat $fileList $fileList1]
    if ![llength $fileList] {
        SetStatus "SCR audit files not found!"
        return
    }
    set tmpFile /tmp/[APSTmpString]
    APSAddToTempFileList $tmpFile $tmpFile.sdds
    if [catch {eval exec sddscombine $fileList -merge -pipe=out \
                 | sddsprocess -pipe $filterList \
                 | sddssort -pipe -column=Time \
                 | sddstimeconvert -pipe \
                 -break=column,Time,year=Year,month=Month,day=Day,hour=TimeOfDay \
                 | sddsprocess -pipe \
                 {"-define=column,Hour,TimeOfDay int,type=short"} \
                 {"-define=column,Min,TimeOfDay Hour - 60 * int,type=short"} \
                 {"-define=column,Sec,TimeOfDay Hour - 60 * Min - 60 * int,type=short"} \
                 {"-print=column,TimeStamp,%04hd/%02hd/%02hd %02hd:%02hd:%02hd,Year,Month,Day,Hour,Min,Sec"} \
                 {"-edit=column,ShortScript,Script,100Z/"} \
                 {"-edit=column,ShortHost,Host,1D1F10D"} \
                 | tee $tmpFile.sdds \
                 | sddsprintout -pipe=in $tmpFile \
                 -column=TimeStamp -column=User,format=%10s -column=ShortHost,format=%10s,label=Hostname \
                 -column=File,format=%40s -column=Action,format=%15s \
                 -column=ShortScript,format=%20s,label=Script  } result] {
        SetStatus "$result"
        return
    }
    if [catch {exec sddsprocess $tmpFile.sdds -pipe=out \
                 "-print=col,NewCol,%s %10s %10s %40s %15s %20s,TimeStamp,User,ShortHost,File,Action,ShortScript" \
                 | sdds2stream -pipe -col=NewCol} combinedList] {
        SetStatus "$combinedList"
        return
    }
    
    listSCRMatch -combinedFile $tmpFile.sdds
}

proc SortRestoreTrackingFiles {args} {
    set fileList ""
    APSParseArguments {fileList}
    
    set newList ""
    foreach file $fileList {
        if [regexp {_(.*)} $file a b] {
            lappend newList $b
        } else {
            return -code error "Invalid restore tracking file format: $file"
        }
    }
    if [catch {exec sddsmakedataset -pipe=out -defaultType=string -col=Filename \
                 -data=[join $fileList ,] \
                 -col=Restoretime -data=[join $newList ,] \
                 | sddssort -pipe -col=Restoretime,decreasing \
                 | sdds2stream -pipe -col=Filename} newFileList] {
        SetStatus "$newFileList"
        return -code error "$newFileList"
    }
    return [join $newFileList]
}



proc listSCRMatch {args} {
    set combinedFile ""
    APSParseArguments {combinedFile}
    global Selections subStringFilter
    if [catch {exec sddsprocess $combinedFile -pipe=out \
                 "-print=col,NewCol,%19s %10s %10s %40s %15s %20s,TimeStamp,User,ShortHost,File,Action,ShortScript" \
                 | sdds2stream -pipe -col=NewCol} combinedList] {
        return -code error $combinedList
    }
    regsub -all \" $combinedList "" combinedList
    set label "[format %19s TimeStamp] [format %10s User] [format %10s ShortHost] [format %40s File] [format %15s Action] [format %20s ShortScript]"
    
    set combinedList [split $combinedList \n]
    set displayList ""
    foreach item $combinedList {
        if {($subStringFilter == "") || ([string first [string tolower $subStringFilter] [string tolower $item]] != -1)} {
            lappend displayList $item
        }
    }
    set windowName .[APSTmpString]
    
    APSScrolledListWindow $windowName -name "SCR Review" -label "$label" -mouseClickCallback SCRRestoreReview \
      -itemList $displayList -acceptButton 0 -printButton 1
      
}

proc SCRRestoreReview {item doubleClick} {
    global apsSCRSystem restoreTrackDir
    if {!$doubleClick} return
   # SetStatus "$item"
    set itemList [join $item]
    set date [lindex $itemList 0]
    set timeStamp [lindex $itemList 1]
    set sourceFile [lindex $itemList 4]
    set action [lrange $itemList 5 end]
    
    set dir /home/helios/oagData/SCR/snapshots/$apsSCRSystem
    SetStatus "Action occurred on $date $timeStamp: $dir/$sourceFile $action"
    if ![string match "restore*" $action] {
        bell
        return
    }
    regsub .gz $sourceFile "" sourceFile
    set directory $restoreTrackDir/$apsSCRSystem
    set dateList [split $date /]
    set year [lindex $dateList 0]
    set month [lindex $dateList 1]
    set day [lindex $dateList 2]
    set restoredTime [clock scan "$month/$day/$year $timeStamp"]
    set fileList [glob -nocomplain $directory/${sourceFile}*]
    if ![llength $fileList] {
        SetStatus "No record found in SCR restore tracking directory for $action!"
        bell
        return
    }
    set newList ""
    foreach file $fileList {
        lappend newList [file tail $file]
    }
    set fileFound 0
    #found files in +- 5 seconds range (assume the time difference in logAction and restore tracking of SCR)
    for {set diff -5} {$diff<=5} {incr diff} {
        set time [expr $restoredTime + $diff]
        set date [clock format $time -format "%Y-%j-%m%d-%H%M%S"]
        set file ${sourceFile}_${date}.gz
        if [lsearch -exact $newList $file]>=0 {
            set fileFound 1
            break
        }
    }

    if !$fileFound {
        SetStatus "No record found in SCR restore tracking directory for $action occurred on $date $timeStamp!"
        bell
        return
    }
    set tmpfile /tmp/[APSTmpString]
    if [catch {exec sddsprintout $directory/$file $tmpfile -par=System -par=User \
                 "-par=SourceFile,label=\nRestored from" \
                 "-par=TimeStamp,label=\nRestored Time" \
                 -col=ControlName,format=%30s -col=ValueString -nowarnings} result] {
        SetStatus "$result"
        return
    }
    set w .[APSUniqueName printout]
    APSFileDisplayWindow $w -fileName $tmpfile -width 80 -printCommand "enscript -r" \
      -deleteOnClose 1 -height 30 -sddsExportableFile $directory/$file
   
}


APSApplication . -name SCRActivityReview -version $CVSRevisionAuthor \
  -overview "Displays activity data for the SCR system, showing the date, time, and account for saves, restores, compares, etc."

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

APSSCRSystemChoiceWidget .choice -parent .userFrame -variable apsSCRSystem 

set subStringFilter ""
APSLabeledEntry .subsearch -parent .userFrame -label "Substring filter:" -textVariable subStringFilter -width 40


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


APSFrame .actionSel -parent .userFrame -label "SCR Action Selections" 
foreach action $actionList {
    set show$action 0
    APSRadioButtonFrame .show$action -parent .userFrame.actionSel.frame \
      -orientation vertical -packOption "-side left" \
      -variable show$action \
      -label $action -buttonList "Yes No" -valueList "1 0" -contextHelp \
      "Selects whether to show [string tolower $action] actions or not."
}

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


SetStatus Ready.
