#!/usr/bin/perl

# perl script to format speedtest.net output. Uses the speedtest-cli python script.
# purpose:   read the speedtest.log file, whose columns are separated by ';'.
# usage:     perl speedtest.pl

use strict;
use warnings;

#variables
my $filename = '/home/pi/speedtest.log'; #filename
my $log_line = ""; #last line of file
# run speedtest
system ('/home/pi/speedtest-cli-extras/bin/speedtest-csv >> /home/pi/speedtest.log') == 0
	or die "Speedtest failed\n";
# delete failed (blank) speedtest results
system ('sed -i.bak "/;$/d" speedtest.log') == 0
	or die "Stripping empty records failed";

#read last line of filename
use File::ReadBackwards; #read file backwards
my $bw = File::ReadBackwards->new($filename) or die "can't read file";
    while( defined( $log_line = $bw->readline ) ){
    #split last line of file
        my $str = $log_line;
    #speedtest results
        my (
        $start, #start date and time
        $stop,  #finish date and time
        $from,  #from location
        $from_ip, #from IP
        $server,  #server test run to
        $server_dist, #approx distance to server
        $server_ping, #ping value
        $download, #download speed
        $upload,  #upload speed
        $share_url #speedtest image url
	   ) = split(';', $str);
    #check it works
        print "$start\n";
        print "$stop\n";
        print "$from\n";
        print "$from_ip\n";
        print "$server\n";
        print "$server_dist\n";
        print "$server_ping\n";
        print "$download\n";
        print "$upload\n";
        print "$share_url\n";

    use Time::Piece;
    #reformat $start to std NZ date time
        my $stime = "$start"; #start time string
        my $oldtime = "%Y-%m-%d %H:%M:%S"; #initial format
        my $newtime = "%d-%m-%Y %H:%M:%S"; #wanted format

        chomp $stime;

        $stime = Time::Piece->strptime($stime, $oldtime)->strftime($newtime);
        $start = $stime;

       # print "$start\n";

    #reformat $stop to std NZ date time
        my $etime ="$stop"; #stop time string
        chomp $etime;
        $etime = Time::Piece->strptime($etime, $oldtime)->strftime($newtime);

       # print "$etime\n";

    #get local timezone
        use POSIX;
        my $tz = POSIX::strftime("%Z", localtime());

    #http: to htpps:

        my $find = "http";
        my $replace = "https";
        $share_url =~ s/$find/$replace/i;

    #print "$share_url\n";

    #create php file for include to web page
    open(my $fh, '>', 'speedtest.php');
    print $fh "Latest speed test generated at speedtest.org: $start $tz using a server 
          located at $server";
    print $fh ".";
    print $fh "<br>";
    chomp $share_url;
    print $fh "<a href= '$share_url'>";
    print $fh "<img src= '$share_url' alt='last speedtest failed' style='width:200px; border:0;'>";
    print $fh "</a>";
    close $fh;

#    exit 0;

#post to twitter

    use Net::Twitter;
    use Config::Tiny;
    use Data::Dumper qw(Dumper);
    use File::HomeDir;
 
my $config_file = File::HomeDir->my_home . "/.twitter";
die "$config_file is missing\n" if not -e $config_file;

my $tweet= ("Speedtest at: ". $start ."\n".
            "Download speed: ". $download ."\n". 
            "Upload speed: ". $upload . "\n" .
	    "URL: ". $share_url );

#my $tweet= ("test \n line \n breaks");


my $config = Config::Tiny->read( $config_file, 'utf8' );
 
my $nt = Net::Twitter->new(
    ssl      => 1,
    traits   => [qw/API::RESTv1_1/],
    consumer_key        => $config->{stevewrightwcc}{api_key},
    consumer_secret     => $config->{stevewrightwcc}{api_secret},
    access_token        => $config->{stevewrightwcc}{access_token},
    access_token_secret => $config->{stevewrightwcc}{access_token_secret},
    );

    $nt->update($tweet);

    print "Tweet sent!\n";

exit 0;

    }
