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

# $Log: not supported by cvs2svn $
# Revision 1.5  2005/09/23 17:16:39  soliday
# Updated because some PVs have been promoted from mirrored PVs to real PVs.
#
# Revision 1.4  2005/09/14 15:40:13  soliday
# When fixing the SCR reference file it now also updates and copies auxiliary
# files which are related.
#
# Revision 1.3  2005/09/08 18:47:12  soliday
# The changed files will no longer overwrite the existing files. Instead new
# files will be made and the symbolic links updated.
#
# Revision 1.2  2005/09/07 15:54:32  soliday
# Added the option to attempt to fix the SCR reference files where PVs have
# been renamed or removed.
#
# Revision 1.1  2005/09/01 22:43:45  soliday
# This program is used to check the SCR reference files for PVs that
# no longer exist.
#
#

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

set email 0
set fix 0

set args $argv
APSStrictParseArguments {email fix}

set pvNameChangeFiles [exec ls -tr /net/phoebus/asdctls/documentation/pv_name_changes]
set goodFiles ""
set docheck 1
foreach file $pvNameChangeFiles {
    if {[catch {exec sddscheck /net/phoebus/asdctls/documentation/pv_name_changes/$file} result]} {
        continue
    }
    if {$result != "ok"} {
        continue
    }
    lappend goodFiles /net/phoebus/asdctls/documentation/pv_name_changes/$file
}
if {[catch {eval exec sddscombine $goodFiles /tmp/pvchangefiles.sdds -merge -overwrite} result]} {
    puts "Warning: unable to check for updated PV names: $result"
    set docheck 0
    catch {file delete -force /tmp/pvchangefiles.sdds}
} else {
    if {[catch {exec sdds2stream /tmp/pvchangefiles.sdds -col=OldControlName} oldControlNames]} {
        puts "Warning: unable to check for updated PV names: $oldControlNames"
        set docheck 0
        catch {file delete -force /tmp/pvchangefiles.sdds}
    } else {
        if {[catch {exec sdds2stream /tmp/pvchangefiles.sdds -col=NewControlName} newControlNames]} {
            puts "Warning: unable to check for updated PV names: $newControlNames"
            set docheck 0
            catch {file delete -force /tmp/pvchangefiles.sdds}
        }
    }
}
catch {file delete -force /tmp/pvchangefiles.sdds}

set names ""
foreach name $oldControlNames {
    set i [string first . $name]
    if {$i != -1} {
        lappend names [string range $name 0 [expr {$i - 1}]]
    } else {
        lappend names $name
    }
}
set oldControlNames $names

set names ""
foreach name $newControlNames {
    set i [string first . $name]
    if {$i != -1} {
        lappend names [string range $name 0 [expr {$i - 1}]]
    } else {
        lappend names $name
    }
}
set newControlNames $names



