#!/usr/bin/perl
#*****************************************************************************
#
# Copyright (c) 2002-2004 Christian Belisle
#                         Thierry Vignaud <tvignaud@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 strict;
use lib qw(/usr/lib/libDrakX);
use common;
use standalone;
use vars qw($MODE %options);
use ugtk2 qw(:helpers :wrappers :ask :create);
use run_program;
use security::level;
use security::msec;
use security::help;
use security::l10n;

#$MODE = 'basic';
#$0 =~ /draksec-firewall$/ and $MODE = 'firewall';
#$0 =~ /draksec-perms$/ and $MODE = 'perms';

#/^-?-(\S+)$/ and $options{$1} = 1 foreach @ARGV;


my ($w, %fields);

############################    I18N     ###################################
my %inv_translations = map { translate($_) => $_ } N_("ALL"), N_("LOCAL"), N_("NONE"), N_("default"), N_("default"), N_("ignore"), N_("no"), N_("yes");
my %translations = reverse %inv_translations;

sub to_i18n { map { $translations{$_} || $_ } @_ }
sub from_i18n { $inv_translations{$_[0]} || $_[0] }
sub resize { gtkset_size_request($_[0], 50, -1) }

%fields = security::l10n::fields();
my %inv_fields = reverse %fields;

# factorize this with rpmdrake and harddrake2
sub wait_msg {
    my $mainw = ugtk2->new(N("Please wait"), (modal => 1, if_(!$::isEmbedded, transient => $w->{rwindow})));
    $mainw->{window}->add(new Gtk2::WrappedLabel($_[0]));
    $mainw->{rwindow}->show_all;
    gtkset_mousecursor_wait($mainw->{rwindow}->window);
    gtkflush();
    $mainw;
}

sub remove_wait_msg { $_[0]->destroy }

