#!/usr/bin/perl

# -------------------------------------------------------------------------------------
# Project:      : hcl
# File          : hclGUI
# Author        : Keerthan Muthurasa <kmuthurasa at mandriva dot com>
# Created On    : Mon Aug 27 11:15:03 2007
# Purpose       : Graphical hcl interface allowing user to send hardware information
#                 in order to send it to a remote server
# -------------------------------------------------------------------------------------


use strict;
use lib qw(/usr/lib/libDrakX /usr/lib/libDrakX/drakfirsttime);
BEGIN { $::no_global_argv_parsing = 1 }

use interactive;
use common;
use wizards;
use lang;
use SOAP::Lite;
use Getopt::Long;

BEGIN { unshift @::textdomains }
$ugtk2::wm_icon = '/usr/share/icons/large/mdkonline.png';

my ($email,$ia);
my $result;
my @line_;
my $in;
my %choices;
my $locale;
my $lang;
my $choice;
my %account;
my $account_;
my $wiz;
my $next;
my $greeting;
my @greets;
my $firstname;
my $lastname;
my $passwd;
my $confirmpasswd;
my %countries;
my $country;
my @info;
my $alias;
my $uri;
my $proxy;
my $soap;
my $release_file;
my $next='data_send';

$ia = 1;
$uri ='https://my.mandriva.com/soap/';
$proxy ='https://my.mandriva.com/soap/';
$soap =SOAP::Lite->uri($uri)->proxy($proxy);

GetOptions('interactive!' => \$ia);
if(-e "/etc/hcl/hclemail")
{
	open(MAIL,"/etc/hcl/hclemail");
	while(<MAIL>)
	{
		@line_ = split('=',$_);
		$line_[1] =~ s/\s+$//;
		$email = $line_[1];
	}
	close(MAIL);
}

sub soap_create_account 
{
	my $data = $soap->registerUserFromWizard(@_)->result;
	$data;
}

sub soap_authenticate_user 
{
        my $data = $soap->authenticateUser(@_)->result;
        $data;
}

sub create_authenticate_account 
{
	my $type = shift;
	my @info = @_;
	my ($response, $ret);
	my $action = {
		             create => sub { eval { $response = soap_create_account(@info) } },
		             authenticate => sub { eval { $response = soap_authenticate_user(@info) } }
		     };	     
	$action->{$type}->();
	$ret = check_server_response($response);
	$ret;
}

sub check_server_response 
{
	my ($response) = shift;
	my $hash_ret = {
				1  => [ N_("Security error"), N("Generic error (machine already registered)") ],        
				2  => [ N("Database error"), N("Server Database failed\nPlease Try again Later") ],
				3  => [ N("Registration error"), N("Some parameters are missing") ],
				5  => [ N("Password error"), N("Wrong password") ],
				7  => [ N("Login error"), N("The email you provided is already in use\nPlease enter another one\n") ],
				8  => [ N("Login error"), N("The email you provided is invalid or forbidden") ],
				10  => [ N("Login error"), N("Email address box is empty\nPlease provide one") ],
				12  => [ N("Restriction Error"), N("Database access forbidden") ],
				13  => [ N("Service error"), N("Mandriva web services are currently unavailable\nPlease Try again Later") ],
				17  => [ N("Password error"), N("Password mismatch") ],
				20  => [ N("Service error"), N("Mandriva web services are under maintenance\nPlease Try again Later") ],
				22  => [ N("User Forbidden"), N("User account forbidden by Mandriva web services") ],
				99  => [ N("Connection error"), N("Mandriva web services not reachable") ]
			};
			
		foreach my $num ([9, 8], [21, 20]) { $hash_ret->{$num->[0]} = $hash_ret->{$num->[1]} };
		my $code = $response->{code} || '99';
		my $answer = $response->{code} eq 0 ? 'OK' : $hash_ret->{$code} ? $hash_ret->{$code}[0] . ' : ' . $hash_ret->{$code}[1] . "\n\n" . $response->{message} : $response->{message};
		return $answer;
}

sub check_valid_email 
{
	my $email = shift;
	my $st = $email =~ /^[a-z][a-z0-9_\-]*(\.[a-z][a-z0-9_]+)?@([a-z][a-z0-9_\-]+\.){1,3}(\w{2,4})(\.[a-z]{2})?$/ix ? 1 : 0;
	return $st;
}

sub get_release() 
{
	my ($r) = cat_($release_file) =~ /release\s+(\S+)/;
	($r);
}

$in = $ia && interactive->vnew('su');
$::Wizard_title = N("Mandriva hardware data collector");
%choices = (
	       agree => N("Yes, I authorize."),
	       noagree => N("No, I don't authorize.")
	   );
%account = ( 
	       yes => N("Yes, I already have a Mandriva account."),
	       no => N("No, I want to register.")
           );
@greets = (N("Mr."),N("Mrs."),N("Ms."));
%countries = map {lang::c2name($_) => $_} lang::list_countries();
$country  ||= lang::c2name($locale->{country});
$locale = lang::read('',$>);
$lang = $locale->{lang} || 'en_US';

