#!/bin/sh
#
# This file is part of the battery-stats package.
# Copyright (C) 2016 Petter Reinholdtsen <pere@hungry.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software

input=/var/log/battery-stats.csv
filename="${1}"
flowfilename=$(mktemp)

perl -MText::CSV <<'EOF' > "$flowfilename" 
use strict;
use warnings;

my $csv = Text::CSV->new();
my $fh;
open $fh, "<:encoding(utf8)", '/var/log/battery-stats.csv'
  or die "open failed: $!";

my $last2 = undef;
my $lasttime2 = undef;
my $last = undef;
my $lasttime = undef;
my @fieldsrow =  $csv->getline($fh);
my $levelrow = 8; # energy_now
while (my $row = $csv->getline($fh) ) {
    if (defined $last2) {
        my $diff = $row->[$levelrow] - $last2;
        my $timediff = $row->[0] - $lasttime2;
        if (0 < $timediff) {
            printf "%s,%.2f\n", $row->[0], $diff / $timediff;
        }
    }
    $last2 = $last;
    $lasttime2 = $lasttime;
    $last = $row->[$levelrow];
    $lasttime = $row->[0];
}
$csv->eof or $csv->error_diag();
close($fh);

EOF

# manufacturer,model_name,technology
type=$(head -2 "$input" | tail -1 | cut -d, -f2-4 | tr , " ")

(
    echo set xdata time
    echo set timefmt \"%s\"
    echo set format x \"%Y\"
    echo set datafile separator \",\"
    echo set title \'Battery statistics $type\'
    echo set ylabel \'Flow per second\'
    echo set xlabel \'Year\'
    echo set grid
    if [ "$filename" ]; then
        echo set term png
        echo set output \"$filename\"
    fi
    echo plot "\"$flowfilename\" using 1:2 smooth unique axis x1y1 title \"Energy flow\" with lines"

) | gnuplot -p

if [ "$filename" ] ; then
    echo "PNG graph $filename created."
fi

rm $flowfilename
