#!/usr/bin/perl

#use strict;
use DBI;
use Chart::Gnuplot;
use File::Temp qw(tempfile);

#
# Fix for GNUPLOT font error
#
$ENV{'GDFONTPATH'} = '/usr/share/fonts/default/Type1';
$ENV{'GNUPLOT_DEFAULT_GDFONT'} = 'n019063l.pfb';

$dbh = DBI->connect(
    "dbi:mysql:dbname=mydb",
    "root",
    "",
    {RaiseError => 1 },
) or die $DBI::errstr;

$sth = $dbh->prepare( "SELECT sample_time,ext_temp FROM ra24_test WHERE sample_time BETWEEN '2015-04-29 00:00:00' AND '2015-04-29 00:01:00'" );
$sth->execute();

$tmp_fh = new File::Temp( Unlink => 1 );
#print "temp filname:  $tmp_fh\n";

while(($sample_time,$ext_temp) = $sth->fetchrow()){
  push	@times, $sample_time;
  push	@temps, $ext_temp;
  print $tmp_fh "$sample_time $ext_temp\n";
#  print "$sample_time $ext_temp\n";
  }

#$fields = $sth->{NUM_OF_FIELDS};
#print "We have selected $fields field(s)\n";

#$rows = $sth->rows();
#print "We have selected $rows row(s)\n";

$sth->finish();
$dbh->disconnect();

$x_format_str = "%M:%S";
$set_xlabel = "set xlabel \"Time mm:ss\"";
#$set_xrange = "set xrange [4:5]";
#$set_yrange = "set yrange [-1:1]";

#Generate GNUPlot
$script = <<"EndScript";
#set terminal png x000000 xdddddd x004400
set terminal x11
set size .75,.5
set xdata time
set timefmt "%Y-%m-%d %H:%M:%S"
set format x "$x_format_str"
$set_xrange
$set_yrange
set grid
set key samplen 1
set xtics nomirror
set xtics rotate
set ytics nomirror
set ylabel "Degress F"
$set_xlabel
set title "EOI Room Temperature"
$set_output
EndScript

$opt{'LastN'} = 120;
$linestyle = "lines";
$plot_color = "ls 2";

#$script .= "plot \"<tail -$opt{'LastN'} /webdata/MarsDCSData/ra24/ra24.dat\" using 1:5 title \"\" with $linestyle $plot_color\n";
#$script .= "plot \"<tail -$opt{'LastN'} $tmp_fh\" using 1:2 title \"\" with $linestyle $plot_color\n";
$script .= "plot \"$tmp_fh\" using 1:3 title \"\" with $linestyle $plot_color\n";

#print "$script\n";
seek $tmp_fh, 0, 0 or die "Seek $tmp_fh failed: $!\n";
#while (<$tmp_fh>) {
#  print "$_";
#}
#exit;

#Execute script
open(GP,"|/usr/bin/gnuplot");
print GP $script;
close(GP);
sleep 30;
exit;
