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

# $Log: not supported by cvs2svn $
# Revision 1.7  2008/02/06 18:23:34  soliday
# Removed calls to setfacl because it is no longer needed.
#
# Revision 1.6  2008/01/22 16:10:08  soliday
# Put setfacl commands inside catch statement.
#
# Revision 1.5  2006/10/19 21:21:55  emery
# Added -noWarning to sddsprocess that created lists of
# CH1 correctors that are not under CPMSI control.
# An empty list was returned which caused the script ot
# exit with an error. Now an empty list will
# not cause an exception.
#
# Revision 1.4  2005/09/30 20:39:43  emery
# Indented exit commands from last change.
# Added sedtfacl -m mask:rwx command for new config files.
#
# Revision 1.3  2005/09/30 20:20:45  shang
# replaced "return -code error" by "puts stderr" and "exit", and modified
# to avoid overwriting input files which caused writing permission problem.
#
# Revision 1.2  2005/09/30 19:41:37  shang
# added catch statements
#
# Revision 1.1  2005/08/22 19:57:36  emery
# First version of the script makeConfig under the new name of
# makeLocalSteeringConfigs. The CVS log under the old name is
# retained in the header.
#

# These are the log comments from the time this script
# was called makeConfigs.
# Revision 1.12  2005/08/22 19:53:13  emery
# Fixed the logic of the "if" statement for CU type steering.
# All non-CU cases were skipped.
#
# Revision 1.11  2005/04/12 09:13:49  emery
# Split a catch statement into two.
#
# Revision 1.10  2005/04/06 06:14:15  emery
# Added setting Flag to 1 for CU configurations, so that the
# correctors won't be removed when creating rmFF files.
#
# Revision 1.9  2005/04/05 20:46:18  emery
# Adds CU magnets to local correction configuration if the magnet
# is in datapool.
#
# Revision 1.8  2005/03/17 19:58:27  emery
# Added canted undulator steering configurations.
#
# Revision 1.7  2005/03/16 21:47:01  emery
# Replaced filemkdir with exec mkdir so that the acl gets transfered.
#
# Revision 1.6  2004/03/12 17:36:27  emery
# Uncommented file delete statement for *~ files.
#
# Revision 1.5  2003/10/20 01:23:16  emery
# Removed if statement which allowed only the P2 steering to benefit
# from the corrector substitution code. Now corrector substitution
# can work for all steerings.
#
# Revision 1.4  2003/10/09 17:04:21  emery
# Added -reuse=page option for sddsselect invert of the
# bad bpms. Previously no bad bpms would have been removed
# without this option.
#
# Revision 1.3  2003/02/26 01:20:33  emery
# Added temporary file as thrid file argument to sddsselect and used a
# copy to update the first argument file.
#
# Revision 1.2  2001/02/02 16:04:40  emery
# Uncommented file delete statement for *~ files.
#
# Revision 1.1  2000/10/27 02:09:21  emery
# First installation.
#

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 usage "makeConfigs -steeringType {CUUSP0|CUDSP0|P0|P1|AM|BM|P2} \[-sourceList <sectorNumberList>\]"
set args $argv
set steeringType ""
set sourceList ""
APSStrictParseArguments {steeringType sourceList}

if ![string length $steeringType] {
    puts stderr $usage
    exit
}
# base directory for creating configugaritons
set configDir /home/helios/oagData/sr/localSteering/configs
set xrefDir /home/helios/oagData/sr/lattices/scripts
set orbCorrDir /home/helios/oagData/sr/orbitControllaw/lattices/default/
set statusDir /home/helios/oagData/sr/BPMStatus

# Any new C:H1 is ok for steering, even if they are not in datapool.
if [catch {exec sddsprocess $statusDir/config.sdds -pipe=out \
             -filter=col,NonexistentH,1,1 \
             | sddsconvert -pipe=in $configDir/badForSteeringX \
             -retain=col,DeviceName } results] {
    puts stderr "makeLocalSteeringConfigs(1): $results"
    exit
}
if [catch {exec sddsprocess $statusDir/config.sdds -pipe=out \
             -filter=col,NonexistentV,1,1 \
             | sddsconvert -pipe=in $configDir/badForSteeringY \
             -retain=col,DeviceName } results] {
    puts stderr "makeLocalSteeringConfigs(2): $results"
    exit
}