$release_file = find { -f $_ } '/etc/mandriva-release', '/etc/mandrakelinux-release', '/etc/mandrake-release', '/etc/redhat-release';
$choice = $choices{agree};
$account_ = $account{yes};
$wiz = 
{
	name => N("Mandriva hardware data collector"),
        	pages => {
			welcome => {
			    	name => formatAlaTeX(N("Make your hardware better supported:\n

						We are building a complete and open Hardware Compatibility List (HCL)
						for Linux! By running this wizard, you will add to this HCL the description 
						of your hardware configuration and the status of Mandriva Linux on this configuration.
						It runs once and only takes a few seconds and no personal information about you is collected.")),
			    	no_back => 1,
                   		post => sub {
                       			$::main_window = $::WizardWindow; # center subdialogs on main window
                       			'choices';
                  		            }	
			   	   },
			choices => {
			    	name => N("Do you authorize Mandriva to collect information on your configuration ?"),
			    	data => [ { val => \$choice, type => 'list', list => [ values %choices ] } ],
			    	post => sub { +{ reverse %choices }->{$choice} },
			   	   },
			agree => {
			    	name => N("Do you already have a Mandriva account ?"),
				data => [ { val => \$account_,type => 'list',list => [ values %account]}],
				post => sub { +{reverse %account}->{$account_}},
			   	 },
			yes => {
				name => N("Authentication on Mandriva hcl"),
				data => sub {[{ label => N("Email address:"),val =>\$email},
					      { label => N("Password:"),val =>\$passwd,hidden =>1}
					     ];
				            },
				complete => sub {
						if (check_valid_email($email) == 0)
						{
					   	
                          				$in->ask_warn(N("Error"), N("Not a valid mail address!\n") . "\n\n"  . $email);
					   		return 1;
				        	}

						if(!$passwd || !$email)
						{
							$in->ask_warn(N("Error"),N("Please fill each field"));
							return 1;
						}

						my $wait = $ia && $in->wait_message(N("Please wait"),N("Connecting to Mandriva hcl..."));
						my $err = create_authenticate_account('authenticate',$email,$passwd);
						undef $wait;

						if($err ne "OK")
						{
					   		$in->ask_warn(N("Error"), $err);
							return 1;
				        	}
				   
						$wait = $ia && $in->wait_message(N("Please wait"),N("User $email authentified with success.\nCollecting hardware data..."));
		
						my $pid=open(CMD,"-|");
						my $status;	
						if($pid)
						{
							while(<CMD>)
							{
								$status = $_;
							}
							
							if($status =~ m/exit error/)
							{
								print "Status :$status\n";
								my @status_ = split('--exit',$status);
								$in->ask_warn(N("Error"),N($status_[0]));
								return 1;
							}
						}
						else
						{
							exec "perl /usr/sbin/hclupload $email";
							exit 0;
						}
						undef $wait;
				          },
					  next =>'data_send',
				  },
			no =>  {
				 name =>N("Create a Mandriva account"), 
				 data => sub {[{ label =>N("Greetings:"),val =>\$greeting,list => [@greets],type =>'combo'},
					       { label =>N("First name:"),val =>\$firstname},
					       { label =>N("Last name:"),val =>\$lastname},
					       { label =>N("Email address:"),val =>\$email},
					       { label =>N("Password:"),val =>\$passwd,hidden =>1},
					       { label =>N("Confirm Password:"),val=>\$confirmpasswd,hidden =>1}
					       ];
				        },
				complete => sub {
						$alias = $firstname.$lastname;
						my @info = ($email,$confirmpasswd,$firstname,$lastname,$lang,$greeting,$alias,'home');
						if($passwd ne $confirmpasswd)
						{
							$in->ask_warn(N("Error"), N("The password does not match\n Please try again\n"));
							return 1;
						}
						if (!$email || !$firstname || !$lastname) 
						{
						        $in->ask_warn(N("Error"), N("Please fill in each field"));
						        return 1;
						}
                			  	if (check_valid_email($email) == 0) 
						{
                          				$in->ask_warn(N("Error"), N("Not a valid mail address!\n") . "\n\n"  . $email);
                          				return 1;
                      				}

						my $err =create_authenticate_account('create',@info);
						if ($err ne 'OK') 
						{
		    	                                $in->ask_warn(N("Error"), N("Creating account failed!") . "\n\n" . $err);
							return 1;
						}
					},
					next =>'accountcreated',
				},
				accountcreated => {
							name => formatAlaTeX(N("Mandriva account successfully created.\nPlease click \"Next\" to authenticate and upload your configuration\n")),
							next =>'yes',
						},
			data_send => { 
				no_back => 1,
				name => formatAlaTeX(N("Congratulation data collected succefully.\n\nThank you.")),
				end  => 1
			     	     },
	        	noagree => {
				no_back => 1,
				name => formatAlaTeX(N("Hardware data collection has been canceled.\n")),
				end => 1
		          	   }	
		    }
  };

	!$::testing && get_release <= 2006.0 ? wizards->new->safe_process($wiz,$in): wizards->new($wiz)->safe_process($in);
