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




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 CVSRevisionAuthor "\$Revision: 1.2 $ \$Author: shang $"

APSApplication . -name SRConfigChangeHistory -version $CVSRevisionAuthor \
  -overview "Prints out the orbit correction configurations that were linked to the\
   default configuration in the range of dates specified. "

set dataDir /home/helios/oagData/logDaemonData/UpdateSoftLinkAudit
#set dataDir /home/oxygen/SHANG/test/logd/UpdateSoftLinkAudit
set resDataDir /home/helios/oagData/logDaemonData

set statusText "Ready..."
APSScrolledStatus .status -parent .userFrame -textVariable statusText -width 60 \
  -contextHelp "Displays processing information." 
update

proc InitViewTime {args} {
    global buttList statusText fileList 
    global printoutString dataDir
    global StartYear StartMonth StartDay StartHour
    global EndYear EndMonth EndDay EndHour Configuration
    
    set type standard
    #three types: standard, DP, and RTFB
    APSParseArguments {type}
    set intervalString "$StartMonth/$StartDay/$StartYear $StartHour and $EndMonth/$EndDay/$EndYear $EndHour"
    set fileList ""
    set tempFile /tmp/[APSTmpString]
    set statusText "Working..."
    update
    
    if {![info exist Configuration] || ![string length $Configuration]} {
        set statusText "Please select a default configuration first."
        return
    }
    #This is in the case of hour selection in format 0:00:00
    set sHour [APSConvertTimeToHours ${StartHour}] 
    set eHour [APSConvertTimeToHours ${EndHour}]
    set lowLimit [exec timeconvert -breakDown=year=${StartYear},month=${StartMonth},day=${StartDay},hour=$sHour]
    set highLimit [exec timeconvert -breakDown=year=${EndYear},month=${EndMonth},day=${EndDay},hour=$eHour]
    
    if {$lowLimit >= $highLimit} {
        set statusText "Wrong time frame selection!"
        return
    }
    set processFileList \
      [APSFindFilesBetweenDates -tailsOnly 0 -extensionList {"*"}\
         -directory $dataDir \
         -startDateList [APSFormatDate -year $StartYear -month $StartMonth \
                           -day $StartDay -dateFormat list] \
         -endDateList [APSFormatDate -year $EndYear -month $EndMonth \
                         -day $EndDay -dateFormat list] ]
    if [llength $processFileList] {
        catch {eval exec sddscombine $processFileList -pipe=out -merge \
                 | sddsprocess -pipe -noWarnings \
                 -filter=column,Time,${lowLimit},${highLimit} \
                 | tee $tempFile.1 \
                 | sddsprocess -pipe -noWarnings -match=column,Link=*${Configuration} \
                 | tee $tempFile.2 \
                 | sddstimeconvert -pipe=in $tempFile  \
                 -breakdown=col,Time,text=InstallTime  } result
    } else {
        set statusText "No data for the chosen range of time."
        bell
        return
    }
    set rows [exec sdds2stream -rows=bar $tempFile]
    if !$rows {
        set statusText "No references found for $Configuration for the chosen range of time."
        return
    }
    global  referenceList mainDir
    set refList [join [exec sdds2stream -col=NewFile $tempFile]]
   # set oldDir [pwd]
   #cd $mainDir
   # set link [file readlink $Configuration]
   # cd $oldDir
   # lappend referenceList $link
    set referenceList ""
    foreach refer $refList {
        if [file exist $mainDir/$refer] {
            lappend referenceList $refer
        }
    }
    if ![llength $referenceList] {
        set statusText "No existing references found for $Configuration for the chosen range of time."
        return
    }
    global reference
    set reference ""
    APSScrolledListWindow .process -name "Select reference of $Configuration" \
      -label "Select a reference of $Configuration" \
      -itemList $referenceList -selectionVar reference
    tkwait variable reference
    if ![string length $reference] {
        set statusText "No reference selected."
        return
    }
    Compare 
    tkwait variable reference
    Compare
}

