#!/bin/sh  
# \
exec oagwish "$0" "$@"
wm withdraw .

#
# $Log: not supported by cvs2svn $
# Revision 1.2  1997/01/13 15:47:55  saunders
# Use APSParseArguments for cmd line args. Added -noLock option.
#
# Revision 1.1  1997/01/10 21:50:53  saunders
# New addition.
#
# 

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 args $argv
if {$argc < 2 || $argc > 8 || $argc % 2} {
    puts stderr "usage: $argv0 \[-m x\] \[-noLock 1\] \[-group <group>\] file dest-dir"
    exit 1
}
set m 0755
set noLock 0
set group epicsmgr
APSParseArguments {m noLock group}
set mode $m

set fileName [lindex $args 0]
set fileTail [file tail $fileName]
set destDir [lindex $args 1]

if {![file exists $fileName]} {
    puts stderr "$argv0: $fileName not found"
    exit 1
}
if {![file writable $destDir]} {
    puts stderr "$argv0: you do not have permission to write in $destDir"
    exit 1
}

proc APSFileLockExit {directory lockFd} {
    global apsFileLockInit

    if {[info exists apsFileLockInit($directory)]} {
	catch {os lockf $lockFd F_ULOCK 0}
	catch {close $lockFd}
	unset apsFileLockInit($directory)
    }
}

proc APSFileLock {args} {
    global apsFileLockInit
    set lockFile ./installLock
    set action lock
    set timeout 10
    APSParseArguments {action lockFile timeout}

    # Lock directory
    if {![string compare $action lock]} {
	if {![info exists apsFileLockInit($lockFile)]} {
	    if [catch {open $lockFile w+} res] {
		return -code error "Unable to open lock file: $res"
	    } else {
		set lockFd $res
	    }
	    set apsFileLockInit($lockFile) $lockFd
	    global atExitList
	    dp_atexit set atExitList
	    dp_atexit append "APSFileLockExit $lockFile $lockFd"
	} else {
	    set lockFd $apsFileLockInit($lockFile)
	}
	if {$timeout == 0} {
	    if [catch {os lockf $lockFd F_LOCK 0} res ] {
		return -code error "unable to acquire lock"
	    } else {
		return -code ok 0
	    }
	} else {
	    set tryAgain $timeout
	    while {$tryAgain} {
		if [catch {os lockf $lockFd F_TLOCK 0} res] {
		    if {![string compare $res EAGAIN]} {
			# file is locked already
			incr tryAgain -1
			if {!$tryAgain} {
			    return -code error "timeout on acquiring lock"
			}
			after 1000
		    } else {
			return -code error "failed to acquire lock"
		    }
		} else {
		    return -code ok 0
		}
	    }
	}
    } else {
	# Unlock directory
	if {[info exists apsFileLockInit($lockFile)]} {
	    set lockFd $apsFileLockInit($lockFile)
	    catch {os lockf $lockFd F_ULOCK 0}
	    catch {close $lockFd}
	    unset apsFileLockInit($lockFile)	    
	}

    }
}

if {!$noLock} {
    if [catch {APSFileLock -lockFile $destDir/installLock -action lock} res] {
	puts stderr "$argv0: $res"
	exit 1
    }
}

# Assume lock is asserted at this point (unless option noLock is set)
# Define some procedures. Body of script continues afterwards...

#
# Given full path to a file, search for the highest serial numbered
# version of that file. Return the next highest serial number. If
# no serial numbered version exists, return .00001
#
proc nextSerialNumber {path} {
    set dir [file dirname $path]
    set file [file tail $path]
    set fileList [glob -nocomplain ${path}.0*]

    set maxSerial 0
    foreach f $fileList {
	set serialNo -1
	regexp {[.]([0-9]+)} $f match serialNo
	scan $serialNo "%d" serialNo
	if {$serialNo > $maxSerial} {
	    set maxSerial $serialNo
	}
    }
    if {$maxSerial == 0} {
	return ${file}.[format "%05d" 1]
    } else {
	return ${file}.[format "%05d" [expr $maxSerial + 1]]
    }
}

#
# Submit a log message for given file
#
proc logPatch {arch from} {
    global env argv0 sourceId serviceId
    global apsScriptUser

    set applicationName [file tail $from]

    set logCmd "logMessage -sourceId=$sourceId -tag=applicationName $applicationName -tag=user $apsScriptUser -tag=applicationArch $arch -tag=applicationState versionChange -tag=previousVersion unknown -tag=newVersion patch"

    if {[catch "eval exec $logCmd" res]} {
	puts stderr " *** Error: Can't log activity: $res"
    } 
}

# Copy file over with new serial number
set newFile [nextSerialNumber $destDir/$fileTail]

if [catch {exec cp -p $fileName $destDir/$newFile} result] {
    puts stderr "$argv0: $result"
    exit 1
} else {
    puts "Copied $fileName -> $destDir/$newFile"
    catch {exec chmod $mode $destDir/$newFile} result
    catch {exec chgrp $group $destDir/$newFile} result
}


exit 0



