#!/usr/bin/perl
#$Id: celltest_updater.pl,v 1.8 2015/11/03 12:41:34 sqko Exp $
use strict;
use warnings;
use LWP::Simple;
use LWP::UserAgent;
use HTTP::Request;
use HTTP::Response;
use HTML::LinkExtor; # allows you to extract the links off of an HTML page.
use SemaforeFile;
use RFC::Header;
use RFC::Main;
use RFC::Rig;
my $proxy = get_cv('main','proxy');

my $debug = 0;
my $user = $<;
if ($user != 0)
{
    print "must be root to run!\n";
    if (!$debug)
    {
        exit 0;
    }
}

my $force = 0;
$force = 1 if (@ARGV && $ARGV[0] eq '-f');

sub mydie($)
{
    my $s = shift;
    chomp $s;
    print $s,"\n";
    die $s,"\n";
}


my $hostfile = SemaforeFile->new('/home/celltest/update_host.txt');
my @lines = $hostfile->readlines();
die "No host information found!" unless (@lines > 2);
my $host = $lines[0];
my $path = $lines[1];
my $file = $lines[2];
my $keyfile = 'http://'.$host.$path.$file;
my $local_build = SemaforeFile->new('/home/celltest/build');
$local_build->open_read;
my $local_version = $RFC::Header::VERSION.'-'.$local_build->readline;
$local_build->close;
chomp $local_version;

my $browser = LWP::UserAgent->new();
$browser->timeout(10);

my $t = localtime();
print $t,"\n";
print "Fetching version from $keyfile\n";
my $request = HTTP::Request->new(GET => $keyfile);
if ($proxy)
{
    $ENV{HTTP_proxy} = $proxy;
    $request->env_proxy;
}
my $response = $browser->request($request);
if ($response->is_error()) {
    printf "%s\n", $response->status_line;
    exit;
}
my $content = $response->content();
chomp $content;
if ($content eq $local_version)
{
    print "RFCcontrol system up to date\n";
    exit;
}
if ($content =~ /^([\d\.]+)/)
{
    my $v = $1;
    my $f = 'http://'.$host.$path.'RFCcontrol-'.$v.'.tgz';
    print "Fetching new version from $f using wget\n";
    my $cmd = '/usr/bin/wget '.$f.' -O /root/RFCcontrol-'.$v.'.tgz';
    if ($proxy)
    {
        $cmd .= ' -e use_proxy=yes -e http_proxy='.$proxy;
    }
    system($cmd);
    chdir '/root/';
    $cmd = '/bin/tar -xzf RFCcontrol-'.$v.'.tgz';
    print "Extracting new source.....\n";
    system($cmd);
    chdir 'RFCcontrol/';
    system('make') == 0 or mydie("Make failed! aborting update.");
    my $string = localtime();
    if ($force)
    {
	system('make update_force') == 0 or mydie("Make update force failed! System possibly in an incomplete/undefined state!.");
	$string .= ": RFCcontrol system force updated to version $content";
    }
    else
    {
	system('make update') == 0 or mydie("Make update failed! System possibly in an incomplete/undefined state!.");
	$string .= ": RFCcontrol system updated to version $content";
    }
    my @rigs = RFC::Main::get_rigs();
    foreach (@rigs)
    {
	my $rig = RFC::Rig->new($_);
	$rig->info($string);
	my $file = SemaforeFile->new($RFC::Header::publicdir.'rig'.$rig->name.'/logbook.txt');
	$file->append($string);
    }
    print "\nDone udating RFCcontrol!\n\n";
}


