#!/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);
BEGIN { $::no_global_argv_parsing = 1 }

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

# i18n: IMPORTANT: to get correct namespace (drakhcl instead of only libDrakX)
BEGIN { unshift @::textdomains, 'drakhcl' }
$ugtk2::wm_icon = '/usr/share/icons/large/mdkonline.png';

my ($email, $ia);
my @line_;
my $in;
my %choices;
my $locale;
my $lang;
my $choice;
my %account;
my $account_;
my $wiz;
my $greeting;
my @greets;
my $firstname;
my $lastname;
my $passwd;
my $confirmpasswd;
my $alias;
my $uri;
my $proxy;
my $soap;
my $release_file;

$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') {
	foreach (cat_('/etc/hcl/hclemail')) {
		@line_ = split('=', $_);
		$line_[1] =~ s/\s+$//;
		$email = $line_[1];
	}
}

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"), join("\n", N("Server Database failed!"), N("Please try again later")) ],
				3  => [ N("Registration error"), N("Some parameters are missing") ],
				5  => [ N("Password error"), N("Wrong password") ],
				7  => [ N("Login error"), join("\n", N("The email you provided is already in use"),
                                                   N("Please enter another one")) ],
				8  => [ N("Login error"), N("The email you provided is invalid or forbidden") ],
				10  => [ N("Login error"), join("\n", N("Email address box is empty"), N("Please provide one")) ],
				12  => [ N("Restriction Error"), N("Database access forbidden") ],
				13  => [ N("Service error"), join("\n", N("Mandriva web services are currently unavailable"),
                                                      N("Please try again later")) ],
				17  => [ N("Password error"), N("Password mismatch") ],
				20  => [ N("Service error"), join("\n", N("Mandriva web services are under maintenance"), 
                                                      N("Please 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} == 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."));
$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(join("\n\n\n", 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"), join("\n\n", N("Not a valid mail address!"), $email));
					   		return 1;
				        	}

						if (!$passwd || !$email) {
							$in->ask_warn(N("Error"), N("Please fill in 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"),
                                                               join("\n", N("User %s authenticated with success.", $email),
                                                                    N("Collecting hardware data...")));
		
						my $pid = open(my $CMD, "-|");
						my $status;	
						if ($pid) {
							foreach (<$CMD>) {
								$status = $_;
							}
							
							if ($status =~ m/exit error/) {
								print "Status :$status\n";
								my @status_ = split('--exit', $status);
								$in->ask_warn(N("Error"), $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"),
                                                 join("\n", N("The password does not match"), N("Please try again later")));
							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"), join("\n\n", N("Not a valid mail address!"), $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(join("\n", N("Mandriva account successfully created."), N("Please click \"Next\" to authenticate and upload your configuration"))),
							next => 'yes',
						},
			data_send => { 
				no_back => 1,
				name => formatAlaTeX(join("\n\n", N("Congratulations. Data collected successfully."), N("Thank you."))),
				end  => 1
			     	     },
	        	noagree => {
				no_back => 1,
				name => formatAlaTeX(N("Hardware data collection has been cancelled.")),
				end => 1
		          	   }	
		    }
  };

	!$::testing && wizards->new($wiz)->safe_process($in);
