#!/usr/bin/perl
#     esms, envo de mensajes a mviles de Espaa 
# 		http://esms.sourceforge.net
#     Copyright (C) 2001 Jos Juan Zapater Vera josej@zapater.fdns.net
#     Programa original de (c) Mauricio Julio Fernndez Pradier
#					  batsman.geo@yahoo.com
#         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 2 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, write to the Free
#     Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
#	ChangeLog
#		2000/2001	Mauricio Julio Fernndez Pradier
#				esms hasta versin 0.9.0
#		01/07/2001	0.9.0a
#				Jos Juan Zapater Vera
#				limpieza del cdigo, correccin para
#				adaptarse a los cambios del servidor de
#				Navegalia
#		06/07/2001	0.9.0
#				Mauricio Julio Fernndez Pradier
#				cambios para que funcione con los
#				mdulos de Potato, pequeas
#				modificaciones
#		30/07/2001	0.9.1
#				Incorporacin del servidor de mensajes de
#				Movistar.
#				Creada estructura para multiples servidores
#				de forma cmoda.
#				Eliminado el parmetro de columnas porque
#				est derivado del servidor.
#		02/09/2001	0.9.2
#				Incorporacin del parche de  Gorka Olaizola 
#				<gorka@escomposlinux.org>, ahora las
#				opciones se leen con GetOpt.
#		08/09/2001	0.9.3
#				La firma se especifica en el fichero de
#				opciones. Cierra bug #111619 de Debian.
#		07/10/2001	0.9.4
#				Cambio del user-agent por uno ms comn.
#				Opciones --license y --reverse
#				Personalizacin del email de envo.
#				Aade espacio entre xx/yy y firma.
#				Cierra los bugs de Debian
#				#113485 #113483 #113971
#		13/10/2001	0.9.5
#				Uso de proxy con la variable de entorno
#				http_proxy. Gracias a Antonio Luque
#				Estepa :-)
#				Servidor por defecto especificable en
#				~/.esmsrc. Cierra bug de Debian #117422.

use CGI;
use Text::Wrap qw(wrap $columns);
use LWP::UserAgent;
use HTTP::Cookies;
use HTTP::Request::Common qw(POST GET);
use HTML::TreeBuilder;
use IO::Socket;
use Getopt::Long;
use strict;


my $version ="0.9.5";

# Definicin de los plugins (servidores de mensajes SMS)
# NombreCorto, Descripcin, N de columnas, Funcin, Usar correo?
my @plugs = ( 	[ "navegalia", "Servidor de Airtel", 130, \&enviar_mensaje_navegalia, 0, ],
		[ "movistar", "Servidor de Movistar", 160,  \&enviar_mensaje_movistar, 1, ]
		);
my $plug = -1;
my $plugname="";

my $debug = 1;
my $nreintentos = 5; # debera haber un parmetro en la lnea de comandos
my $errorconexion = 0; # puesto a uno si el servidor est hundido

sub espera
{
    my $tiempo= pop @_;
    print "Esperando $tiempo segundo(s)...\n" if ($debug);
    select(undef,undef,undef,$tiempo); 
    # granularidad menor que un segundo
}

sub pretty_print()
{
 my $mensaje = pop @_;
 print 
 "-------------------------------------------------------------------------\n" .
 "$mensaje\n" . 
 "-------------------------------------------------------------------------\n";
}


sub obtener_email
{
 my $fichero;
 $fichero = $ENV{"HOME"} . "/.esmsrc";
 open(INPUT, $fichero);
 while (<INPUT>) {
	chop($_);
	if ( /^Email\:/ ) {
		s/^Email\:[ \t]*//g;
		close(INPUT);
		return $_;
	}
 }
 close(INPUT);
 return "me\@example.com";
}


sub obtener_firma
{
 my $fichero;
 $fichero = $ENV{"HOME"} . "/.esmsrc";
 open(INPUT, $fichero);
 while (<INPUT>) {
	chop($_);
	if ( /^Firma\:/ ) {
		s/^Firma\:[ \t]*//g;
		close(INPUT);
		return $_;
	}
 }
 close(INPUT);
 return "MFP";
}

sub obtener_servidor
{
 my $fichero;
 $fichero = $ENV{"HOME"} . "/.esmsrc";
 open(INPUT, $fichero);
 while (<INPUT>) {
	chop($_);
	if ( /^Servidor\:/ ) {
		s/^Servidor\:[ \t]*//g;
		close(INPUT);
		return $_;
	}
 }
 close(INPUT);
 return "navegalia";
}


