#!/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)]
APSStandardSetup
global apsScriptHost

set version 1.0
APSApplication . -name "SRSetDefaultLattice" -version 1.0 \
  -overview "Allows re-linking the default lattices is various oagData sr directories."

set status "Ready."

set dataDir [file dir $OAGGlobal(SRLatticesDirectory)]
# some of these we may never use, like etax etay correction since LOCO will handle that.
set directoryList {lattices \
    orbitControllaw/lattices \
    rfOrbitControllaw/lattices \
    fastOrbitFeedback/lattices \
    latticeFunctionCorrection/beta/lattices \
    latticeFunctionCorrection/etay/lattices \
    latticeFunctionCorrection/etax/lattices \
    calibratedModels/lattices \
    calibratedModels/LOCOMatrices \
    knobs/IDbump/lattices \
    knobs/chrom/lattices \
    knobs/localBumps/lattices \
    knobs/orbit/lattices \
    knobs/skew/lattices \
    knobs/tune/lattices \
    }

proc GetPresentLattice {} {
    global PresentLattice OAGGlobal
    cd $OAGGlobal(SRLatticesDirectory)
    if [catch { file tail [file readlink default] } PresentLattice ] {
        APSSetVarAndUpdate status "Error with GetPresentLattice: $PresentLattice"
        incr errors
    }
}

proc ChangeDefault {newLattice} {
    global dataDir directoryList env opList OAGGlobal apsScriptHost
    set errors 0
    foreach dir $directoryList {
	#--- Change calibratedModels link only for operational lattices:
	if {[string first calibratedModels $dir] != -1 && [lsearch -exact $opList $newLattice] == -1} { continue }
        cd $dataDir/$dir
        if {[file exists default]} {
            if [catch {file tail [file readlink default] } oldLattice] {
                APSSetVarAndUpdate status "Error with ChangeDefault: $oldLattice"
                incr errors
            }
        } else {
            set oldLattice none
        }
        if [catch {exec logMessage -sourceId=defaultLatticeAudit \
                       -tag=Directory $dataDir/$dir \
                       -tag=OldLattice $oldLattice \
                       -tag=NewLattice $newLattice -tag=Application SRSetDefaultLattice \
                       -tag=User $env(USER) -tag=Host $apsScriptHost -tag=Action Start} result] {
            APSSetVarAndUpdate status "Error with logMessage start: $result"
            incr errors
        }
        if {[file exists default]} {
            set oldLattice [file tail [file readlink default]]
            if {[catch {exec rm default 
                exec ln -s $newLattice default} result]} {
                APSSetVarAndUpdate status "Couldn't make link to $newLattice in directory $dir\n$result"
                incr errors
            }
        } else {
            set oldLattice none
            if {[catch {exec ln -s $newLattice default} result]} {
                APSSetVarAndUpdate status "Couldn't make link to $newLattice in directory $dir\n$result"
                incr errors
            }
        }
        if [catch {exec logMessage -sourceId=defaultLatticeAudit \
                       -tag=Directory $dataDir/$dir \
                       -tag=OldLattice $oldLattice \
                       -tag=NewLattice $newLattice -tag=Application SRSetDefaultLattice \
                       -tag=User $env(USER) -tag=Host $apsScriptHost -tag=Action Finish} result] {
            APSSetVarAndUpdate status "Error with logMessage finish: $result"
            incr errors
        }
        cd $dataDir/$dir
        if ![file exists $newLattice] {
            exec mkdir -p $newLattice
            file attributes $newLattice -permissions 0775
            set aclDirFile $OAGGlobal(SRLatticesDirectory)/dirs.acl    
#            if [regexp {Linux} $env(HOST_ARCH)] {
#                catch {exec setfacl -M $aclDirFile $newLattice}
#            } else {
#                catch {exec setfacl -f $aclDirFile $newLattice}
#            }
        }
    }
    if {!$errors} {
       APSSetVarAndUpdate status "Re-links of default lattice directories to $newLattice successful.\nReady." 
    }
    GetPresentLattice
    return
}

proc CheckLinks {args} {
    global dataDir directoryList
    APSSetVarAndUpdate status "Checking links..."
    foreach dir $directoryList {
        set lattice [file tail [file readlink $dataDir/$dir/default]]
        APSSetVarAndUpdate status "[format %-45s $dir:] $lattice"
    }
    APSSetVarAndUpdate status "Done."
    return
}

proc CreateLatticeWidget {args} {
    set parent ""
    set latticeList ""
    APSParseArguments {parent latticeList}

    APSFrameGrid .buttonList -parent $parent -xList {x1 x2}
    set buttonParent(1) $parent.buttonList.x1
    set buttonParent(2) $parent.buttonList.x2
    set i 1
    foreach item $latticeList {
        if {$i > 2} {
            set i 1
        }
        regsub -all {\.} $item "point" latticeButton
        set latticeButton [string tolower $latticeButton]
        APSButton .$latticeButton -parent $buttonParent($i) -text "->[format %20s $item]" \
          -packOption {-side top} \
          -command "ChangeDefault $item; GetPresentLattice" \
          -contextHelp "Changes the SR default lattice $item.  N.B.: you must stop and restart orbit correction, steering, lattice function corrections to complete this."
        incr i
    }
}

set status Working...
APSScrolledStatus .status -parent .userFrame -textVariable status \
    -width 70 -height 8 -packOption "-fill x"

APSLabeledOutput .presentLattice -parent .userFrame \
  -label "Present Lattice: " \
  -textVariable PresentLattice \
  -contextHelp "The presently selected SR lattice." \

APSButton .checkLinks -parent  .userFrame \
  -text "Check All Links" \
  -packOption "-side top" \
  -command {CheckLinks; GetPresentLattice} \
  -contextHelp "Reads out the links of default lattice directories."

GetPresentLattice

cd $OAGGlobal(SRLatticesDirectory)
set operationList [exec sdds2stream -col=LatticeName operationalLattices.sdds]
set latticeList [APSSRFindLattices]
set opList ""
set otherList ""
foreach lattice $operationList {
    if [lsearch $latticeList $lattice]>=0 {
        lappend opList $lattice
    }
}
foreach lattice $latticeList {
    if [lsearch $operationList $lattice]<0 {
        lappend otherList $lattice
    }
}

set widgetList [APSTabFrame .tab -parent .userFrame -label "" -labelList {"Recent Lattices" "Others Lattices"} \
                  -height 450 -width 800]
set w1 [lindex $widgetList 0]
set w2 [lindex $widgetList 1]

CreateLatticeWidget -parent $w1 -latticeList $opList
CreateLatticeWidget -parent $w2 -latticeList $otherList

set status Ready.
update

# Local Variables:
# mode: tcl
# End:
