#!/bin/sh  
# \
  exec oagtclsh "$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)]

#Script goes through the cppatched files and limits files to the last three versions.
#Older versions are moved into the attic directory.

APSStandardSetup

proc CleanDirectory {args} {
    set directory ""
    APSStrictParseArguments {directory}

    if {![file exists $directory]} {
        return
    }
    cd $directory
    if {![file exists attic]} {
        file mkdir attic
        exec chmod g+rws attic
        exec chmod o+rx attic
    }
    set files [glob -nocomplain *.0* ]
    foreach f $files {
        set rootname [file rootname $f]
        if {(![info exists rootList($rootname)]) && ([file exist $rootname])} {
            set rootList($rootname) 1
        }
    }
    foreach rootname [lsort -dictionary [array names rootList]] {
        if {[file type $rootname] != "link"} {
            continue
        }
        set linkname [file link $rootname]
        set number [string range [file extension $linkname] 1 end]
        set length [string length $number]
        set num [string trimleft $number "0"]
        if {$num == ""} {
            set num 0
        }
        lappend ignoreList $linkname
        incr num -1
        lappend ignoreList ${rootname}.[format %0${length}d $num]
        incr num -1
        lappend ignoreList ${rootname}.[format %0${length}d $num]
        
        while {$num > 1} {
            incr num -1
            set f ${rootname}.[format %0${length}d $num]
            if {[file exist $f]} {
                if {[catch {file rename $f attic/$f} results]} {
                    puts stderr "ERROR: $f $results"
                    exit 1
                }
            }
        }
    }
}

if {$env(USER) != "oag"} {
    puts "Error: cleanInstalledOAGSoftwareVersions must be run by the oag user"
    exit
}
if {$apsNetworkDomain != "aps4.anl.gov"} {
    puts "Error: cleanInstalledOAGSoftwareVersions must be run on the helios network"
    exit
}

CleanDirectory -directory /usr/local/oag/apps/bin/linux-x86_64
CleanDirectory -directory /usr/local/oag/apps/lib/linux-x86_64
CleanDirectory -directory /net/phoebus/oagmgr/oag/apps/bin/linux-x86_64
CleanDirectory -directory /net/phoebus/oagmgr/oag/apps/lib/linux-x86_64