switch -regexp $steeringType {
    CUUSP0|CUDSP0|P0|P1|P2|AM|BM {
    }
    default {
        puts stderr "Error for $argv0 in [pwd]: Invalid steering type: $steeringType\n$usage"
        exit
    }
}

if ![string length $sourceList] {
    for {set i 1} {$i < 41} {incr i} {
        lappend sourceList $i
    }
}
# For canted undulator configurations. These configuration use P0 steering.
set  CUdataDir /home/helios/oagData/sr/XAXSTF
if [catch {exec sddsprocess $CUdataDir/sectors.sdds -pipe=out  -noWarning \
             -filter=col,CUflag,1,1 \
             | sdds2stream -pipe -col=Sector} CUlist] {
    puts stder "makeLocalSteeringConfigs(3): $CUlist"
    exit
}
# Determine which C:H1 and C:V1 is not in datapool.
# In that case these correctors should not be in the local steering
# matrix, even when we don't run datapool (for simplicity).
set HCorrectorDir /home/helios/oagData/sr/HCorrectorStatus
if [catch {exec sddsprocess $HCorrectorDir/config.sdds -pipe=out -noWarning \
             -match=col,DeviceName=*C:H1* -filter=col,Nonexistent,0,0 \
             -filter=col,OkForFastDCOrbitCorrection,0,0 \
             | sdds2stream -pipe -col=DeviceName} DPCH1badList] {
    puts stderr "makeLocalSteeringConfigs(4): $DPCH1badList"
    exit
}
set VCorrectorDir /home/helios/oagData/sr/VCorrectorStatus
if [catch {exec sddsprocess $VCorrectorDir/config.sdds -pipe=out  -noWarning \
             -match=col,DeviceName=*C:V1* -filter=col,Nonexistent,0,0 \
             -filter=col,OkForFastDCOrbitCorrection,0,0 \
             | sdds2stream -pipe -col=DeviceName} DPCV1badList] {
    puts stderr "makeLocalSteeringConfigs(5): $DPCV1badList"
    exit
}

