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

# cleanup
system "rm -f flightlog.out*"

set pid 0
# check -S option with bulk(percpu file) mode
catch {spawn stap -F -o flightlog.out -S 1,3 -b $srcdir/$subdir/$test.stp}
expect {
  -timeout 240
  -re {([0-9]+)\r\n} {
      pass "$test (-S option with bulk mode)"
      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
}

exec sleep 4
array set cpus {}
set scnt 0
# wait for log files
kill -STOP $pid
exec sleep 1
catch {eval spawn stat -c \"%n %s\" [glob -nocomplain flightlog.out_cpu*]}
expect {
  -timeout 100
  -re {flightlog.out_cpu([0-9]+).[0-9]+ ([0-9]+)\r\n} {
      set cpuid $expect_out(1,string)
      set size $expect_out(2,string)
      if {[array get cpus $cpuid] == ""} {set cpus($cpuid) 0}
      incr cpus($cpuid);
      if {$size <= 1048576 } {incr scnt}
      exp_continue}
  timeout { fail "$test (logfile timeout)"}
}
catch { close -i $spawn_id }; catch { wait -i $spawn_id }
kill -CONT $pid
exec sleep 3
kill -STOP $pid

catch {eval spawn stat -c \"%n %s\" [glob -nocomplain flightlog.out_cpu*]}
expect {
  -timeout 100
  -re {flightlog.out_cpu([0-9]+).[0-9]+ ([0-9]+)\r\n} {
      set cpuid $expect_out(1,string)
      set size $expect_out(2,string)
      if {[array get cpus $cpuid] == ""} {set cpus($cpuid) 0}
      incr cpus($cpuid);
      if {$size <= 1048576 } {incr scnt}
      exp_continue}
  timeout { fail "$test (logfile timeout)"}
}
catch { close -i $spawn_id }; catch { wait -i $spawn_id }
kill -CONT $pid
# check logfile number
set cnt 0
foreach e [array names cpus] {
    # If we have more than 6 files per cpu, something is wrong. We
    # might have less than 6 files per cpu if the machine is slow.
    if {$cpus($e) > 6} {
        fail "$test (log file numbers cpu:$e, cnt:$cpus($e)))"
    }
    set cnt [expr $cnt + $cpus($e)]
}
# check logfile size
if {$scnt == $cnt} {
    pass "$test (log file size limitation with bulk mode)"
} else {
    fail "$test (log file size ($scnt != $cnt))"
}

# Kill the background stapio process.
kill -TERM $pid 5
catch {system "rm -f flightlog.out*"}

