#!/usr/bin/perl

# Drak Bug Report 
# Copyright (C) 2002-2008 Mandriva (daouda at mandriva dot com)
#                          Stew Benedict (sbenedict at mandriva 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 lib qw(/usr/lib/libDrakX);
use any;
use standalone;
use MDK::Common;
use common;
BEGIN { $::no_ugtk_init = 1 }
use mygtk3 qw(gtknew);
use ugtk3 qw(:all);
use Config;
use URI::Escape;
use run_program;

my $prog;
my $incident = 0;
my ($table, $comb_app, $com_app, $button_pkg, $button_browse, $package, $distrocode, $error, $user_descr);

my $i;
foreach (@ARGV) {
    next unless defined $_;
    $i++;
    /^--error$/ and do { $error = splice(@ARGV, $i, 1) };
    /^--report$/ and $prog = splice(@ARGV, $i, 1);
    /^--incident$/ and do { $incident = 1; $prog = splice(@ARGV, $i, 1) };
}

my $segfaulted = $error =~ /SEGV/;
if (!check_for_xserver()) {
    print("Cannot be run in console mode.\n");
    print join("\n", 
               N("The \"%s\" program has crashed with the following error:", $prog),
               $error,
               '')
      if $error;
    c::_exit(0);
}

mygtk3::init();

$ugtk3::wm_icon = 'drakbug-16';
my $window = ugtk3->new(N("%s Bug Report ", N("PCLinuxOS")), center => 1);
$window->{rwindow}->set_border_width(5);
$window->{window}->signal_connect("delete_event", sub { ugtk3->exit(0) });

my $mdk_app = { 
	       N("%s Control Center", N("PCLinuxOS")) => 'drakconf',
	       N("First Time Wizard") => 'drakfw',
	       N("Synchronization tool") => 'draksync',  
	       N("Standalone Tools") => 'drakxtools',
	       "harddrake" => 'harddrake2',
	       N("Remote Control") => 'rfbdrake',
	       N("Software Manager") => 'rpmdrake',
	       N("Windows Migration tool") => 'transfugdrake',
	       N("Configuration Wizards") => 'wizdrake',
	      };

my @generic_tool = keys %$mdk_app; 
my @all_drakxtools = qw(adduserdrake diskdrake drakautoinst drakboot drakbug drakclock drakfloppy drakfont draksec drakxservices drakxtools drakxtv logdrake scannerdrake);
push @generic_tool, @all_drakxtools, qw(drakbackup drakconnect drakfirewall drakhosts drakmenustyle draknfs draksambashare drakgw drakroam drakvpn keyboarddrake msec mousedrake net_monitor urpmi userdrake XFdrake);

my $kernel_release = chomp_(`uname -r`);
my $pclinuxos_release = chomp_(cat_('/etc/release'));

my $distrocode = $pclinuxos_release;
my $bugzilla_url = 'http://pclinuxos.com';
my $wizard_name = "Harry Potter";

$table = create_packtable({ col_spacings => 5, row_spacings => 10 },
		          [ gtknew('Label_Left', text => N("Select %s Tool:", N("PCLinuxOS"))), $comb_app = Gtk3::ComboBoxText->new, $comb_app->set_wrap_width(3) ],
                          [ gtknew('Label_Left', text => N("or Application Name\n(or Full Path):")), 
			  gtkpack_(Gtk3::HBox->new(0, 5),
				   1, $com_app = gtkset_editable(Gtk3::Entry->new, 1), 
				   0, $button_pkg = Gtk3::Button->new(N("Find Package")),
				   0, $button_browse = Gtk3::FileChooserButton->new(N("Browse"), 'GTK_FILE_CHOOSER_ACTION_OPEN'),
				  ) ],
			  [ gtknew('Label_Left', text => N("Package: ")), $package = Gtk3::Entry->new_with_text("...") ], # complain on gtk-perl@ml
			  [ gtknew('Label_Left', text => N("Kernel:")), gtkset_editable(Gtk3::Entry->new_with_text($kernel_release), 0) ]
                         );
$comb_app->set_popdown_strings("", uniq(sort(@generic_tool), if_($prog, $prog)));
$comb_app->set_text("");
my $theme_name = $table->get_settings->get('gtk-theme-name');

sub is_a_boot_issue() {
    $prog =~ /boot|mkinitrd/;
}

sub format_trace_with_message {
    my ($message, $trace) = @_;
    ([ $message ], [ "\n\n  " . join("\n  ", split("\n", $trace)) . "\n\n", { family => 'monospace' } ]);
}

my @commands = 'lspcidrake -v';

push @commands, 'blkid' if is_a_boot_issue();

my $parent_uid = get_parent_uid();

my $width = 600;
gtkadd($window->{window},
       gtkpack_(Gtk3::VBox->new(0, 5),
                0, gtknew('Title1', label => $pclinuxos_release, width => $width),
                1, create_scrolled_window(
                    gtknew('TextView', editable => 0, height => 150,
                           text => [
                               if_($prog,
                                   if_($error,
                                       format_trace_with_message(
                                           ($segfaulted ?
                                              N("The \"%s\" program has segfaulted with the following error:", $prog)
                                                : N("The \"%s\" program has crashed with the following error:", $prog)),
                                           $error)
                                   ),
                               ),
                               [ N("Used theme: %s", $theme_name) . "\n\n" ],
                               [
                                   N("Please report this to the PCLinuxOS forum.\n")
                               ]
                           ])),
		0, gtkpack(Gtk3::HSeparator->new),
		0, gtkpack(create_hbox('edge'),
                           gtkpack(create_hbox('end'),
                                   gtksignal_connect(Gtk3::Button->new(N("Close")), clicked => sub { ugtk3->exit(0) }),
                               ))));

if (defined $prog) {
    update_app($prog); 
    $comb_app->set_text($prog);
}
$comb_app->entry->signal_connect('changed', sub {
    my $text = $comb_app->entry->get_text;
    $text and update_app($text);
 });

$button_pkg->signal_connect('clicked', sub { 
				    $comb_app->set_text("");
				    my $pkg_name = get_package($com_app->get_text);
				    $package->set_text($pkg_name);
				});

$button_browse->signal_connect('file-set', sub { $com_app->set_text($button_browse->get_filename) });

$window->{window}->show_all;
$window->main;
ugtk3->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})) {
	$app_choice = get_package($mdk_app->{$text});
    } else {
        $app_choice = get_package($text);
    }
    $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) {
        local $ENV{PATH} = "$ENV{PATH}:/sbin:/usr/sbin";
        $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") : common::to_utf8(chomp_(`rpm -qf '$which_app' 2>&1`));
        $packages{$executable} = $rpm_package;
    }
    $rpm_package;
}

sub get_top_of_trace {
    my ($error) = @_;
    return if !$error;
    sprintf(" (%s)", first(split(/\n/, $error)));
}

