#!/usr/bin/perl

# Drak Bug Report 
# Copyright (C) 2002-2004 Mandrakesoft (daouda at mandrakesoft dot com)
#                                       Stew Benedict (sbenedict at mandrakesoft dot com) 
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# 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 strict;
use diagnostics;
use lib qw(/usr/lib/libDrakX);

use standalone;
use common;
use ugtk2 qw(:all);
use Config;

my ($bugzilla, $wizard_name);
my $prog;
my ($incident, $stable_release) = (0, 0);
my ($bugdesc, $bugwrite, $table, $comb_app, $button_pkg, $package, $extra_data, $summary, $textview, $kversion, $cpuinfo, $lspci);

foreach (@ARGV) {
    next unless defined $_;
    /^--report$/ and $prog = shift @ARGV;
    /^--incident$/ and do { $incident = 1; $prog = shift @ARGV };
}

my $window = ugtk2->new(N("Mandrakelinux Bug Report Tool"), center => 1);
$window->{rwindow}->set_border_width(5);
$window->{window}->signal_connect("delete_event", sub { ugtk2->exit(0) });

my $mdk_app = { 
	       N("Mandrakelinux Control Center") => 'drakconf',
	       N("First Time Wizard") => 'drakfw',
	       N("Synchronization tool") => 'draksync',  
	       N("Standalone Tools") => ['adduserdrake', 'diskdrake', 'drakautoinst', 'drakbackup', 'drakboot', 'DrakBug', 'DrakClock', 'DrakConnect', 'drakfloppy', 'drakfirewall', 'drakfont', 'drakgw', 'DrakSec', 'draksplash', 'drakvpn', 'drakxservices', 'drakxtools', 'drakxtv', 'keyboardrake', 'logdrake', 'mousedrake', 'net_monitor', 'printerdrake', 'scannerdrake', 'XFdrake'],
	       N("HardDrake") => 'harddrake2',
	       N("Mandrakeonline") => 'mdkonline',
	       N("Menudrake") => 'menudrake',
	       N("Msec") => 'msec',
	       N("Remote Control") => 'rfbdrake',
	       N("Software Manager") => 'rpmdrake',
	       N("Urpmi") => 'urpmi',
	       N("Windows Migration tool") => 'transfugdrake',
	       N("Userdrake") => 'userdrake',
	       N("Configuration Wizards") => 'wizdrake',
	      };

my @generic_tool = keys %$mdk_app; 
my @all_drakxtools = @{ $mdk_app->{N("Standalone Tools")} };
push(@generic_tool,@all_drakxtools);

my $kernel_release = chomp_(`uname -r`);
my $mandrake_release = chomp_(cat_('/etc/mandrakelinux-release'));
#- unused for now
#- (my $mandrake_version) = $mandrake_release =~ /(\d+\.\d+)/;

if ($mandrake_release =~ /(official|community)/i) {
    my $anthill = 'http://bugs.mandrakelinux.com';
    $bugzilla = $anthill . '/drakbug.php?request=1';
    $stable_release = 1;
    $wizard_name = "Anthill";
} else {
    $bugzilla = 'http://qa.mandrakesoft.com/enter_bug.cgi';
    $wizard_name = "Bugzilla wizard";
}

