#!/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)]
set CVSRevisionAuthor "\$Revision: 1.5 $ \$Author: soliday $"

proc putResult {log output} {
    global logFile
    file rename -force -- $log $logFile
    if {[llength $output]} {
	puts stdout $output
    }
    exit
}

proc putError {output} {
    puts stderr $output
    exit 1
}

set parser [interp create -safe]

$parser alias putResult putResult
$parser alias putError putError
$parser eval {
    proc finished {snapshot log output} {
	putResult $log $output
    }
    proc error_result {output} {
	putError $output
    }
}

proc client_handle {sid} {
    global parser buffer
    if {[gets $sid request] < 0} {
	catch {close $sid}
	puts stderr "Disconnected from server"
	exit 1
    } else {
	append buffer $request "\n"
	if {[info complete $buffer]} {
	    set request $buffer
	    set buffer ""
	    if {[catch {$parser eval $request} result]} {
		puts stderr $result
		exit 1
	    }
	}
    }
}


set args $argv
set snapshotFile ""
set logFile ""
set cawait 30
set host localhost
set pipe ""
set apsTempFileList ""

if [APSStrictParseArguments {snapshotFile logFile cawait host pipe}] {
    puts stderr "usage: tclcaput -snapshotFile <string> -logFile <string> \[-cawait <timeInSecs>\] \[-host <computer address>\] -pipe in\n[join [split $CVSRevisionAuthor $] ""]"
    exit 1
}
if {$pipe == "in"} {
#    fconfigure stdin -blocking 0
    fconfigure stdin -translation binary
    set tempFile /tmp/[APSTmpString]
    APSAddToTempFileList $tempFile
    if [catch {open $tempFile w} fileID] {
	puts stderr "Unable to create file: $fileID"
	exit 1
    }
    fconfigure $fileID -translation binary
    puts $fileID [read -nonewline stdin]
    catch {close $fileID}
    set snapshotFile $tempFile
}

if {([llength $snapshotFile] != 1) || ([llength $logFile] != 1)} {
    puts stderr "usage: tclcaput -snapshotFile <string> -logFile <string> \[-cawait <timeInSecs>\] \[-host <computer address>\] -pipe in\n[join [split $CVSRevisionAuthor $] ""]"
    exit 1
}

if [catch {socket $host 4577} sid] {
    puts stderr $sid
    exit 1
} else {
    set snapshotFile [file join [pwd] $snapshotFile]
    set logFile [file join [pwd] $logFile]
    fileevent $sid readable "client_handle $sid"
    fconfigure $sid -buffering line
    puts $sid "setvalues $snapshotFile $cawait"
    vwait enter-mainloop
}

