#!/usr/bin/perl 

# Twitter @sismos_cl NO oficial del Servicio Sismológico de la Universidad de Chile
# Copyright (C) 2009 - Luis León Cárdenas Graide < lcardena [@] dcc [.] uchile [.] cl >
#
# 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 3 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, see <http://www.gnu.org/licenses/>.
#
#
# If you think this is useful, you can donate to the author:
# https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=1290721
# Thank you, very much.

use strict;
use warnings;

use Getopt::Std qw/ getopts /;

use YAML qw/ Dump /;

my $twidge = qx{ which twidge };
$twidge = '' unless defined $twidge;
chomp $twidge;
die 'twidge not found in PATH' unless length $twidge;
die "Can't execute $twidge" unless -x $twidge;

my %opts = (
    c => "$ENV{HOME}/.twidgerc-sismos_cl",                      # Twidge RC file
    C => "$ENV{HOME}/.sismos_cl",                               # Cache
    f => 0,                                                     # Borra C
    t => 0,                                                     # Test mode
    u => 'http://ssn.dgf.uchile.cl/cgi-bin/autoproc_intra.pl',  # URL
    v => 0,                                                     # Verboso
    d => 0,                                                     # Debug
    h => 0,                                                     # Help
    i => 0,                                                     # Interactivo
);
unless ( getopts( 'c:C:u:tfvdhi', \%opts ) ) {
    print "Unknown option\n";
    exit 2;
}
if ( $opts{h} ) {
    print <<'EOT';
Twitteador NO oficial del Servicio Sismologico de la Universidad de Chile
Version 1.2

COPYRIGHT 2009 '(C)' Luis León Cárdenas Graide '< lcardena [@] dcc [.] uchile [.] cl >'

Usage:

sismos_cl.pl [options]

Options:

-h: This help.
-t: Test mode. Doesn't twit.
-v: Verbose. Shows information.
-d: Debug mode. Shows more low-level information.
-i: Interactive mode. Confirms operation before tweeting.
-f: Forces full update. By default, it remembers the last twitted information in order to avoid duplicated tweets. This options "forgets" what has been previously twitted and tweets everything again.
-u URL: The URL where to get the information from. Defaults to "http://ssn.dgf.uchile.cl/cgi-bin/autoproc_intra.pl".
-c TWIDGE_CONFIG_FILE: Location of Twidge's configuration file with your Twitter account's login information. Defaults to "$HOME/.twidgerc-sismos_cl".
-C CACHE_FILE: The file where to remember (see -f) the last twitted information. Defaults to "$HOME/.sismos_cl".
 
Requires:

Twidge, wget, cat, echo

LICENSE:
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 3 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, see <http://www.gnu.org/licenses/>.


If you think this is useful, you can donate to the author:
https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=1290721
Thank you, very much.

CHANGELOG

2009-07-17 v1.2: + Shorter Lat,Long and Richter
2009-07-07 v1.1: + Supports interactive option (-i).

EOT

    exit;
}
my $v = $opts{v} ? sub { print @_; } : sub { };
my $d = $opts{d} ? sub { print @_; } : sub { };
die $opts{c} unless -r $opts{c};
unlink $opts{C} if $opts{f};

my @cmd = ( 'cat', quotemeta $opts{C} );
my $cmd = join ' ', @cmd;
my $ultimoSismo = qx{ $cmd  };
chomp $ultimoSismo;
$v->( Dump($ultimoSismo) );

@cmd = ( qw/ wget -q -O - /, quotemeta $opts{u} );
$cmd = join ' ', @cmd;