sub obtener_telefono
{
  my $alias = pop @_;
  my $fichero;
  $fichero = $ENV{"HOME"} . "/.esmsalias";
  print "Abriendo fichero de alias $fichero.\n";
  print "Buscando telfono de $alias.\n";
  open(INPUT, $fichero);
  while (<INPUT>) {
	chop($_);
        ##	print "Leda lnea $_.\n";
  	if ( /^$alias/ ) {
		s/^$alias[ \t]*//g;
		close(INPUT);
		return $_;
	}
  }
  close(INPUT);
  return 0;
}


sub enviar_mensaje_navegalia
{
 my ($linea, $telefono, $repeat) = @_;
 my $ua = new LWP::UserAgent;
 $ua->agent("Mozilla/4.0 [en] (compatible; MSIE 4.01; Windows NT)");
 $ua->env_proxy();  
 
 my $req = GET 'http://212.73.32.207/html/texto.htm', [ tNumber=>$telefono, nAddress=>"ttt\@ttt.es" ];
 $req->header ( Referer =>
  "http://212.73.32.207/html/c_01.htm");
 my $res=$ua->request($req);
 
 unless($res->is_success || $errorconexion) {
	print "Error en la peticin HTTP.\n";
	print "El servidor no funciona correctamente en este momento.\n";
	print "Intntelo ms tarde o comunqueselo a los autores de esms.\n";
	$errorconexion = 1;
 	return 1;
 }
 if($res->is_success) { 
 	$errorconexion = 0; 
 } else {
	return 1;
 }
 
 my $tree = HTML::TreeBuilder->new();
 $tree->ignore_text(1);
 $tree->parse($res->content);
 
 my $form = $tree->find_by_attribute('name','envio_sms');
 my $action=$form->attr_get_i('action');
 my $value1=$form->find_by_attribute('name','estado1')->attr_get_i('value');
 my $value2=$form->find_by_attribute('name','estado2')->attr_get_i('value');

 #print "Usando action=$action, estado1=$value1, estado2=$value2.\n" if($debug);

 $req= POST $action, [ estado1 => $value1, estado2 => $value2,
    telefonoDestino1 => $telefono, codigoLookFeel => 1, tNumber => "", nAddress => "", texto => $linea];
 $req->header ( Referer => "http://212.73.32.207/html/texto.htm?$telefono");

 &espera(($repeat-1)*2+0.1); #Tengo que hacer pausa que si no no cuela

 $res=$ua->request($req);
 
 # elimina rbol HTML, el reference counting falla
 #$tree->destroy;
 # aunque est en la documentacin, no est en el paquete para potato
 # ??

 # depuracin a lo bestia
 # print $res->content if ($debug);
 
 if ($res->content =~ /no se est procesando correctamente/) {
     print ( "Error al enviar el mensaje:\n" );
     &pretty_print($linea);
     return 1;
 }
 else {
     print "Mensaje enviado correctamente\n" if ($debug);
     return 0;
 }
}

sub enviar_mensaje_movistar
{
 my ($linea, $telefono, $repeat) = @_;
 my $ua = new LWP::UserAgent;
 $ua->agent("Mozilla/4.0 [en] (compatible; MSIE 4.01; Windows NT)");
 $ua->env_proxy();  

 # Obtenemos cookies

 my $cookie_jar = HTTP::Cookies->new;

 my $req = POST 'http://www.correo.movistar.net/enviar_mensajes.asp';
 my $res = $ua->request($req);
 $cookie_jar->extract_cookies($res);
 
 $req= POST 'http://www.correo.movistar.net/confirmacion_envio.asp', [ confirmacion => 0,
    nocache => "7%2F24%2F01+5%3A53%3A55+PM",
    telefono => $telefono, email => &obtener_email(), mensaje_texto => $linea];
 $req->header ( Referer => "http://www.correo.movistar.net/enviar_mensajes.asp");
 $cookie_jar->add_cookie_header($req); 
 
 my $res=$ua->request($req);
 
 # depuracin a lo bestia
 # print $res->content if ($debug);
 
 if (!($res->content =~ /enviado con xito/)) {
     print ( "Error al enviar el mensaje:\n" );
     &pretty_print($linea);
     return 1;
 }
 else {
     print "Mensaje enviado correctamente\n" if ($debug);
     return 0;
 }
}

sub enviar_mensaje{
 my ($linea, $telefono, $repeat) = @_;
 print "- Servidor $plugs[$plug][0] -\n";
 my $func = $plugs[$plug][3];
 &$func($linea,$telefono,$repeat);
}

sub license{
	print "esms $version, Copyright  2000, 2001 Mauricio Julio Fernndez Pradier\n";
	print "                                                   batsman.geo\@yahoo.com\n";
	print "         2001 Jos Juan Zapater Vera               josej\@zapater.fdns.net\n";
	print "         2001, Gorka Olaizola                      gorka\@escomposlinux.org\n\n";
	print "esms comes with ABSOLUTELY NO WARRANTY. This is free software,\n";
	print "and you are welcome to redistribute it under certain conditions.\n";
	print "\n";
	print "Ms informacin en http://esms.sourceforge.net \n\n";
	exit(3);
}

