#!/usr/bin/perl -w

use FindBin;
use Expect;

# Create startup script in ramdisk
my $S99 = "$FindBin::Bin/initramfs/etc/init.d/S99benchmark";
system("rm -f $S99");
system("cat > $S99; chmod +x $S99") unless -t STDIN;

# Boot the gateway
# die("No boot command") if ($#ARGV eq -1);
my $bootcmd = scalar @ARGV ? "'".join("' '", @ARGV)."'" : "$FindBin::Bin/boot";
$exp = Expect->spawn($bootcmd) or die "Cannot spawn $bootcmd: $!";
$exp->expect(120,
	     'Welcome to Buildroot',
	     'UGW started',
	     '-re', 't...a...s...k...s... ...s...t...a...r...t...e...d') # RTEMS has bug - it sends 4 characters instead of just one
    or die("Boot failed");

# Measure latencies
my $latester = '
set -e
rm -f tmp-stat.txt
echo "Starting latester"
sudo /sbin/ifdown eth0
r=0
sudo ~/bin/latester -d can0 -d can1 -d can2 -c 3200 -q --oneattime -n tmp || r=$?
sudo /sbin/ifup eth0
source tmp-stat.txt
for i in sent lost enobufs $(seq -f percentile%g 0 10 100); do keyval="$keyval $i=$((i))"; done
echo "! PERF: gw_latency $avg µs $keyval ok"
test $avg -eq 0 && exit 1
exit $r
';

my $status = system((qw(ssh -T glab), $latester));
$exp->close();
exit($status >> 8);
