# Copyright: 2007-2023 Paul Obermeier (obermeier@poSoft.de)
# Distributed under BSD license.

set opts(Verbose) false

set tclsh "tclsh"

set patternList  [list]
set testFileList [list]
set useAllFiles  false

proc PrintUsage { progName { msg "" } } {
    global opts nsAvailList

    puts ""
    if { $msg ne "" } {
        puts "Error: $msg"
    }
    puts ""
    puts "Usage: $progName \[Options\] FilePattern \[FilePattern\]"
    puts ""
    puts "Run the test programs for specified glob-style file pattern(s)."
    puts "Use \"all\" as file pattern to run all available test programs."
    puts ""
    puts "Options:"
    puts "  --help   : Display this usage message and exit."
    puts "  --verbose: Show the detailed results of the tests. (Default: No)"
    puts ""
}

proc RunTest { testFile } {
    global opts

    puts "Running test $testFile ..."
    set catchVal [catch {exec -ignorestderr $::tclsh $testFile auto 2>@1 } retVal optionsDict]
    if { $catchVal || [string match "*Error:*" $retVal] } {
        if { $catchVal } {
            set fullErrorInfo [dict get $optionsDict -errorinfo]
            set msgEndIndex [string first "\n" $fullErrorInfo]
            set msg [string range $fullErrorInfo 0 [expr {$msgEndIndex -1}]]
        } else {
            foreach line [split $retVal "\n"] {
                if { [string match "*Error:*" $line] } {
                    append msg $line
                }
            }
        }
        puts "Test $testFile failed: $msg"
    } else {
        if { $opts(Verbose) } {
            puts $retVal
            puts ""
        }
    }
}

set curArg 0
while { $curArg < $argc } {
    set curParam [lindex $argv $curArg]
    if { [string compare -length 1 $curParam "-"]  == 0 || \
         [string compare -length 2 $curParam "--"] == 0 } {
        set curOpt [string tolower [string trimleft $curParam "-"]]
        if { $curOpt eq "verbose" } {
            set opts(Verbose) true
        } elseif { $curOpt eq "help" } {
            PrintUsage $argv0
            exit 1
        } else {
            PrintUsage $argv0 "Invalid option \"$curParam\" specified."
            exit 1
        }
    } else {
        if { $curParam eq "all" } {
            set useAllFiles true
        } else {
            lappend patternList $curParam
        }
    }
    incr curArg
}

if { $useAllFiles } {
    set testFileList [lsort [glob -nocomplain "t_*.tcl"]]
} else {
    foreach pattern $patternList {
        lappend testFileList {*}[lsort [glob -nocomplain $pattern]]
    }
}

if { [llength $testFileList] == 0 } {
    PrintUsage $argv0 "No valid file pattern specified."
    exit 1
}


catch { file mkdir testOut }
foreach testFile $testFileList {
    RunTest $testFile
}

exit 0