my ( $l, $lDef ) = ( '', '<tr align=center>' );
my @sismos;
open W, "$cmd|";
LOOP: while ( defined $l ) {
    $d->("LOOP $l");
    unless ( $l =~ m!<tr +align=center *>!i ) {
        $l = <W>;
        next;
    }
    defined( $l = <W> ) || last;    # ID
    $d->(": $l");
    my @campos = \( my ( $fecha, $hora, $long, $lat, $prof, $int, $loc ) );
    foreach my $r (@campos) {
        defined( $$r = $l = <W> ) || last;
        $d->(": $l");
    }

    #<TH><font size=-1>30/06/2009</TH>
    ( ($fecha) = $fecha =~ m!>(\d+/\d+/\d+)</th>!i ) || next;
    $fecha = sprintf '%02d/%02d/%04d', split '/', $fecha;
    $d->(": $fecha\n");

    # <TH><font size=-1>20:26 <img  src=/images/share/autoproc/but_r.gif></TH>
    ( ($hora) = $hora =~ m!>(\d\d:\d\d) *<!i ) || next;
    $hora = sprintf '%02dh%02dm', split ':', $hora;
    $d->(": $hora\n");

    my $id = "${fecha}-$hora";
    $d->(": $id = $ultimoSismo\n");
    last if $id eq $ultimoSismo;

    # <TH><font size=-1>-32 40' 4'' </TH>
    # <TH><font size=-1>-71 29' 45'' </TH>
    foreach my $r ( \( $long, $lat ) ) {
        ( my ( $g, $m, $s ) = $$r =~ m!>(-?\d+) +(\d+)' +(\d+)'' *</th>!i )
          || next LOOP;
        $$r = sprintf '%dg%d\'%d"', $g, $m, $s;
        $d->(": $$r\n");
    }

    # <TH><font size=-1>22.7</TH>
    ( ($prof) = $prof =~ m!>(\d+\.\d+)<! ) || next;    # Km
    $prof += 0;
    $d->(": $prof\n");

    # <TH><font size=-1>3.8</TH>
    ( ($int) = $int =~ m!>(\d+\.\d+)<! ) || next;
    $int += 0;
    $d->(": $int\n");

# <TH align=left><font size=-1><a href="/new_autoproc/data/EVT20090701_002611.a/mapa.jpg">8 km NO PUCHUNCAVI</a></TH>  <TH><font size=-1><a href="/new_autoproc/data/EVT20090701_002611.a/2009-07-01-0026-03S.APIC1_015.gif">8</a></TH>  <TH><font size=-1>0.8</TH>  <TH><font size=-1><a href="/new_autoproc/data/EVT20090701_002611.a/print.out">HYP</a></TH>  <TH><font size=-1><a href="/new_autoproc/data/EVT20090701_002611.a/hyp.out">01-0026-03L.S200907</a></TH></TR><TR align=center>
    ( ($loc) = $loc =~ m!/mapa\.jpg">([^<]+)</a>! ) || next;
    $d->(": $loc\n");
    $loc =~ s/ +km +(\w+) +/Km @ $1 d / || next;

    push @sismos, [ $id, $fecha, $hora, $lat, $long, $prof, $int, $loc ];
    $v->( Dump( $sismos[-1] ) );
    $l = $lDef;
}
close W;
unless (@sismos) {
    $v->("Nada que hacer: $ultimoSismo\n");
    exit;
}
my @msgs;
while ( my $sismo = pop @sismos ) {
    my ( $lat, $long ) = @{$sismo}[ 3, 4 ];
    foreach my $r ( \( $lat, $long ) ) {
        my ( $g, $m, $s ) = $$r =~ m!(-?\d+)g(\d+)'(\d+)"!;
        my $ss = ( 60 * $m + $s ) / 3600;
        my ($sss) = $ss =~ /^0?\.(\d{0,6})/;
        $$r = "$g.$sss";
    }

    my $urlGmaps = sprintf 'http://maps.google.com/?ll=%s,%s&z=8', $lat, $long;

    foreach my $par ( [ 4, 'E', 'O' ], [ 3, 'N', 'S' ] ) {
        $sismo->[ $par->[0] ] .=
          ( @{$par}[ 1, 2 ] )[ $sismo->[ $par->[0] ] =~ s/^-// ];
    }
    my $msg = sprintf '#Sismo #Temblor %s %s %s,%s Prof:-%sKm %sRchtr %s %s',
      @{$sismo}[ 1 .. $#{$sismo} ], $urlGmaps;
    push @msgs, [ $sismo->[0], $msg ];
}

my $lastMsg = undef;
foreach my $msg (@msgs) {
    my ( $id, $txt ) = @{$msg};
    print "$txt\n";
    my $cmd = sprintf '%s -c %s update %s',
      map { quotemeta $_ } ( $twidge, $opts{c}, $txt );
    $d->("$cmd\n");
    unless ( $opts{t} ) {
        if ( $opts{i} ) {
            print "Tweet? (sSyY/n[N])? ";
            my $yn = <STDIN> || 'n';
            unless ( $yn =~ /^y/i ) {
                print "Tweet discarded\n";
                next;
            }
        }
        system $cmd;
        $lastMsg = $msg;
    }
    $d->( print "\n" );
}
system(
    sprintf( 'echo %s >%s', map { quotemeta $_ } ( $lastMsg->[0], $opts{C} ) ) )
  if defined $lastMsg;

