#run this like so: `tclshn.n configure` Where n.n is the version number of the
#interpreter that you wish to use.

set ::DEBUG 0
set ::CC "cc -g -Wall -fPIC -O2"
#Make this empty if you don't want stub support
set ::USE_STUBS "-DUSE_STUBS"
#set ::USE_STUBS ""
#You may need to edit the paths
set ::libPath [list /usr/lib /usr/local/lib /usr/X11R6/lib /usr/X11/lib /opt/lib /usr/lib/X11]
set ::INCLUDE "-I/usr/X11R6/include -I/usr/local/include -I/usr/local/include/tcl8.3 -I/usr/local/include/tk8.3"

if {$::DEBUG} {
	set ::libPath [concat {/usr/local/tcltk8.4/lib} $libPath]
	set ::INCLUDE "-I/usr/local/tcltk8.4/include $INCLUDE"

	puts $::libPath
	puts $::INCLUDE
}
	
set ::libDirList [list]

proc findLib {name versionMajor versionMinor} {
	set oldWD [pwd]
	foreach path $::libPath {
		if {[file exists $path] != 1} {
			continue
		}
		
		cd $path
		set result [glob -nocomplain lib${name}*${versionMajor}*${versionMinor}*.so*]
		if {$result != ""} {
			cd $oldWD
			set lib [lindex $result 0]
			puts "found $lib"
	
			set lpath "-L$path"
			if {[lsearch $::libDirList $lpath] < 0} {
				lappend ::libDirList $lpath
			}
	
			if {![regexp "lib($name.*?)\.so.*" $lib all theMatch]} {
				return -code error "unable to extract the linking pattern from the result"
			}
	
			return "-l$theMatch"
		}
	}
	puts stderr "error: library $name not found"
	exit 1
}

proc configure {argc argv} {
	puts "configuring for Tk version $::tcl_version"
	#TODO add flag processing for Tcl lib/header paths
	set versionList [split $::tcl_version .]
	set major [lindex $versionList 0]
	set minor [lindex $versionList 1]
	
	set tclLib [findLib tcl $major $minor]
	set tkLib [findLib tk $major $minor]
	set X11Lib [findLib X11 * *]
	set XextLib [findLib Xext * *]
	set XpmLib [findLib Xpm * *]
	set XmuLib [findLib Xmu * *]
	set XtLib [findLib Xt * *]

	puts "done finding libraries"
	
	set ldLibs "$tclLib $tkLib $X11Lib $XextLib $XpmLib $XmuLib $XtLib -lm"
	puts "I will search in the following directories when linking: $::libDirList"
	
	puts -nonewline "checking if -ldl (for Linux) is needed: "
	if {[regexp -nocase $::tcl_platform(os) linux]} {
		puts yes
		append ldLibs " -ldl"
	} else {
		puts no
	}
	
	file delete Makefile
	set fo [open Makefile w]
	puts $fo "all: theme.so\n"
	puts $fo "CC=$::CC $::USE_STUBS"
	puts $fo "INCLUDE=$::INCLUDE\n"
	
	puts $fo "theme.so: *.c"
	puts $fo "\t\$(CC) theme.c themeCursor.c themeLabel.c \$(INCLUDE) -c"
	puts $fo "\tld theme.o themeCursor.o themeLabel.o -Bshareable $::libDirList $ldLibs -o theme.so"
	puts $fo ""
	
	puts $fo "test: *.c"
	puts $fo "\t\$(CC) main.c theme.c themeCursor.c themeLabel.c \$(INCLUDE) $::libDirList $ldLibs -o test"
	puts $fo ""
	
	puts $fo "clean:"
	puts $fo "\trm -f *.core *.o *.so test"
	puts $fo ""
	
	close $fo
	puts "now run make"
}
configure $argc $argv