if ($stable_release == 0) {
    $table = create_packtable({ col_spacings => 5, row_spacings => 10 },
			      [ Gtk2::Label->new(N("Application:")), $comb_app = Gtk2::ComboBox->new_text ],
			      [ Gtk2::Label->new(N("Package: ")), $package = Gtk2::Entry->new_with_text("...") ], # complain on gtk-perl@ml
			      [ Gtk2::Label->new(N("Kernel:")), gtkset_editable(Gtk2::Entry->new_with_text($kernel_release), 0) ],
			      [ Gtk2::Label->new(N("Release: ")), gtkset_editable(Gtk2::Entry->new_with_text($mandrake_release), 0) ]
                             );
    $comb_app->set_popdown_strings("", sort(@generic_tool));
} else {
    $table = create_packtable({ col_spacings => 5, row_spacings => 5 },
			      [Gtk2::Label->new(N("Application Name\nor Full Path:")), 
			       gtkpack_(Gtk2::HBox->new(0,5),
					1, $comb_app = gtkset_editable(Gtk2::Entry->new, 1), 
					0, $button_pkg = Gtk2::Button->new(N("Find Package")),
				       )],
			      [ Gtk2::Label->new(N("Package: ")), $package = gtkset_editable(Gtk2::Entry->new_with_text("..."), 0) ],
			      [ Gtk2::Label->new(N("Release: ")), gtkset_editable(Gtk2::Entry->new_with_text($mandrake_release), 0) ],
			      [ Gtk2::Label->new(N("Summary: ")), $summary = gtkset_editable(Gtk2::Entry->new_with_text(""), 1) ]
			     );
    
    $textview = Gtk2::TextView->new;
    
    $extra_data = gtkpack_(Gtk2::VBox->new(0,1),
			   0, Gtk2::Label->new(N("Bug Description/System Information")),
			   1, create_scrolled_window(gtktext_insert($textview,  N("YOUR TEXT HERE"), editable => 1, visible => 1)),
			   0, gtkpack_(Gtk2::HBox->new(0,20),
				       0, Gtk2::HBox->new(0,0),
				       1, $kversion = Gtk2::CheckButton->new(N("Submit kernel version")),
				       1, $cpuinfo = Gtk2::CheckButton->new(N("Submit cpuinfo")),
				       1, $lspci = Gtk2::CheckButton->new(N("Submit lspci")),
				      ),
			   0, Gtk2::HSeparator->new,		
			  );
    $kversion->set_active(1);
    $cpuinfo->set_active(1);
    $lspci->set_active(1);
}

gtkadd($window->{window},
       gtkpack_(Gtk2::VBox->new(0,5),
		0, gtkadd($table),
		1, gtkadd($extra_data),
		0, gtkpack(Gtk2::HBox->new(0,0),
			   gtkpack(gtkset_justify(Gtk2::WrappedLabel->new(formatAlaTeX(N("To submit a bug report, click on the report button.\nThis will open  a web browser window on %s\n where you'll find a form to fill in.  The information displayed above will be \ntransferred to that server.", $wizard_name))), "left")),
			  ),
		0, gtkpack(Gtk2::HSeparator->new),
		0, gtkpack_(Gtk2::HBox->new(0,0),
			    0, gtksignal_connect(Gtk2::Button->new(N("Help")), clicked => sub { system("drakhelp --id drakbug &") }),
			    1, Gtk2::Label->new(""),
			    0, gtksignal_connect(Gtk2::Button->new(N("Report")), clicked => sub {
						     if ($stable_release == 0) { 
							 my $options = "mdkbugreport=1";
							 $options .= "&incident=1" if $incident;
							 my $p = $package->get_text;
							 my ($product, $version) = $p =~ /^(.*)-([^-]+-[^-]+mdk)$/;
							 my $app = $comb_app->entry->get_text;
							 my $component = if_(member($app, @all_drakxtools), $app) || $mdk_app->{$app};
							 $options .= "&product=$product" if $product;
							 $options .= "&component=$component" if $component;
							 $options .= "&version=$version" if $version;
							 $options .= "&kernel=$kernel_release";
							 print($bugzilla . "?" . $options . "\n");
							 connect_bugzilla($bugzilla . "?" . $options);
						      } else {
							  # anthill variant - we'll create a text file, then connect to upload
							  my $check = write_anthill_file(); 
							  connect_bugzilla($bugzilla) if !$check;
						      }
						 }
						),
			    0, gtksignal_connect(Gtk2::Button->new(N("Close")), clicked => sub { ugtk2->exit(0) }),
			   )));

if ($stable_release == 0) {
    if (defined $prog) {
    	update_app($prog); 
    	$comb_app->entry->set_text($prog);
    };
    $comb_app->entry->signal_connect('changed', sub { update_app($comb_app->entry->get_text) });
} else {
    $window->{window}->set_size_request(600, 460);
    $button_pkg->signal_connect('clicked', sub { 
				    my $pkg_name = get_pkg_name($comb_app->get_text);
				    $package->set_text($pkg_name);
				});
}

$window->{window}->show_all;
$window->main;
ugtk2->exit(0);

sub update_app {
    my ($text) = @_;
    my $app_choice;
    $ENV{PATH} = "/sbin:/usr/sbin:$ENV{PATH}";
    if (member($text,@all_drakxtools) || $text eq N("Standalone Tools")) {
	$app_choice = chomp_(`rpm -q drakxtools`);
    } elsif (exists($mdk_app->{$text}) && $text ne N("Standalone Tools")) {	
	$app_choice = get_package($mdk_app->{$text});
    } else {
      LOOP: while (my ($key, $value) = each %$mdk_app) {
	    next if $key eq N("Standalone Tools");
	    if ($value eq $text) { 
		$app_choice = get_package($text);
		$prog = $key; 
		last LOOP;
	    }
	}
	
    }
    $app_choice ? $package->set_text($app_choice) : $package->set_text(N("Not installed"));
}

