#! /usr/bin/env tclsh

set sourceDirectory [file dirname [file normalize [info script]]]

lappend auto_path [file join $sourceDirectory lib]

set template [file join $sourceDirectory lib xvfs xvfs.c.rvt]

package require minirivet

set mode "run"
if {[lindex $argv 0] == "--dump-tcl"} {
	set mode "dump-tcl"
}

foreach {arg val} $argv {
	switch -exact -- $arg {
		"--output" {
			set outputFile $val
		}
	}
}

proc remove_debug {input} {
	set output [list]

	set lastLine -
	foreach line [split $input "\n"] {
		if {[string match -nocase "*XVFS_DEBUG*" $line]} {
			continue
		}

		if {$lastLine eq "" && $line eq ""} {
			continue
		}

		set lastLine $line
		lappend output $line
	}

	return [join $output "\n"]
}

switch -- $mode {
	"run" {
		package require xvfs

		if {[info exists outputFile]} {
			set fd [open $outputFile w]
			::xvfs::setOutputChannel $fd
		}

		set ::xvfs::argv $argv
		::xvfs::run

		if {[info exists fd]} {
			close $fd
		}
	}
	"dump-tcl" {
		set xvfs_tcl [file join $sourceDirectory lib xvfs xvfs.tcl]
		set xvfs_core_h [file join $sourceDirectory xvfs-core.h]
		set xvfs_core_c [file join $sourceDirectory xvfs-core.c]

		set cleanup {
			"#include <xvfs-core.h>" ""
			"#include <xvfs-core.c>" ""
		}

		set core_header_data ""
		append core_header_data [string map $cleanup [read [open $xvfs_core_h]]] "\n"
		append core_header_data [string map $cleanup [read [open $xvfs_core_c]]] "\n"

		if {[lsearch -exact $argv "--remove-debug"] != -1} {
			set core_header_data [remove_debug $core_header_data]
		}

		puts "#! /usr/bin/env tclsh"
		puts ""
		puts [list namespace eval ::minirivet {}]
		puts [list set ::minirivet::_outputChannel stdout]
		puts [list proc ::minirivet::_emitOutput [info args ::minirivet::_emitOutput] [info body ::minirivet::_emitOutput]]
		puts ""
		puts [read [open $xvfs_tcl]]
		puts ""
		puts {set ::xvfs::argv $::argv}
		puts {
			foreach {arg val} $argv {
				switch -exact -- $arg {
					"--output" {
						set ::minirivet::_outputChannel [open $val w]
					}
				}
			}
		}
		puts ""
		puts [list ::minirivet::_emitOutput $core_header_data]
		puts ""

		puts ""
		puts [string map $cleanup [::minirivet::parseStringToCode [read [open $template]]]]
	}
	default {
		puts stderr "error: Invalid mode: $mode"
		exit 1
	}
}
