#!/usr/bin/perl -w
# Fet per David Alcobero Pinyot
# Last update: 26/09/08
#

use WWW::Mechanize;

use strict;
use warnings;
use Crypt::Lite;
###############################
my $dir='/home/anguila/Projectes/cvNews';
###############################
my $crypt = Crypt::Lite->new( debug => 0,encoding => 'hex8' );
my $agente = WWW::Mechanize->new( cookie_jar => {} );
my $seek=(getpwuid($<))."cvnews";
my $user;
my $Epass;

$agente->get('https://cv2008.uab.cat');
$agente->success or die "Error! No s'ha pogut conectar al campus virtual!\n";
open (FILE,"$dir/cvnews.conf") or die "No es pot accedir al arxiu de configuracio\n";

foreach (<FILE>){
	if ($_ =~ /user=(\S+)/){
		$user=$1;
	}
	if ($_ =~ /password=(\S+)/){
		$Epass=$1;
	}
}
close FILE;
chomp($user);
chomp($Epass);

my $pass= $crypt->decrypt($Epass, $seek);

my $res = $agente->submit_form(
    with_fields => {
                    j_username => $user,
                    j_password => $pass,
                    },
    button      => 'Entrar',
);
if ($res->is_success ) {
	my $val=$agente->content(format => 'text');
	my @casos=($val=~/novetats!\s\s(\D+)\sGD/g);
	if ($#casos eq -1) {
		if ($#ARGV ne -1 and $ARGV[0] eq "-avisar"){
			system("gmessage -timeout 10 -geometry 300x150 -buttons Ok -center -title 'Novetats en el CV!' -name cvNews No hi ha novetats!");
		}
	}
	else {
		open(FILE,">news");
		foreach (@casos){
			chomp;
			print FILE "$_\n";
		}
		system("gmessage -timeout 10 -geometry 300x150 -buttons Ok -center -file $dir/news -title 'Novetats en el CV!' -name cvNews");
		system("rm news");
	}
}
else {
	print "No s'ha pogut establir la connexió al campus virtual!\n";
}
