#!/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

APSApplication . -name SRUpdateDependentFiles   \
  -overview "SRUpdateDependentFiles runs scripts that update files that depend on the hardware configuration of the storage ring. For example new bpm hardware requires additions to the PV lists in data loggers and SaveCompareRestore request files. Also a change in lattice model requires new steering knobs files."

if {![llength [info commands blt::bgexec]]} {
    package require BLT
}

proc RunConfigPrograms {args} {
    set dependsOn ""
    set latticeDirList ""
    set mode All
    APSStrictParseArguments {dependsOn latticeDirList mode}
    set currDir [pwd]
    eval global $dependsOn $latticeDirList status abort
    set abort 0
    set dependsOnList ""
    foreach item $dependsOn {
        if {[set $item]} {
            lappend dependsOnList $item
        }
    }
    set latticeList ""
    foreach item $latticeDirList {
        if {[set $item]} {
            lappend latticeList $item
        }
    }
    global config
    set commandList ""
    set directoryList ""
    set pages [llength $config(Column.Script)]
    for {set page 0} {$page < $pages} {incr page} {
        set rows [llength [lindex $config(Column.Script) $page]]
        for {set i 0} {$i < $rows} {incr i} {
            set needed 0
            foreach dependsOnItem $dependsOnList {
                if {[lindex [lindex $config(Column.DependsOn$dependsOnItem) $page] $i]} {
                    set needed 1
                    break
                }
            }
            if {$needed} {
                set workingDirectory [lindex [lindex $config(Column.WorkingDirectory) $page] $i]
                if {[lindex [lindex $config(Column.LoopOverLattices) $page] $i]} {
                    foreach lattice $latticeList {
                        set command [lindex [lindex $config(Column.Script) $page] $i]
                        set index [lsearch -exact $command "<lattice>"]
                        set command [lreplace $command $index $index $lattice]
                        lappend commandList $command
                        lappend directoryList $workingDirectory
                    }
                } else {
                    set command [lindex [lindex $config(Column.Script) $page] $i]
                    lappend commandList $command
                    lappend directoryList $workingDirectory
                }
            }
        }
    }
    if {$commandList == ""} {
        APSSetVarAndUpdate status "No scripts to run."
        return
    }
    switch -exact [string tolower $mode] {
        all {
            foreach command $commandList dir $directoryList {
                cd $dir
                if [catch {RunProgram -command $command} results] {
                    APSSetVarAndUpdate status "$results"
                    return
                }
            }
        }
        selected {
            set newCommandList [APSChooseItemFromList \
                                  -name "Script Selection" \
                                  -itemList $commandList \
                                  -returnList $commandList \
                                  -multiItem 1 ]
            if {$newCommandList==""} {
                APSSetVarAndUpdate status "No Script selected!"
            }
            foreach command $newCommandList {
                set index [lsearch -exact $commandList $command]
                set dir [lindex $directoryList $index]
                cd $dir
                if [catch {RunProgram -command $command} results] {
                    APSSetVarAndUpdate status "$results"
                    return
                }
            }
        }
    }
    APSSetVarAndUpdate status Done
    cd $currDir
}

proc RunProgram {args} {
    set command ""
    APSStrictParseArguments {command}
    global status abort output errorOutput
    # The value of abort is changed to 1 when abort button is pressed.
    # However the variable may have the value of the return expression of the
    # previous blt::bgexec command if the abort button was never pressed, 
    # so we should ignore that case.
    if [string equal $abort 1] {
        return -code error "Aborted"
    }
    APSSetVarAndUpdate status "Running \"$command\""
    APSWaitWithUpdate -waitSeconds 1
    set errorOutput ""
    if [catch {eval blt::bgexec abort -output output -error errorOutput $command} results] {
        if [string length $errorOutput] {
            set width [expr 2 + [string length "Standard error output from $command"]]
            APSInfoWindow .info -width $width \
              -name "Standard error output from $command" -infoMessage "$errorOutput" -modal 1
        }
        return -code error "$results"
    }
}

set latticeDir /home/helios/oagData/sr/lattices
set names [APSSRFindLattices]
set latticeDirList ""
foreach name $names {
    lappend latticeDirList $name
    set $name 0
}

set [file tail [file readlink $latticeDir/default]] 1

if {[catch {sdds load /home/helios/oagData/sr/startupScripts/config.sdds config} results]} {
    catch {puts stderr "error: $results"}
    exit
}

set dependsOnList ""
foreach name $config(ColumnNames) {
    if {[string range $name 0 8] == "DependsOn"} {
        lappend dependsOnList [string range $name 9 end]
        set $name 0
    }
}

set status "Default lattice is [file tail [file readlink $latticeDir/default]]"
APSScrolledStatus .status -parent .userFrame -textVariable status -width 81
set status "Ready..."


pack [frame .userFrame.f1]
APSCheckButtonFrame .dependsOnList -parent .userFrame.f1 -label "Select items which have changed" -variableList $dependsOnList -buttonList $dependsOnList -packOption "-side left"

APSCheckButtonFrame .latticeSubDir -parent .userFrame.f1 -label "Lattice Sub-Directory" -variableList $latticeDirList -buttonList $latticeDirList -packOption "-side left"

APSButton .run -parent .userFrame -text "Run" -command {RunConfigPrograms -dependsOn $dependsOnList -latticeDirList $latticeDirList}

APSButton .runRestart -parent .userFrame -text "Run Selected..." \
  -command {RunConfigPrograms -mode selected -dependsOn $dependsOnList \
              -latticeDirList $latticeDirList} \
  -contextHelp "Brings up a list of scripts that should be run given the above widget selections. One select a smaller set of scripts, useful if recovering from errors."

APSButton .abort -parent .userFrame -text "Abort" -command {set abort 1}