my %packages;

sub get_package {
    my ($executable) = @_;
    my ($rpm_package, $which_app);
    $rpm_package = $packages{$executable};
    if (!defined $rpm_package) {
        $which_app = chomp_(`which '$executable' 2> /dev/null`);
        # deush, rpm can takes some time aka it'll sleeps if something has opened rpm db !
        $rpm_package = $which_app eq "" ? N("Package not installed") : chomp_(`rpm -qf '$which_app' 2>&1`);
        $packages{$executable} = $rpm_package;
    }
    $rpm_package;
}

sub get_pkg_name {
    my ($executable) = @_;
    my $which_app = chomp_(`which '$executable' 2> /dev/null`);
    my $rpm_package;
    if ($which_app eq "") {
	$rpm_package = chomp_(`rpm -q '$executable' --qf '%{NAME}' 2>&1`);
    } else {
	$rpm_package = chomp_(`rpm -qf '$which_app' --qf '%{NAME}' 2>&1`);
    }
    $rpm_package = chomp_(`rpm -qf '$executable' --qf '%{NAME}' 2>&1`) if $rpm_package =~ /not installed$/;
    $rpm_package = (split(/-2/, $rpm_package))[0] if $rpm_package =~ /^kernel/;
    $rpm_package ||= N("NOT FOUND");
    $rpm_package;
}

sub connect_bugzilla {
    my ($url) = @_;
    if (!$stable_release) {
	my $_w = create_dialog(N("Please wait"), N("connecting to %s...", $wizard_name)); 
	sleep(3);
    }
    exec $ENV{BROWSER},$url if exists $ENV{BROWSER};
    my @browser = qw(mozilla konqueror galeon);
    foreach (@browser) {
	if (-e "/usr/bin/$_") { log::explanations("Contacting $url with $_\n "); exec $_,$url } 
    }
    create_dialog(N("Error"), N("No browser available! Please install one"));
}

sub write_anthill_file() {
    my $buffer = $textview->get_buffer;
    my $siter = $buffer->get_start_iter;
    my $eiter = $buffer->get_end_iter; 
    $bugdesc = $buffer->get_text($siter, $eiter, 0);
    
    #- create anthill upload file in specified format
    my $file;
    open($file, "> /tmp/drakbug.report") or return 1;
    print $file "--- BEGIN DRAKBUG REPORT ---\n";
    print $file "%product: $mandrake_release\n";
    my $version = arch();
    $version = "x86" if $version =~ /^i.86/;
    print $file "%version: $version\n";
    my $pkg_name = $package->get_text;
    if ($pkg_name eq "..." || $pkg_name eq "") {
	my $_w = create_dialog(N("Error"), N("Please enter a package name."));
	return 1;
    }
    print $file "%component: $pkg_name\n";
    my $summary_text = $summary->get_text;
    if ($summary_text eq "") {
	my $_w = create_dialog(N("Error"), N("Please enter summary text."));
	return 1;
    }
    
    print $file "%summary: $summary_text\n";
    print $file "%description:\n";
    
    #- gave me fits wanted to wrap what was wrapped in the GUI
    #- plus include user's \n
    my @buglist = split("\n", $bugdesc);
    foreach my $bugdesc (@buglist) {
	if (length($bugdesc) > 77) {
	    $bugwrite = $bugdesc;
	    select($file);
	    local $~ = "PFORMAT";
	    write $file;
	    select(STDOUT);
	    $bugwrite = '';
	} else {
	    print $file "   $bugdesc\n";
	}
    }
    
    print $file "-" x 80 . "\n";
    print $file "Kernel: $kernel_release\n" . "Uname: " . `uname -a` . "\n" if $kversion->get_active;
    print $file "Cpuinfo: \n" . cat_("/proc/cpuinfo") if $cpuinfo->get_active;
    print $file "Lspci Output:\n" . `lspci` if $lspci->get_active;
    print $file "--- END DRAKBUG REPORT ---\n";
    close $file or return 1;
    return 0
}

format PFORMAT =
~~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$bugwrite
.