#!/bin/sh
# -*- mode: tcl -*-
# ALL the continued lines following this one are interpreted
# by the bourne shell and ignored by Tcl, which picks up
# execution after the exec line.\
exec `which tclsh` "$0" ${1+"$@"}

#--------------------------------------------------------------------------------
# Establish the name of the package to be unstowed
#--------------------------------------------------------------------------------
proc SetCurrent { } {
    if { [ file exist bin ] } {
	catch { set data [file link bin] } err
	regexp {(ldas-[^\/]*)} $data -> ::Current
    } else {
	set ::Current ""
    }        
}

#--------------------------------------------------------------------------------
# Establish the name of the package to be stowed
#--------------------------------------------------------------------------------
proc SetNew { } {
    if { ! [ info exist ::New ] } {
	catch { exec ls -1t stow_pkgs | head -1 } ::New
    }
}

#--------------------------------------------------------------------------------
# Establish default values
#--------------------------------------------------------------------------------
set ::STOW /ldcg/bin/stow
set ::GATEWAY_NFS_OS_PARENT_DIRECTORY /export/ldcg_server/ldas_prod
if { ! [file isdirectory $::GATEWAY_NFS_OS_PARENT_DIRECTORY] } {
    unset ::GATEWAY_NFS_OS_PARENT_DIRECTORY
    cd /ldas
} else {
    set ::GATEWAY_NFS_OS_ARCHITECTURES [ list solaris centos5_x86 opteron_sol10 ]
    cd $::GATEWAY_NFS_OS_PARENT_DIRECTORY
}

if { $argc } {
    set ::New [ lindex $argv 0 ]
}

set curdir [ pwd ]

if { [info exists ::GATEWAY_NFS_OS_ARCHITECTURES] } {
    foreach mach $::GATEWAY_NFS_OS_ARCHITECTURES { 
	if { [file isdirectory ${mach}/stow_pkgs] } {
	    #--------------------------------------------------------------------
	    # The directory exists
	    #--------------------------------------------------------------------
	    cd ${mach}
	    SetCurrent
	    SetNew
	    cd stow_pkgs
	    catch { exec $::STOW -D $::Current } err
	    puts "$mach stow -D $::Current: $err"
	    catch { exec $::STOW $::New } err1
	    puts "$mach stow $::New: $err1"
	    puts "$mach: previous $::Current current $:New"
	    cd $curdir
	}
    } ;# foreach mach $::GATEWAY_NFS_OS_ARCHITECTURES
} else {
    if { [file isdirectory stow_pkgs] } {
	#------------------------------------------------------------------------
	# The directory exists
	#------------------------------------------------------------------------
	SetCurrent
	SetNew
	cd stow_pkgs
	catch { exec $::STOW -D $::Current } err
	puts "stow -D $::Current: $err"
	catch { exec $::STOW $::New } err1
	puts "stow $::New: $err1"
	puts "previous $::Current current $::New"
    }
}

# :TODO: find the clear_reports script and put into sbin
#catch { clear_reports } err
#puts $err
