#!/usr/bin/perl

# программа для генерации картинки с погодными данными
# с кисловодской станции для сайта http://observ.pereplet.ru/

use GD;
use LWP::Simple;
use Date::Manip;
use lib '/home/rel/ivan/nasa/MIME-Lite-3.01/blib/lib/';
use MIME::Lite;

use strict;

$SIG{ALRM}= sub{die "timeout"};

my ($date,@d,$x1,$y1,$im,$tmp,@m,$byte,$SkyTem,$SenTem,$AmbTem,$cond);
my ($white,$black,$brown,$violet,$blue,$red,$remote);
my ($string1,$string2,$date1,$date2,$d1,$d2);
my $m1="79055048408\@sms.beemail.ru";
#my $m2="79055048447\@sms.beemail.ru";
#my $m3="79032077825\@sms.beemail.ru";

eval{
  alarm(220);
  my $txt=get ("http://apollo.sai.msu.ru/");
  if($txt=~m!Sky.*?font color="green">(.*?)\s+(.*?)\s+(.*?)\s+(.*?)</font!is){
    print "[$1] [$2] [$3] [$4]";
    $SkyTem=$1; $SenTem=$2; $AmbTem=$3; $cond=$4;
    chomp $cond;
    print "$SkyTem $SenTem $AmbTem $cond";
    $string1=$1 if $txt=~m!<p align="center">(.*?)</p>!s;
    $string2=$1 if $txt=~m!<font color="green">\n(.*?)</font>!s;
    $date1=&ParseDate($string1);
    $date2=&ParseDate($string2);
    $d1 = UnixDate($date1,"%s");
    $d2 = UnixDate($date2,"%s");
    if ($d1 -$d2 >= 360){
      $m1="79055048408\@sms.beemail.ru";
      &message();
    } else {
      print "";
    }
    
  }
  if($@ and $@=~/timeout/){
#    print "таймаут!\n";
    exit 0;
  }
};

#@d=split(/[ ]+/, scalar localtime);

#$date="$d[0] $d[1] $d[2] $d[3] $d[4]";
$date=qx[perl utc.pl 195.208.220.195];

open F,">>weather.log" or die "cant open weather.log: $!";
print F "$SkyTem $SenTem $AmbTem $cond $date\n";
close F;

exit (0) if $date eq '' or $SkyTem eq '' or $SenTem eq '' or $AmbTem eq '' or $cond eq '';

$im = new GD::Image(160, 65);
&InitColors($im);
$im->transparent($white);
$im->interlaced('true');
$im->rectangle(0, 0, 159, 64, $black); $x1 = 2; $y1 = 2;
$im->string(gdSmallFont, $x1, $y1, " $date", $violet);
$im->string(gdMediumBoldFont, $x1, $y1 + 16, " Sky   Sens   Amb", $blue);
$im->string(gdMediumBoldFont, $x1, $y1 + 32, " $SkyTem $SenTem $AmbTem", $brown);
$im->string(gdMediumBoldFont, $x1, $y1 + 46, " Cond: $cond", $red);

exit(0) if $cond=~m!socket data!is;

open(PICTURE, ">weather_kis.png") or die ("Cannot open file: $!");
binmode PICTURE;
print PICTURE $im->png;
close PICTURE;

sub InitColors {
  $im = $_[0];
  $white = $im->colorAllocate(255,255,255);
  $black = $im->colorAllocate(0,0,0);
  $red = $im->colorAllocate(255,0,0);
  $blue = $im->colorAllocate(0,0,255);
  $brown = $im->colorAllocate(255, 0x99, 0);
  $violet = $im->colorAllocate(255, 0, 255);
}

sub message{
  my $txt=qx[date];
=pod
  my $msg = MIME::Lite->new( From  => 'GRB',
                           To      => "$m1",
                           Subject => 'socket',
                           Type    => 'text/plain',
                           Data    => "MASTER Kislovodsk: socket offline more then 5 min" );
  $msg->send();
=cut
}
