#!/usr/bin/perl -w
use strict;
use Statistics::Descriptive;

my $SLEEP_AFTER_COMMAND = 60;
my $SLEEP_BETWEEN_MEAUREMENTS = 10;
my $NUMBER_OF_MEASUREMENTS = 10;

sub read_file {
    my ($file) = @_;
    open(my $fd, "<", $file);
    my $ret = <$fd>;
    close($fd);
    chomp($ret);
    return $ret;
}

sub write_file {
    my ($file, $data) = @_;
    open(my $fd, ">", $file)
	or die "unable to open $file for writing: $!";
    print $fd $data;
    close($fd);
}

sub get_current {
    return read_file("/sys/class/power_supply/battery/current_now");
}

sub dbg {
    my ($msg) = @_;
    printf(">dbg %s\n", $msg);
}

sub run_and_measure {
    my ($cmd) = @_;
    dbg("running $cmd");
    system($cmd);
    dbg("sleeping for $SLEEP_AFTER_COMMAND seconds for current to stabilize");
    sleep($SLEEP_AFTER_COMMAND);
    dbg("taking $NUMBER_OF_MEASUREMENTS samples with $SLEEP_BETWEEN_MEAUREMENTS-second delays");
    my $measurements =  Statistics::Descriptive::Full->new();
    for (my $i = 0; $i < $NUMBER_OF_MEASUREMENTS; $i++) {
	my $tmp = get_current();
	$measurements->add_data($tmp);
	dbg(sprintf("current now %8d, mean %9.4f, deviation %9.4f, range %9.4f",
		    $tmp,
		    $measurements->mean(),
		    $i ? $measurements->standard_deviation() : -1,
		    $measurements->sample_range()));
	sleep($SLEEP_BETWEEN_MEAUREMENTS);
    }
}

system("killall dhclient");
system("ifconfig eth0 down");
system("echo s3c2440-sdi > /sys/bus/platform/drivers/s3c2440-sdi/unbind");
system("rmmod ar6000");
run_and_measure("echo 0 > /sys/class/i2c-adapter/i2c-0/0-0073/pcf50633-mbc/usb_curlim");

run_and_measure("modprobe ar6000");

run_and_measure("echo s3c2440-sdi > /sys/bus/platform/drivers/s3c2440-sdi/bind");

run_and_measure("ifconfig eth0 up");

run_and_measure("iwconfig eth0 essid aalto");

run_and_measure("dhclient eth0");

system("ping -c 10 aallonmurtaja.hut.fi");
system("killall dhclient");

run_and_measure("ifconfig eth0 down");

run_and_measure("echo s3c2440-sdi > /sys/bus/platform/drivers/s3c2440-sdi/unbind");

run_and_measure("rmmod ar6000");

