set testlist {backtrace args pid num_args}

if {![installtest_p]} { 
    foreach test $testlist {
	untested $test
    }
    return
}

set build_dir ""

proc cleanup_modules {} {
    global build_dir
    catch { exec kill -INT -- -[exp_pid] }
    foreach n {1 2} {
	as_root  [list /bin/rm -f /lib/modules/$::uname/kernel/systemtap_test_module$n.ko]
	as_root [list /sbin/rmmod systemtap_test_module$n]
    }
    if {$build_dir != ""} {
	catch { exec rm -rf $build_dir }
    }
}

proc build_modules {} {
    global build_dir
    global srcdir subdir

    # Create the build directory and populate it
    if {[catch {exec mktemp -d staptestXXXXXX} build_dir]} {
	verbose -log "Failed to create temporary directory: $build_dir"
	return 0
    }
    foreach f [glob $srcdir/$subdir/systemtap_test_module*.c] {
	exec cp $f $build_dir/
    }

    # Build the modules
    foreach n {2 1} {
	exec cp -p $srcdir/$subdir/makefile$n $build_dir/Makefile
	if {[catch {exec make -C $build_dir clean} res]} {
	    verbose -log "$res"
	    return 0
	}
	catch {exec make -C $build_dir} res
	if {![file exists $build_dir/systemtap_test_module$n.ko]} {
	    verbose -log "$res"
	    return 0
	}
	set res [as_root  [list cp $build_dir/systemtap_test_module$n.ko /lib/modules/$::uname/kernel]]
	if { $res != 0 } {
	    verbose -log "$res"
	    return 0
	}
    }

    # Install the modules
    foreach n {2 1} {
	set res [as_root [list /sbin/insmod $build_dir/systemtap_test_module$n.ko]]
	if {$res != 0} {
	    verbose -log "$res"
	    return 0
	}
    }
    return 1
}

# first build the modules

# NB: We cannot "cd" on behalf the whole dejagnu process, especially
# without going back to the build tree, and especially not to the
# source tree expecting to be able to write there.
#
# cd $srcdir/$subdir

set uname [exec /bin/uname -r]

if {[build_modules] == 0} {
    verbose -log "BUILD FAILED"
    foreach test $testlist {
	fail "$test - could not build modules"
    }
    return
}

foreach test $testlist {
    send_log "sourcing: $srcdir/$subdir/$test.tcl\n"
    source $srcdir/$subdir/$test.tcl
}

cleanup_modules