sub help{
	printf "esms $version\n";
	print "Uso: esms [-s --server servidor] [--license] [-r --reverse] <telefono|alias>\n\n";
	for(my $n=1;$n<=scalar(@plugs);$n++){
		print "\t-s ",$plugs[$n-1][0],": ",$plugs[$n-1][1],"\n";
	}
	print "\nEjemplo:\n";
	print " fortune -s | esms -s movistar Linus\n";
	print " uname -a | esms 12345678 \n";
	print "\nEl primero buscar 'Linus' en el fichero de alias\n";
	print	"\t\t" . $ENV{"HOME"} . "/.esmsalias\n";
	print "Ejemplo de .esmsalias:\n";
	print "yo      123456789\n";
	print "Linus   1111111111\n";
	print "\nAdicionalmente, puede especificarse la firma, el servidor a utilizar por defecto\n";
	print "y la direccin de correo electrnico ";
	print  "con el fichero " . $ENV{"HOME"} . "/.esmsrc\n";
	print "Algunos proveedores aaden esta direccin al mensaje enviado.\n";
	print "La direccin debe ser vlida, aunque no exista.\n";
	print "Ejemplo de .esmsrc:\n";
	print "Firma: Rafa\n";
	print "Email: yo\@isp.com\n";
	print "Servidor: navegalia\n";
	exit(3);
}

my $telefono = 0;
my $reverse = 0;

if (!GetOptions(
	"server=s" => \$plugname,
        "help" => \&help,
	"license" => \&license,
        "reverse" => \$reverse ) ) {
	&help;
}

$telefono = $ARGV[0];
if ($telefono eq ""){
	help();
}


my $prefserv = &obtener_servidor();
#print "Obtenido favorito: $prefserv.\n";
$plug=-1;
for(my $n=1;$n<=scalar(@plugs);$n++){
	if ($plugs[$n-1][0] eq $prefserv){
		$plug=$n-1;
	}
}


my $name=$telefono;

if ( $telefono !~ /^[0-9]+/ ) {
	$telefono = &obtener_telefono($telefono);
}
print "Telfono obtenido: $telefono.\n";
if ($telefono == 0)
{
	print "No se pudo encontrar el telfono asociado a $name.\n";
	exit(2);
}

if ( !($plugname eq "") ) {
	for(my $n=1;$n<=scalar(@plugs);$n++){
		if ($plugs[$n-1][0] eq $plugname){
			$plug=$n-1;
		}
	}
	if ($plug==-1) {
		&help;
	}
}

for(my $i=0; $i < scalar(@plugs); $i++) {
	$plugs[$i][2] -= 6 + length( &obtener_firma() );
	if ( $plugs[$i][4] == 1 ) {
		$plugs[$i][2] -= length( &obtener_email() );
	}
}

$columns=$plugs[$plug][2];
my @in = <STDIN>;
my $mensaje = join ('', @in);

$mensaje =~ s/\n/\/g;
$mensaje =~ s/\t/ /g;
my $linea = wrap ("","",$mensaje);
my @lineas = split(/\n/,$linea);
my $numlineas = @lineas;
$mensaje =~ s/\/\n/g;
$| = 1; ## turn auto-flush on

print "Envo de mensaje a mvil\n";
print "Telfono: $telefono\n";
print "Mensaje:\n";
&pretty_print($mensaje);

print "El mensaje ha sido fragmentado en $numlineas paquetes.\n"
    if ($numlineas > 1);
print "El mensaje no ha sido fragmentado.\n"
    if ($numlineas == 1);
my $j=1;

if ( $reverse == 0 ) {
for (my $i=1; ($i<=$numlineas) && ($j<=$nreintentos); $i++){
    $lineas[$i-1] =~ s/\/\n/g;
    $j=1;
    while ($j<=$nreintentos && &enviar_mensaje("$lineas[$i-1]\n$i/$numlineas " . &obtener_firma(), $telefono, $j )!=0){
	$j++;
    }
} 
}
else {

for (my $i=$numlineas; ($i>=1) && ($j<=$nreintentos); $i--){
    $lineas[$i-1] =~ s/\/\n/g;
    $j=1;
    while ($j<=$nreintentos && &enviar_mensaje("$lineas[$i-1]\n$i/$numlineas " . &obtener_firma(), $telefono, $j )!=0){
	$j++;
    }
} 

}
if ($j<=$nreintentos){
   exit(0); # Sin errores
}
else{
   exit(1); # Con errores
}

