#!/usr/bin/perl
################################################################################
# Mdkupdate                                                                    # 
#                                                                              #
# Copyright (C) 2002 MandrakeSoft                                              #
#
# Daouda Lo <daouda@mandrakesoft.com>                                          #
#                                                                              #
# This program is free software; you can redistribute it and/or modify         #
# it under the terms of the GNU General Public License Version 2 as            #
# published by the Free Software Foundation.                                   #
#                                                                              #
# 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.   #
################################################################################

use POSIX;
use Digest::MD5  qw(md5 md5_hex md5_base64);
use HTTP::Request;
use HTTP::Request::Common;
use LWP::UserAgent;
use MDK::Common;
use lib qw(/usr/lib/libDrakX);
use Locale::GetText;

#- I18N.
setlocale (LC_ALL, "");
Locale::GetText::textdomain ("mdkupdate");

sub _ {
    my ($format, @params) = @_;
    sprintf(Locale::GetText::I_($format), @params);
}

$logfile = "/var/log/mdkupdate.log";
my $url_upload_diff = "https://www.mandrakeonline.net/online_dif.php";
my $url_get_rpms = "https://www.mandrakeonline.net/online_update.php";
my $rpms_rep = "/root/tmp/";
my $VERSION = "0.16";
my $security = 0;

sub usage {
    print STDERR _("mdkupdate version %s
Copyright (C) 2002 MandrakeSoft.
This is free software and may be redistributed under the terms of the GNU GPL.

usage:
") . _("  --help         - print this help message.
") . _("  --security     - use only security media.
") . _("  -v             - verbose mode.
", $VERSION );
    exit(0);
}

my %o = getVarsFromSh("/root/.mdkupdate");
rpm_qa("/root/rpm_qa_installed_before");
update_rpms($o{LOGIN},$o{PASS},$o{BOX},$o{CURRENTKEY});
rpm_qa("/root/rpm_qa_installed_after");
my %new = getVarsFromSh("/root/.mdkupdate");
send_rpm_dif($new{LOGIN},$new{PASS},$new{BOX},$new{OLDKEY});
clean_dir();

sub update_rpms () {
    my ($login,$password,$box_name,$curkey) =@_;
    my $result = -1;
    my $string;
    
    if ($login && $password && $login !~ /\s+/ && $password !~ /\s+/) {
	my $ua = LWP::UserAgent->new;
	$ua->agent("MdkUpdateAgent/0.15" . $ua->agent);
	my $request = HTTP::Request->new(GET => $url_get_rpms.'?log='.$login.'&pass='.$password.'&host='.$box_name.'&key='.$curkey);
	my $response = $ua->request($request);
	$string = $response->content;
	if ($response->is_success) {
	    $result = ($response->content =~ /^TRUE/) ? 0 : -1;
	} else {
	    log_it(_("Connection problem")."\n"._("MandrakeUpdate could not contact the site, we will try again"));
	    clean_dir();
	    exit -1;
	}
    } else {
	$result = -1; 
    }
    # if correct, return 0
    if (! $result) {
	@str_m = split '\n', $string;
	my %l = getVarsFromSh "/root/.mdkupdate";
	if ($str_m[0] eq 'TRUE') {
	    setVarsInSh("/root/.mdkupdate", {
		OLDKEY => $str_m[2],
		CURRENTKEY => $str_m[1],
		MIRROR => $l{MIRROR},
		VER => $l{VER},
		BOX => $l{BOX},
		PASS => $l{PASS},
		LOGIN => $l{LOGIN} ,
	    });
	    my @junk= splice(@str_m,0,3);
	    my $mir_full = "ftp://" . $l{MIRROR} . "/" . $l{VER} ."/" . "RPMS"."/";
	    update_packages($mir_full,@str_m);
	} else { log_it("problem occur $str_m\n");}
	    	    
    } else {
	log_it(_("Your login or password may be wrong")."\n"._("You'll need to have an account on MandrakeOnline, or update your subscription")."\n"._("For any problem send mail to support\@mandrakeonline.net\n"));
	clean_dir();
	exit -1;
    }
}

sub update_packages {
    my ($mir,@str) = @_;
    chdir($rpms_rep) or log_it("\ncannot chdir to $rpms_rep\n");
    $full_rpm = join(' ',@str);
    print "@str\n";
    foreach (@str) {
	-x "/usr/bin/wget" or die _("wget is missing\n");
	`/usr/bin/wget -nc $mir$_`;
    }
    `urpmi $full_rpm`;
    foreach $pack (@str) {
	system("rm -f $pack");
    }	
}

sub send_rpm_dif {
    my ($login,$password,$box_name,$oldkey) =@_;
    `sdiff -s /root/rpm_qa_installed_after /root/rpm_qa_installed_before >/root/$login.$password.$box_name.$oldkey.dif`;
    my $ua = LWP::UserAgent->new;
    $ua->agent("MdkOnlineAgent/0.15" . $ua->agent);
    my $response = $ua->request(POST "https://www.mandrakeonline.net/online_dif.php",

				Content_Type => 'form-data',
				Content => [submit => "upload_dif",
					    dif_file => ["/root/$login.$password.$box_name.$oldkey.dif"]
					    ]);
    # Check the outcome of the response
    print "REPONSE: ".$response->content."\n";
}

sub clean_dir() {
    system("rm -f /root/*.dif /root/rpm_qa_installed_before /root/rpm_qa_installed_after");    
    exit 1;
}

sub rpm_qa {
    my ($file) = @_;
    open (FILE,"> $file") || die "Couldn't open $file : $!"; 
    join '', map { chomp; print FILE "$_" }
    join('',sort `rpm -qa`); 
}

sub log_it {
    local *LOG;
    open LOG, ">> $logfile" or die "can't output to log file\n";
    print LOG @_;
}

sub fatal {
    my ($comment)=@_;
    printf STDERR "%s\n", $comment; exit($_[0]);
}