set mainDir /home/helios/oagData/sr/orbitControllaw/lattices/default
proc Compare {args} {
    global reference Configuration mainDir referenceList
    set tmpRoot /tmp/[APSTmpString]
    set fid [open $tmpRoot.print "w"]
    puts $fid "Compare $Configuration configs with reference $reference"
    puts $fid ""
    foreach config $referenceList {
        if {[string compare $config $reference]==0} {
            continue
        }
        if [catch {exec sddsselect $mainDir/$config/config $mainDir/$reference/config \
                     -match=Name -invert $tmpRoot.1} result] {
            return -code error "Compare1: $result"
        }
        if [catch {exec sddscombine $tmpRoot.1 -merge $tmpRoot.added -overwrite} result] {
            return -code error "Compare2: $result"
        }
        if [catch {exec sddsselect $mainDir/$reference/config $mainDir/$config/config \
                     -match=Name -invert $tmpRoot.2} result] {
            return -code error "Compare3: $result"
        }
        if [catch {exec sddscombine $tmpRoot.2 -merge $tmpRoot.removed -overwrite} result] {
            return -code error "Compare4: $result"
        }
        set rowsRemoved [exec sdds2stream -rows=bar $tmpRoot.removed]
        set rowsAdded [exec sdds2stream -rows=bar $tmpRoot.added]
        
        puts $fid "$config "
        if {!$rowsRemoved && !$rowsAdded} {
            puts $fid "Two configurations are the same, no BPMs or correctors were added or removed."
        } else {
            if {$rowsRemoved} {
                puts $fid "Removed: [join [exec sdds2stream -col=Name $tmpRoot.removed]]."
            } else {
                puts $fid "No BPMs or correctors were removed."
            }
            
            if {$rowsAdded} {
                puts $fid "Added: [join [exec sdds2stream -col=Name $tmpRoot.added]]."
            } else {
                puts $fid "No BPMs or correctors were added."
            }
            puts $fid ""
        }
    }
    close $fid
    set w .[APSUniqueName printout]
    APSFileDisplayWindow $w -fileName $tmpRoot.print -width 80 -printCommand "enscript -r" -width 80
}
# makes frame for date/time selection widgets (for range
# of dates to process)

proc MakeDateTimeFrame {widget args} {
    set parent .

    APSStrictParseArguments {parent}

    set label "Date/Time Range of Interest"

    APSFrame $widget -parent $parent -label $label

    set w $parent$widget.frame

    APSDateTimeAdjEntry .startDate -parent $w \
      -yearVariable StartYear \
      -monthVariable StartMonth \
      -dayVariable StartDay \
      -hourVariable StartHour \
      -label "Starting date/time (year, month, day, hour): " \
      -defaultHour 0 \
      -command ResetMonDataFileList
    APSDateTimeAdjEntry .endDate -parent $w \
      -yearVariable EndYear \
      -monthVariable EndMonth \
      -dayVariable EndDay \
      -hourVariable EndHour \
      -label "Ending date/time (year, month, day, hour):   " \
      -defaultHour 24 \
      -command ResetMonDataFileList

    SetDateTimeToToday -rootname Start -hour 0
    SetDateTimeToToday -rootname End  -hour 24
}

proc SetDateTimeToToday {args} {
    set rootname ""
    set hour 0

    ResetMonDataFileList
    APSStrictParseArguments {rootname hour}

    global ${rootname}Month ${rootname}Year ${rootname}Day ${rootname}Hour
    
    APSDateBreakDown -dayVariable ${rootname}Day -yearVariable ${rootname}Year \
      -monthVariable ${rootname}Month -twoDigitYear 0 -leadingZeros 0
    set ${rootname}Hour $hour
}

proc ResetMonDataFileList {} {
    global DataFileList 

    set DataFileList " "
    update
}

MakeDateTimeFrame .timeFrame -parent .userFrame  

set configList {h.default h.defaultXR h.defaultDP h.defaultXRDP v.default v.defaultXR v.defaultDP v.defaultXRDP}

APSComboboxFrame .cong -parent .userFrame -label "Select default configuration:" \
            -width 30 -textVariable  Configuration \
            -itemList "$configList"


APSButton .view -parent .userFrame -text "ViewAndCompare" -packOption "-side left" \
  -command InitViewTime -contextHelp \
  "Invokes data analysis from UpdateSoftLinkAudit log files for the chosen\
     plane in the selected time frame." 
