set test "flightrec4"
if {![installtest_p]} { untested $test; return }

# Make sure we start with a clean slate.
catch {exec rm -f $test.out*}

# run stapio in background mode with number limit
spawn stap -u -F -S 1,2 -o $test.out -we {probe begin {}}
# check whether stap outputs stapio pid
set pid 0
expect {
  -timeout 240
  -re {([0-9]+)\r\n} {
      pass "$test (flight recorder option)"
      set pid $expect_out(1,string)
      exp_continue}
  timeout { fail "$test (timeout)" }
  eof { }
}
# Here we're waiting on the parent stap process to finish. Stapio will
# still be running in the background.
catch { close }; catch { wait }

if {$pid == 0} {
  fail "$test (no pid)"
  return -1
}

# switch file to .1
exec sleep 2
kill -USR2 $pid

# check output file
if {[catch {exec rm $test.out.0}]} {
  fail "$test (no output file)"
  return -1
} else {
  pass "$test (output file)"
}

# switch file to .2
exec sleep 2
kill -USR2 $pid
# switch file to .3 (this time, .1 file should be deleted)
exec sleep 2
kill -USR2 $pid

# check switched output file
exec sleep 2
if {[catch {exec rm $test.out.1}]} {
  pass "$test (old output file is removed)"
} else {
  fail "$test (failed to remove output file)"
  return -1
}

# Kill the background stapio process.
kill -TERM $pid 5

# check switched output file
if {[catch {exec rm $test.out.2 $test.out.3}]} {
  fail "$test (failed to switch output file)"
  return -1
} else {
  pass "$test (switch output file)"
}