# which bpms to use outside the bump.
#       x           y
# AM    BP1         BP1 BP5
# BM    BP1         BP1 BP5
# CU P0 BP1 BP5     BP1 BP5 
# P0    BP1 BP5     BP1 BP5 
# P1    BP1 BP5     BP1 BP5
# P2    BP2         BP2 BP5
foreach i $sourceList {
    set i1 [expr $i + 1]
    if [expr $i1 == 41] {
        set i1 1
    }
    # Skips the loop for the CU type if the sector doesn't have CU undulator or 
    # magnets.
    if {[regexp {CU} $steeringType] && -1 == [lsearch $CUlist $i]} {
        continue
    }
    set subdirectory ${steeringType}s
    set targetDir $configDir/$subdirectory/[format %02ld $i]${steeringType} 
    if ![file exists $targetDir] {
        exec mkdir -p $targetDir
    }
    set tmp /tmp/[APSTmpString]
    if [catch {exec sddsprocess $configDir/${steeringType}s.template.x $tmp.x \
                 -reedit=col,Name,%/<n>/$i/%/<n+1>/$i1/ \
                 -redef=col,Flag,1,type=long \
             } result ] {
        puts stderr "makeLocalSteeringConfigs(6): Problem with ${steeringType}s.template.x: $result"
        exit
    }

    if [catch {exec sddsprocess $configDir/${steeringType}s.template.y $tmp.y \
                 -reedit=col,Name,%/<n>/$i/%/<n+1>/$i1/ \
                 -redef=col,Flag,1,type=long \
             } result ] {
        puts stderr "makeLocalSteeringConfigs(7): Problem with ${steeringType}s.template.y: $result"
        exit
    }

    # remove a CU corrector if necesary
    if {[regexp {CU} $steeringType] && \
          -1 < [lsearch $DPCH1badList S${i}C:H1]} {
        if [catch {exec sddsprocess $tmp.x -noWarning \
                     -match=col,Name=S${i}C:H1,! \
                 } result ] {
            puts stderr "makeLocalSteeringConfigs(8): $result"
            exit
        }
    }
    if {[regexp {CU} $steeringType] && \
          -1 < [lsearch $DPCV1badList S${i}C:V1]} {
        if [catch {exec sddsprocess $tmp.y -noWarning \
                     -match=col,Name=S${i}C:V1,! \
                 } result ] {
            puts stderr "makeLocalSteeringConfigs(9): $result"
            exit
        }
    }
    
    # in P2 steering some correctors are not available.
    # Maybe this should be more automatically applied, such as
    # replacing non-existing correctors with neighboring ones.
    foreach plane {x y} {
        if [catch {exec sddsprocess $tmp.$plane -pipe=out -nowarning \
                     -match=parameter,NameType=CorrectorNames \
                     | sddsxref -pipe -nowarning \
                     $configDir/corrSubstitutes.sdds \
                     -match=Name -take=NewName \
                     | sddsconvert -pipe=in $tmp.${plane}1 \
                     -delete=column,Name -rename=column,NewName=Name 
            exec sddsselect $tmp.$plane \
                     $configDir/corrSubstitutes.sdds \
                     -reuse=page,row \
                     -match=Name -invert \
                     $tmp.${plane}2 
            exec sddscombine $tmp.${plane}1 $tmp.${plane}2 $tmp.$plane \
                     -merge=NameCode -overwrite 
            file delete $tmp.${plane}1 $tmp.${plane}2 \
                 } result] {
            puts stderr "makeLocalSteeringConfigs(10): $result"
            exit
        }
    }

    switch $steeringType {
        AM -
        BM {
            if [catch {exec sddscombine $tmp.x \
                         $configDir/BP1s.config -pipe=out \
                         -merge=NameCode -overWrite \
                         | sddsxref -pipe \
                         $xrefDir/SRBPMCorrPosition.xref \
                         -noWarning \
                         -take=s -match=Name=ElementName -reuse=page \
                         | sddssort -pipe -col=s \
                         | sddsconvert -pipe=in $targetDir/config.x \
                         -dele=para,NumberCombined,NameCode \
                         -dele=col,s 
                exec sddscombine $tmp.y \
                         $configDir/BP1s.config $configDir/BP5s.config -pipe=out \
                         -merge=NameCode -overWrite \
                         | sddsxref -pipe \
                         $xrefDir/SRBPMCorrPosition.xref \
                         -noWarning \
                         -take=s -match=Name=ElementName -reuse=page \
                         | sddssort -pipe -col=s \
                         | sddsconvert -pipe=in $targetDir/config.y \
                         -dele=para,NumberCombined,NameCode \
                         -dele=col,s \
                     } result ] {
                puts stderr "makeLocalSteeringConfigs(11): $result"
                exit
            }
            # removing one BP5 bpm S${i}B:P5 from file ${file}.y.
            if [catch {exec sddsprocess $targetDir/config.y -nowarning \
                         -match=col,Name=S${i}B:P5,! \
                     } result ] {
                puts stderr "makeLocalSteeringConfigs(12): $result"
                exit
            }
        }
        CUUSP0 -
        CUDSP0 -
        P0 {
            # it's OK to use B:P5's for ID steering.
            if [catch {exec sddscombine $tmp.x \
                         $configDir/BP1s.config $configDir/BP5s.config  -pipe=out \
                         -merge=NameCode -overWrite \
                         | sddsxref -pipe \
                         $xrefDir/SRBPMCorrPosition.xref \
                         -noWarning \
                         -take=s -match=Name=ElementName -reuse=page \
                         | sddssort -pipe -col=s \
                         | sddsconvert -pipe=in $targetDir/config.x \
                         -dele=para,NumberCombined,NameCode \
                         -dele=col,s 
                exec sddscombine $tmp.y \
                         $configDir/BP1s.config $configDir/BP5s.config -pipe=out \
                         -merge=NameCode -overWrite \
                         | sddsxref -pipe \
                         $xrefDir/SRBPMCorrPosition.xref \
                         -noWarning \
                         -take=s -match=Name=ElementName -reuse=page \
                         | sddssort -pipe -col=s \
                         | sddsconvert -pipe=in $targetDir/config.y \
                         -dele=para,NumberCombined,NameCode \
                         -dele=col,s \
                     } result ] {
                puts stderr "makeLocalSteeringConfigs(12): $result"
                exit
            }
            # removing one BP1 bpm S${i}B:P1 from files.
            if [catch {exec sddsprocess $targetDir/config.y $targetDir/config.y.1 \
                         -nowarning \
                         -match=col,Name=S${i}B:P1,!
                exec sddsprocess $targetDir/config.x $targetDir/config.x.1 \
                         -nowarning \
                         -match=col,Name=S${i}B:P1,! \
                     } result ] {
                puts stderr "makeLocalSteeringConfigs(13): $result"
                exit
            }
            exec mv $targetDir/config.y.1 $targetDir/config.y
            exec mv $targetDir/config.x.1 $targetDir/config.x
        }
        P1 {
            # OK to use B:P5's for ID steering.
            if [catch {exec sddscombine $tmp.x \
                         $configDir/BP1s.config $configDir/BP5s.config  -pipe=out \
                         -merge=NameCode -overWrite \
                         | sddsxref -pipe \
                         $xrefDir/SRBPMCorrPosition.xref \
                         -noWarning \
                         -take=s -match=Name=ElementName -reuse=page \
                         | sddssort -pipe -col=s \
                         | sddsconvert -pipe=in $targetDir/config.x \
                         -dele=para,NumberCombined,NameCode \
                         -dele=col,s 
                exec sddscombine $tmp.y \
                         $configDir/BP1s.config $configDir/BP5s.config -pipe=out \
                         -merge=NameCode -overWrite \
                         | sddsxref -pipe \
                         $xrefDir/SRBPMCorrPosition.xref \
                         -noWarning \
                         -take=s -match=Name=ElementName -reuse=page \
                         | sddssort -pipe -col=s \
                         | sddsconvert -pipe=in $targetDir/config.y \
                         -dele=para,NumberCombined,NameCode \
                         -dele=col,s \
                     } result ] {
                puts stderr "makeLocalSteeringConfigs(14): $result"
                exit
            }
        }
        P2 {
            if [catch {exec sddscombine $tmp.x \
                         $configDir/BP2s.config -pipe=out \
                         -merge=NameCode -overWrite \
                         | sddsxref -pipe \
                         $xrefDir/SRBPMCorrPosition.xref \
                         -noWarning \
                         -take=s -match=Name=ElementName -reuse=page \
                         | sddssort -pipe -col=s \
                         | sddsconvert -pipe=in $targetDir/config.x \
                         -dele=para,NumberCombined,NameCode \
                         -dele=col,s 
                exec sddscombine $tmp.y \
                         $configDir/BP2s.config $configDir/BP5s.config -pipe=out \
                         -merge=NameCode -overWrite \
                         | sddsxref -pipe \
                         $xrefDir/SRBPMCorrPosition.xref \
                         -noWarning \
                         -take=s -match=Name=ElementName -reuse=page \
                         | sddssort -pipe -col=s \
                         | sddsconvert -pipe=in $targetDir/config.y \
                         -dele=para,NumberCombined,NameCode \
                         -dele=col,s \
                     } result ] {
                puts stderr "makeLocalSteeringConfigs(15): $result"
                exit
            }
            # removing bpm S${i}B:P5 S${i1}B:P5 for file config.y
            # bump covers two BP5 bpms.
            if [catch {exec sddsprocess $targetDir/config.y -nowarning \
                         -match=col,Name=S${i}B:P5,!,Name=S${i1}B:P5,!,& \
                     } result ] {
                puts stderr "makeLocalSteeringConfigs(16): $result"
                exit
            }
        }
    }
    # remove bad bpms from configuration
    if [catch {exec sddsselect $targetDir/config.x $configDir/badForSteeringX \
                 $tmp.config.x \
                 -match=Name=DeviceName -reuse=page -invert -noWarnings 
        APSFileCopy -from $tmp.config.x -to $targetDir/config.x \
             } result ] {
        puts stderr "makeLocalSteeringConfigs(17): $result"
        exit
    }
    if [catch {exec sddsselect $targetDir/config.y $configDir/badForSteeringY \
                 $tmp.config.y \
                 -match=Name=DeviceName -reuse=page -invert -noWarnings
        APSFileCopy -from $tmp.config.y -to $targetDir/config.y \
             } result ] {
        puts stderr "makeLocalSteeringConfigs(18): $result"
        exit
    }
    #catch {exec setfacl -m mask:rwx $targetDir/config.x}
    #catch {exec setfacl -m mask:rwx $targetDir/config.y}
    file delete $tmp.x $tmp.y $targetDir/config.x~ $targetDir/config.y~
}


# Local Variables:
# mode: tcl
# indent-tabs-mode: nil
# End:
