#!/usr/bin/tclsh

set scripts {
    { scripts/agent/init.tcl embedded/initScript.c tcl7.5/unix}
    { scripts/agent/agent.tcl embedded/agentScript.cc agent-tcl}
    { scripts/agent/require.tcl embedded/requireScript.cc agent-tcl}
    { scripts/agent/safety.tcl embedded/safetyScript.cc agent-tcl}
}

foreach script $scripts {

    set scriptFile  [lindex $script 0]
    set ccode       [lindex $script 1]
    set destination [lindex $script 2]

    set extension [file extension $ccode]
    set prefix    [file root      $ccode]
    set tail      [file tail      $ccode]
    set basename  [file root      $tail]

    set includeFile $prefix.h
    set sourceFile  $prefix$extension

	# output the include file

    if ![file writable $includeFile] {
	catch {
	    exec co -l $includeFile
	} result
    }

    set fd [open $includeFile w 0644]
    puts $fd "/*"
    puts $fd " * Generated automatically by $argv0 on [exec date]."
    puts $fd " * Do not edit."
    puts $fd " */"
    puts $fd ""
    puts $fd "#ifndef _[string toupper $basename]_H"
    puts $fd "#define _[string toupper $basename]_H"
    puts $fd ""
    puts $fd "#ifdef __cplusplus"
    puts $fd "#define EXTERNAL extern \"C\""
    puts $fd "#else"
    puts $fd "#define EXTERNAL extern"
    puts $fd "#endif"
    puts $fd ""
    puts $fd "EXTERNAL char *string_$basename;"
    puts $fd ""
    puts $fd "#endif"
    close $fd

	# get the script

    set fd [open $scriptFile r]
    set script [read $fd]
    set script [string trim $script]
    close $fd

	# output the source code file

    if ![file writable $sourceFile] {
	catch {
	    exec co -l $sourceFile
	}
    }

    set fd [open $sourceFile w 0644]
    puts $fd "/*"
    puts $fd " * Generated automatically by $argv0 on [exec date]."
    puts $fd " * Do not edit."
    puts $fd " */"
    puts $fd ""
    puts $fd "#include \"[file tail $includeFile]\""
    puts $fd ""

    if {[lindex $argv 0] == "no"} {

	puts $fd "char *string_$basename = (char *) 0;"

    } else {

	set splitScript [split $script \n]
	set script      {}

	foreach line $splitScript {

	    set line [string trim $line]

	    if {$line == ""} {
		continue
	    }
	
	    if {[string range $line 0 0] == "#"} {
		continue
	    }

	    append script $line\n
	}

	puts -nonewline $fd "char *string_$basename = \""
	regsub -all {\\} $script {\\\\} script
	regsub -all \" $script \\\" script
	regsub -all \n $script "\\n\\\n" script
	regsub -all \t $script \\t script
	regsub -all \t $script \\r script
	puts -nonewline $fd $script
	puts $fd "\";"
    }

    close $fd

	# copy to the destination

    set includeTail [file tail $includeFile]
    set sourceTail  [file tail $sourceFile]

    if ![file writable $destination/$includeTail] {
	catch {
	    exec co -l $destination/$includeTail
	}
    }

    if ![file writable $destination/$sourceTail] {
	catch {
	    exec co -l $destination/$sourceTail
	}
    }

    exec cp $includeFile $destination
    exec cp $sourceFile  $destination
}
