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

# $Log: not supported by cvs2svn $
# Revision 1.7  2005/03/17 20:09:27  emery
# Added canted undulator P0 steering choices.
#
# Revision 1.6  2004/09/24 03:23:24  emery
# Added button "Run Selected..." which will allow the selection of a smaller
# set of scripts.  Useful if recovering from an error during the
# execution of "Run".
#
# Revision 1.5  2003/10/14 17:23:29  soliday
# The error message from RunProgram is always displayed now.
#
# Revision 1.4  2003/09/25 18:39:32  soliday
# Added BLT line.
#
# Revision 1.3  2002/05/22 17:46:02  emery
# Use APSSRFindLattices to find lattices directories.
#
# Revision 1.2  2000/10/31 02:27:08  emery
# Added a info window when an error is reported.
#
# Revision 1.1  2000/10/28 08:48:24  emery
# First installation. Written by B. Soliday
#
#

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.8 $ \$Author: soliday $"
APSApplication . -name SRUpdateDependentFiles -version $CVSRevisionAuthor  \
  -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 local bump matrices."

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

proc RunConfigPrograms {args} {
    set dependsOn ""
    set latticeDirList ""
    set steeringTypeList ""
    set mode All
    APSStrictParseArguments {dependsOn latticeDirList steeringTypeList mode}
    set currDir [pwd]
    eval global $dependsOn $latticeDirList $steeringTypeList 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
        }
    }
    set steeringList ""
    foreach item $steeringTypeList {
        if {[set $item]} {
            lappend steeringList $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 {
                        if {[lindex [lindex $config(Column.LoopOverSteeringTypes) $page] $i]} {
                            foreach steering $steeringList {
                                set command [lindex [lindex $config(Column.Script) $page] $i]
                                set index [lsearch -exact $command "<steeringType>"]
                                set command [lreplace $command $index $index $steering]
                                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]
                            set index [lsearch -exact $command "<lattice>"]
                            set command [lreplace $command $index $index $lattice]
                            lappend commandList $command
                            lappend directoryList $workingDirectory
                        }
                    }
                } else {
                    if {[lindex [lindex $config(Column.LoopOverSteeringTypes) $page] $i]} {
                        foreach steering $steeringList {
                            set command [lindex [lindex $config(Column.Script) $page] $i]
                            set index [lsearch -exact $command "<steeringType>"]
                            set command [lreplace $command $index $index $steering]
                            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 steeringTypeList "CUUSP0 CUDSP0 P0 P1 P2 AM BM"
foreach name $steeringTypeList {
    set $name 1
}

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"

APSCheckButtonFrame .steeringTypeList -parent .userFrame.f1 -label "Steering Type" -variableList $steeringTypeList -buttonList $steeringTypeList -packOption "-side left" \
  -contextHelp "Select which steering type to re-generate steering matrices.\n\nCUUSP0: Canted undulator upstream P0 steering\nCUDSP0: Canted undulator downstream P0 steering\nP0: Regular P0 steering\nBM: BM source point steering\nAM: AM source point steering."

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

APSButton .runRestart -parent .userFrame -text "Run Selected..." \
  -command {RunConfigPrograms -mode selected -dependsOn $dependsOnList \
              -latticeDirList $latticeDirList \
              -steeringTypeList $steeringTypeList} \
  -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}

