#!/usr/bin/env perl
# ------------------------------------------------------------------
#    made by sputnick in da FreAkY lAb (c) 2009-2011
#    gilles.quenot <AT> gmail <DOT> com
#
#    This program is free software; you can redistribute it and/or
#    modify it under the terms of version 2 of the GNU General Public
#    License published by the Free Software Foundation.
# ------------------------------------------------------------------
#                                                ,,_
#                                               o"  )@
#                                                ''''
# ------------------------------------------------------------------
#

# 20110828

my $loginURL = "https://subscribe.free.fr/login/login.pl";		# URL de login console Free
my $temporisation = 30; 										# secondes d'attente entre chaque essai de téléchargement de l'archive

use strict;
use warnings;
use Getopt::Std;
use WWW::Mechanize;
use Env qw/HOME/;

$| = 1;
my ($login, $password, $cups2freefax_hide_fax_number, $cups2freefax_email_confirmation, $cups2freefax_faxs_store, $url2pdf, @newUrl);
my $dieMessage = $0 . "requiert que le fichier ~/.cups2freefax/cups2freefaxrc ou /etc/cups2freefaxrc soit renseigné avec les logins et password de l'interface Free.";

# Si on est en interactif, on est donc en CLI.
# Si c'est bien le cas, on affiche sur la sortie standard,
# sinon via zenity.
use constant IS_TERMINAL => -t STDIN;

sub printdie {
	if (IS_TERMINAL) {
		print STDERR @_;
		exit(1);
	}
	else {
		qx(zenity --error --title fax4free --text \"@_\");
		exit(1);
	}
} 

sub printout {
	if (IS_TERMINAL) {
		print @_;
	}
	else {
		qx(zenity --info --title fax4free --text \"@_\");
	}
}

printdie("$dieMessage\n") unless -s "$HOME/.cups2freefax/cups2freefaxrc" || -s "/etc/cups2freefaxrc";
my @arr = `cat /etc/cups2freefaxrc $HOME/.cups2freefax/cups2freefaxrc`;
for ( @arr ) {
	if (/=/ and !/(^#|^$)/) {
		chomp;
		s/=/="/;
		eval '$' . $_ . '";';
	}
}

printdie($dieMessage) unless $password && $login;

sub Help {
	printdie("Usage : $0 -d <numero destinataire fax> -f <fichier>\n-d <Numero de fax du destinataire>\n-f <document a faxer>") unless @ARGV;
}

my %opts;

getopt('hl:d:f:', \%opts);

$cups2freefax_hide_fax_number = 'Y' if $cups2freefax_hide_fax_number eq 'yes';
$cups2freefax_hide_fax_number = 'off' if $cups2freefax_hide_fax_number eq 'no';
$cups2freefax_email_confirmation = 1 if $cups2freefax_email_confirmation eq 'yes';
$cups2freefax_email_confirmation = 'off' if $cups2freefax_email_confirmation eq 'no';

my $Doc2Fax = $opts{'f'} or printdie('Argument obligatoire "-f"');
printdie("Le document $Doc2Fax n'existe pas") unless -e $Doc2Fax;

my $destinataire = $opts{'d'} or printdie('Argument obligatoire "-d"');

Help if defined($opts{'h'});

my $m = WWW::Mechanize->new( autocheck => 1 );
$m->agent_alias( 'Linux Mozilla' );
$m->get($loginURL);
$m->submit_form( fields => {
		login => $login, pass => $password, ok => "Connexion"
	}
);
my $authreply = $m->content( format => 'text' );
printdie("Authentification erronée\n") if $authreply =~ /Identifiant incorrect/i;
$m->follow_link( url_regex => qr/\/compte\/console\.pl\?id=.*sommaire=telephone/i );
$m->follow_link( url_regex => qr/\/admin\/tel\/fax\/tel_fax\.pl\?/i );
$m->submit_form( fields => {
		masque 			=> 	$cups2freefax_hide_fax_number,
		destinataire 	=> 	$destinataire,
		email_ack 		=> 	$cups2freefax_email_confirmation,
		document 		=> 	$Doc2Fax
	}
) or printdie("Impossible d'uploader $Doc2Fax: [$!]\n");
my $overflowreply = $m->content( format => 'text' );
printdie("Quota depassé : Vous envoyez trop de fax\n") if $overflowreply =~ m/Vous envoyez trop de fax/i ;

$Doc2Fax =~ s!.*/!!;
printout("Le fax $Doc2Fax a bien été envoyé vers $destinataire.\n");
printout("vous allez recevoir une confirmation via mail.\n") if $cups2freefax_email_confirmation eq 1;

# Partie récupération des archives
exit(0) if $cups2freefax_faxs_store == 0;
mkdir("$HOME/.cups2freefax/envoyes");
chomp($Doc2Fax);

my $c = 1;
until ($c == 20) {
	$m->get($m->uri);
	@newUrl = $m->find_link( url_regex => qr/tel_dlfax\.pl\?id=\w+\&idt=\w+\&fichier=$Doc2Fax\&msg=\w+&type=tx/ );
	next unless @newUrl;	

	for ( @newUrl ) {
		$url2pdf = $_->url();
		$m->get( "https://adsls.free.fr/admin/tel/fax/$url2pdf", ':content_file' => "$HOME/.cups2freefax/envoyes/$Doc2Fax" )
			or printdie("Il n'a pas été possible de récupérer $Doc2Fax sur la console Free...\n");
	}

	last if -s "$HOME/.cups2freefax/envoyes/$Doc2Fax";
    sleep($temporisation);
}

# Un peu trop d'infos affichées, non ? Ca fait cliquer trop souvent pour valider.
-s "$HOME/.cups2freefax/envoyes/$Doc2Fax" ? printout("$Doc2Fax récupéré\n") : printdie("Téléchargement impossible de $Doc2Fax après 10 tentatives espacées de $temporisation secondes");