set files [glob /home/helios/oagData/SCR/preferredChoices/*.sdds]
set outputError ""
set output ""

if {[catch {exec sdds2stream -col=rec_name \
              /home/helios/oagData/pvdata/iocRecNamesOAG.sdds} PVs]} {
    append outputError "Error: $PVs\n"
} else {

    foreach pv $PVs {
        set valid($pv) 1
    }
    
    foreach file $files {
        if {([file rootname [file tail $file]] == "LINAC") ||
            ([file rootname [file tail $file]] == "LEUTL") ||
            ([file rootname [file tail $file]] == "PLET")} {
            continue
        }
        if {[catch {sdds load $file preferredData} results]} {
            append outputError "Error: $results\n"
            continue
        }
        set category [file tail [file rootname $file]]
        foreach ChoiceName [lindex $preferredData(Column.ChoiceName) 0] \
          Suffix [lindex $preferredData(Column.Suffix) 0] {
              set filename "/home/helios/oagData/SCR/snapshots/${category}/${category}-${Suffix}.gz"

              if {![file exists $filename]} {
                  append outputError "Error: SCR reference file $filename does not exist\n"
                  continue
              }
              if {[catch {sdds load $filename data} result]} {
                  append outputError "Error: $result\n"
                  continue
              }
              set realname $filename
              for {set i 0} {$i < 10} {incr i} {
                  if {[file type $realname] == "link"} {
                      set realname [file dirname $filename]/[file tail [file readlink $realname]]
                      continue
                  } else {
                      break
                  }
              }

#              set col [lsort -dictionary [lindex $data(Column.ControlName) 0]]
              set col [lindex $data(Column.ControlName) 0]
              set colNew [lindex $data(Column.ControlName) 0]
              set badPVsFound 0
              set badPVList ""
              set j -1
              set changed 0
              foreach c $col {
                  incr j
                  set i [string first . $c]
                  if {$i != -1} {
                      set d [string range $c 0 [expr {$i - 1}]]
                  } else {
                      set d $c
                  }
                  if {[info exists valid($d)] == 0} {
                      if {!$badPVsFound} {
                          append output "\n$filename\n"
                          set dateAndTime [clock format [file mtime $realname]]
                          append output "File created on $dateAndTime\n"
                      }
                      if {([llength $c]) && ($docheck)} {
                          set i [lsearch -exact $oldControlNames $d]
                          if {$i != -1} {
                              set newName [lindex $newControlNames $i]
                              if {[llength $newName]} {
                                  set newName $newName[file extension $c]
                                  append output "Bad PV Name: $c Replaced by [lindex $newControlNames $i]\n"
                                  if {$fix} {
                                      set colNew [lreplace $colNew $j $j [lindex $newControlNames $i]]
                                      set changed 1
                                  }
                              } else {
                                  append output "Bad PV Name: $c Removed and not replaced\n"
                                  if {$fix} {
                                      set colNew [lreplace $colNew $j $j ""]
                                      set changed 1
                                  }
                              }
                          } else {
                              append output "Bad PV Name: $c\n"
                          }
                      } else {
                          append output "Bad PV Name: $c\n"
                      }
                      set badPVsFound 1
                  }
              }
              if {$fix && $changed} {
                  if {$realname == $filename} {
                      puts stderr "Error: $filename is not a symbolic link"
                      continue
                  }
                  catch {file delete -force /tmp/SCRReferenceFileCheck.tmp}
                  set data(Column.ControlName) [list $colNew]
                  if {[catch {sdds save /tmp/SCRReferenceFileCheck.tmp data} result]} {
                      puts stderr "Error: $result"
                      exit
                  }
                  set sec [expr int([lindex $data(Parameter.Time) 0])]
                  set newfilename [string range $realname 0 end-23][clock format $sec -format "%Y-%j-%m%d-%H%M%S"].gz
                  while {[file exists $newfilename]} {
                      incr sec
                      set newfilename [string range $realname 0 end-23][clock format $sec -format "%Y-%j-%m%d-%H%M%S"].gz
                  }
                  if {[catch {exec sddsprocess /tmp/SCRReferenceFileCheck.tmp $newfilename -nowarnings \
                                -match=column,ControlName=,! \
                                "-reedit=parameter,SnapshotDescription,i/Updated: /"} result]} {
                      puts stderr "Error: $result"
                      exit
                  }
                  if {[catch {exec rm -f $filename} result]} {
                      puts stderr "Error: $result"
                      exit
                  }
                  if {[catch {exec ln -sf $newfilename $filename} result]} {
                      puts stderr "Error: $result"
                      exit
                  }
                  catch {file delete -force /tmp/SCRReferenceFileCheck.tmp}
                  if {[file exists [file dirname $realname]/collapsed]} {
                      if {[catch {exec sddsprocess [file dirname $realname]/collapsed/c[file rootname [file tail $realname]] \
                                    [file dirname $newfilename]/collapsed/c[file rootname [file tail $newfilename]] \
                                    -nowarnings \
                                    "-reedit=column,SnapshotDescription,i/Updated: /"} result]} {
                          puts stderr "Error: $result"
                          exit
                      }
                  } else {
                      if {[catch {exec sddsprocess [file dirname $realname]/c[file rootname [file tail $realname]] \
                                    [file dirname $newfilename]/c[file rootname [file tail $newfilename]] \
                                    -nowarnings \
                                    "-reedit=column,SnapshotDescription,i/Updated: /"} result]} {
                          puts stderr "Error: $result"
                          exit
                      }
                  }
                  if {[file exists [file dirname $realname]/categories]} {
                      if {[catch {exec cp [file dirname $realname]/categories/categ[file rootname [file tail $realname]] [file dirname $newfilename]/categories/categ[file rootname [file tail $newfilename]]} result]} {
                          puts stderr "Error: $result"
                          exit
                      }
                  } else {
                      if {[catch {exec cp [file dirname $realname]/categ[file rootname [file tail $realname]] [file dirname $newfilename]/categ[file rootname [file tail $newfilename]]} result]} {
                          puts stderr "Error: $result"
                          exit
                      }
                  }
                  if {[file exists [file dirname $realname]/beamlines]} {
                      if {[catch {exec cp [file dirname $realname]/beamlines/beam[file rootname [file tail $realname]] [file dirname $newfilename]/beamlines/beam[file rootname [file tail $newfilename]]} result]} {
                          puts stderr "Error: $result"
                          exit
                      }
                  } else {
                      if {[catch {exec cp [file dirname $realname]/beam[file rootname [file tail $realname]] [file dirname $newfilename]/beam[file rootname [file tail $newfilename]]} result]} {
                          puts stderr "Error: $result"
                          exit
                      }
                  }


              }
          }
    }
}

if {$email} {
    if {([string length $output] > 0) || ([string length $outputError] > 0)} {
        foreach address "soliday borland sereno emery" {
            APSSendEMail -address $address -message "$outputError \n $output" -subject "SCR Reference File Problems"
        }
    }
} else {
    puts $outputError
    puts $output
}