sub basic_seclevel_explanations() {
    my $text = Gtk2::TextView->new;
    use Gtk2::Pango;
    my %common_opts = ('left-margin' => '10', 'right-margin' => '10');
    gtktext_insert($text, [ map  {
        if (my ($title, $str) = m!<span foreground="royalblue3">(.*)</span>(.*)!) {
            if_($title, [ $title, { 'foreground' => 'royalblue3', 'weight' => Gtk2::Pango->PANGO_WEIGHT_BOLD, %common_opts } ]),
              if_($str, [ $str . "\n\n", \%common_opts ]);
        } else {
            if_($_, [ "$_\n\n", \%common_opts ]);
    }
      } split("\n",

                             formatAlaTeX(
#-PO: Do not alter the <span ..> and </span> tags
#-PO: Translate the security levels (Poor, Standard, High, Higher and Paranoid) in the same way, you translated these individuals words
					  N("Here, you can setup the security level and administrator of your machine.


The Security Administrator is the one who will receive security alerts if the
'Security Alerts' option is set. It can be a username or an email.


The Security Level menu allows you to select one of the six preconfigured security levels
provided with msec. These levels range from poor security and ease of use, to
paranoid config, suitable for very sensitive server applications:


<span foreground=\"royalblue3\">Poor</span>: This is a totally unsafe but very
easy to use security level. It should only be used for machines not connected to
any network and that are not accessible to everybody.


<span foreground=\"royalblue3\">Standard</span>: This is the standard security
recommended for a computer that will be used to connect to the Internet as a
client.


<span foreground=\"royalblue3\">High</span>: There are already some
restrictions, and more automatic checks are run every night.


<span foreground=\"royalblue3\">Higher</span>: The security is now high enough
to use the system as a server which can accept connections from many clients. If
your machine is only a client on the Internet, you should choose a lower level.


<span foreground=\"royalblue3\">Paranoid</span>: This is similar to the previous
level, but the system is entirely closed and security features are at their
maximum"))) ]);
    create_scrolled_window($text, [ 'never', 'automatic' ]);
}

sub new_nonedit_combo {
    my ($string_list, $o_default_value) = @_;
    my $w = Gtk2::ComboBox->new_text ;
    $w->set_popdown_strings(to_i18n(@$string_list)) unless is_empty_array_ref $string_list;
    $w->entry->set_text(to_i18n($o_default_value)) if $o_default_value;
    $w;
}

sub set_help_tip {
     my ($entry, $default, $opt) = @_;
     my $help = $security::help::help{$opt};
     gtkset_tip(new Gtk2::Tooltips, $entry, formatAlaTeX($help) . "\n" . N("(default value: %s)", to_i18n($default)));
}

my $msec = new security::msec;
$w = ugtk2->new('draksec');
my $window = $w->{window};


############################ MAIN WINDOW ###################################
# Set different options to Gtk2::Window
unless ($::isEmbedded) {
    $w->{rwindow}->set_position('center');
    $w->{rwindow}->set_title("DrakSec");
    $window->set_size_request(598, 520);
}

# Connect the signals
$window->signal_connect('delete_event', sub { $window->destroy });
$window->signal_connect('destroy', sub { ugtk2->exit });

$window->add(my $vbox = gtkshow(new Gtk2::VBox(0, 0)));

# Create the notebook (for bookmarks at the top)
my $notebook = create_notebook();

my $common_opts = { col_spacings => 10, row_spacings => 5, mcc => 1 };

######################## BASIC OPTIONS PAGE ################################
my ($seclevel_entry, $secadmin_entry);

$notebook->append_page(gtkshow(gtkpack_(new Gtk2::VBox(0, 0),
                                       1, basic_seclevel_explanations(),
                                       0, create_packtable($common_opts,
                                                        [ 
                                                          do {
                                                              my @sec_levels = security::level::get_common_list();
                                                              my $current_level = security::level::get_string();
                                                              
                                                              push(@sec_levels, $current_level) unless member($current_level, @sec_levels);
                                                              $seclevel_entry = new_nonedit_combo(\@sec_levels, $current_level);
                                                              
                                                              Gtk2::WrappedLabel->new(N("Security Level:")), $seclevel_entry;
                                                          }
                                                          ],
                                                        [ Gtk2::WrappedLabel->new(N("Security Alerts:")), 
                                                          my $secadmin_check = gtksignal_connect(Gtk2::CheckButton->new, toggled => sub {
                                                                                                     $secadmin_entry->set_sensitive($_[0]->get_active);
                                                                                                 }) ],
                                                        [ Gtk2::WrappedLabel->new(N("Security Administrator:")),
                                                          $secadmin_entry = Gtk2::Entry->new_with_text($msec->get_check_value("MAIL_USER")) ]))),
                               new Gtk2::Label(N("Basic options")));
                       
if ($msec->get_check_value("MAIL_WARN") eq "yes") {
    $secadmin_check->set_active(1);
} else {
    $secadmin_entry->set_sensitive(0);
 }
                       
######################### NETWORK & SYSTEM OPTIONS #########################
my @yesno_choices    = qw(yes no default ignore);
my @alllocal_choices = qw(ALL LOCAL NONE default);
my @all_choices = (@yesno_choices, @alllocal_choices);
my %options_values;
my $help_msg = N("The following options can be set to customize your\nsystem security. If you need an explanation, look at the help tooltip.\n");

foreach ([ 'network', N("Network Options") ], [ 'system', N("System Options") ]) {
    my ($domain, $label) = @$_;
    my %values;
    $notebook->append_page(gtkshow(gtkpack_(Gtk2::VBox->new,
                                            0, Gtk2::Label->new($help_msg),
                                            1, create_scrolled_window(create_packtable($common_opts,
                                                                                       map {
                                                                                           my $i = $_;
                                                                                           
                                                                                           my $entry;
                                                                                           my $opt = $inv_fields{$i} || $i;
                                                                                           my $default = $msec->get_function_default($opt);
                                                                                           if (member($default, @all_choices)) {
                                                                                               $values{$i} = new_nonedit_combo(member($default, @yesno_choices) ? \@yesno_choices : if_(member($default, @alllocal_choices), \@alllocal_choices));
                                                                                               $entry = $values{$i}->entry;
                                                                                           } else {
                                                                                               $values{$i} = new Gtk2::Entry();
                                                                                               $entry = $values{$i};
                                                                                           }
                                                                                           $entry->set_text(to_i18n($msec->get_function_value($opt)));
                                                                                           set_help_tip($entry, $default, $opt);
                                                                                           [ Gtk2::WrappedLabel->new($i), resize($values{$i}) ];
                                                                                       } sort map { $fields{$_} || $_ } $msec->list_functions($domain),
                                                                                      ),
                                                                      [ 'never', 'automatic' ],
                                                                     ),
                                           )
                                  ),
                           Gtk2::WrappedLabel->new($label));
    $options_values{$domain} = \%values;
}

######################## PERIODIC CHECKS ###################################
my %security_checks_value;

$notebook->append_page(gtkshow(gtkpack_(Gtk2::VBox->new,
                                        0, Gtk2::Label->new($help_msg),
                                        1, create_scrolled_window(create_packtable($common_opts,
                                                                                   map {
                                                                                       my $i = $_;
                                                                                       my $opt = $inv_fields{$i} || $i;
                                                                                       $security_checks_value{$i} = new_nonedit_combo([ 'yes', 'no', 'default' ], $msec->get_check_value($opt));
                                                                                       my $entry = $security_checks_value{$i}->entry;
                                                                                       set_help_tip($entry, $msec->get_check_default($opt), $opt);
                                                                                       [ gtkshow(Gtk2::WrappedLabel->new($i)), resize($security_checks_value{$i}) ];
                                                                                   } sort map { $fields{$_} || $_ } $msec->list_checks)))),
                       new Gtk2::Label(N("Periodic Checks")));


####################### OK CANCEL BUTTONS ##################################
gtkpack_($vbox,
         1, gtkshow($notebook),
         0, create_okcancel(my $oc =
                            {
                             cancel_clicked => sub { ugtk2->exit(0) },
                             ok_clicked => sub {
                                my $seclevel_value = $seclevel_entry->entry->get_text;
                                my $secadmin_check_value = $secadmin_check->get_active;
                                my $secadmin_value = $secadmin_entry->get_text;
                                my $w;

                                log::explanations("Configuring msec");

                                if ($seclevel_value ne security::level::get_string()) {
                                    $w = wait_msg(N("Please wait, setting security level..."));
                                    log::explanations(qq(Setting security level to "$seclevel_value"));
                                    security::level::set(security::level::from_string($seclevel_value));
                                    remove_wait_msg($w);
                                }

                                $w = wait_msg(N("Please wait, setting security options..."));
                                log::explanations(qq(Setting security administrator option to ") . bool2yesno($secadmin_check_value) . '"');
                                $msec->set_check('MAIL_WARN', bool2yesno($secadmin_check_value));

                                if ($secadmin_value ne $msec->get_check_value('MAIL_USER') && $secadmin_check_value) {
                                    log::explanations(qq(Setting security administrator contact to "$secadmin_value"));
                                    $msec->set_check('MAIL_USER', $secadmin_value);
                                  }

                                log::explanations("Setting security periodic checks");
                                foreach my $key (keys %security_checks_value) {
                                    $msec->set_check($inv_fields{$key} || $key, from_i18n($security_checks_value{$key}->entry->get_text));
                                }
                                $msec->apply_checks;

                                foreach my $domain (keys %options_values) {
                                    log::explanations("Setting msec functions related to $domain");
                                    foreach my $key (keys %{$options_values{$domain}}) {
                                        my $opt = $options_values{$domain}{$key};
                                        $msec->set_function($inv_fields{$key} || $key, from_i18n($opt->get_text));
                                    }
                                }
                                $msec->apply_functions;
                                log::explanations("Applying msec changes");
                                run_program::rooted($::prefix, "/usr/sbin/msec");

                                remove_wait_msg($w);

                                ugtk2->exit(0);
                            }
                            },
                            undef, undef, '',
                            [ N("Help"), sub { unless (fork()) { exec("drakhelp --id draksec") } } ],
                           ),
        );
$oc->{cancel}->can_default(1);
$oc->{cancel}->grab_default;

$w->main;
ugtk2->exit(0);