#!/usr/bin/perl
# Mandriva Remote FrameBuffer 
#
# Copyright (C) 2003, 2004 Mandriva Daouda Lo (daouda 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 strict;

use lib qw(/usr/lib/libDrakX/);
use standalone;
use common;
BEGIN { unshift @::textdomains, 'drakfax' }
use ugtk2 qw(:all);


my $spool = '/var/spool/fax';
my $faxsysconfdir = $spool . '/etc/';
my $setupcachefile = $spool . '/etc/setup.cache';
my $setupmodemfile = $spool . '/etc/setup.modem';
my $exec_probe = '/usr/sbin/drakfax_probemodem';
my $pixdir = '/usr/share/drakfax/pixmaps/';
my $nosetup = 0;

require_root_capability();


if (!-e $setupcachefile || !-e $setupmodemfile) {
    $nosetup =1;
}

my $df = {};

my ($device, $modemtype, $flowcontrol, $countrycode, $areacode, $faxnumber, $dialrules);
$df->{wnd} = ugtk2->new(N("Server Configuration") . " " );
gtkset_size_request($df->{wnd}{rwindow}, 580, 450);
$df->{wnd}{window}->set_position('center') if !$::isEmbedded;
$df->{wnd}{window}->signal_connect(delete_event => \&quitGlobal);

$df->{nb} = Gtk2::Notebook->new;
my $hbox_buttons = gtkpack_(Gtk2::HBox->new(0, 5),
			    0, gtkpack__(create_hbox('start'),
					 gtksignal_connect(Gtk2::Button->new(N("Quit")), clicked => sub { Gtk2->main_quit })
					),
			    1, Gtk2::Label->new(""),
			    0, gtkpack__(create_hbox('start'),
					 gtksignal_connect(Gtk2::Button->new(N("Launch Client")), clicked => sub { system("drakfax &") }),
					 gtksignal_connect(Gtk2::Button->new(N("Apply")), clicked => sub { applySettings() }),
					),
			   );
$df->{wnd}{window}->add(gtkpack_(Gtk2::VBox->new(0, 0),
				 if_(!$::isEmbedded, 0, Gtk2::Banner->new($pixdir . "icon-title.png", N("Fax Server Setup"))),
				 1, $df->{nb},
				 0, Gtk2::HSeparator->new,
				 0, $hbox_buttons
				));

gtkappend_page($df->{nb},
	       gtkpack_(Gtk2::VBox->new(0, 4),
			1, create_packtable({ homogeneous => 1, col_spacings => 5, row_spacings => 10 },
			    [ "", "", "", "" ],
			    # BUG (to fix once mdk10.1 is out): appending ":" is wrong for RTL languages:
			    [ N("Device") . " :", $device = getList('dev'), N("Modem type") . " :", $modemtype = getList('mt') ],
			    [ N("Flow control") . " :", $flowcontrol = getList('fc') ]
			)
		       ), N("Hardware"));

gtkappend_page($df->{nb},
	       gtkpack_(Gtk2::VBox->new(0, 4),
			1, create_packtable({ homogeneous => 0, col_spacings => 5, row_spacings => 10 },
					    [ " ", " ", " ", " " ],
					    [ N("Country code") . " :", $countrycode = Gtk2::Entry->new, N("Area code") . " :", $areacode = Gtk2::Entry->new ],
					    [ N("Fax Number") . " :", $faxnumber = Gtk2::Entry->new, N("Dial rules") . " :", $dialrules = getList('dr') ]
					   )
		       ), N("Options"));

if (-d $faxsysconfdir) { $df->{wnd}{rwindow}->show_all; } else { installPkg('hylafax-server') };

#Gtk2->main;
$df->{wnd}->main;
ugtk2->exit(0);

sub installPkg {
    my $pkg = shift;
    my $w = ugtk2->new(N("Install client package"), grab => 1);
    $w->{rwindow}->set_position('center_always');
    gtkadd($w->{window}, 
	   gtkpack_(my $vbox = Gtk2::VBox->new(0, 2),
		    1, Gtk2::Label->new(N("You need to install hylafax-server")),
		    0, Gtk2::HSeparator->new,
		    0, gtkpack(Gtk2::HBox->new(1, 20),
			       map {
				   my $r = $_->[1];
				   gtksignal_connect(Gtk2::Button->new_from_stock($_->[0]), clicked => sub {
							 if (!$r) {
							     system("drakhelp_inst $pkg");
							     $df->{wnd}{rwindow}->show_all
							 } else { Gtk2->main_quit }
							 $w->destroy; })
			       } ([ N("Cancel"), 1 ], [ N("Ok"), 0 ]))
		   )
	  );
    $w->main
}
sub applySettings {
    if ($nosetup) {
	cp_af("$spool/config/defaults/setup.cache", "$setupcachefile");
	cp_af("$spool/config/defaults/setup.modem", "$setupmodemfile");
    }
    my $dev = $device->entry->get_text();
    my $class = $modemtype->entry->get_text();
    $dev =~ s/\/dev\///;
    my $fifo = "$spool/FIFO.$dev";
    if ($dev && !-p $fifo) {
	log::l(N("Creating FIFO file"));
	system("/usr/bin/mkfifo","$fifo");
	system("chown","uucp.uucp","$fifo");
	chmod(0600, "$fifo");
    }
    if ($class && $dev) {
	my $c = lc($class);
	print "$c ** $spool/config/$c ** $spool/config/config.$dev \n";
	!-e "$spool/config/$c" and cp_af("$spool/config/$c", "$spool/etc/config.$dev");
    }
    stopService();
    startService($dev);
}
sub stopService {
    system("faxquit");
    system("service hylafax-server stop");
    system("/usr/bin/killall -QUIT faxgetty");
}
sub startService {
    my $device = shift;
    system("service hylafax-server start");
    system("faxgetty -D /dev/$device");
}
sub getList {
    my $type = shift;
    my $combo = $type eq 'dev' ? Gtk2::Combo->new : Gtk2::OptionMenu->new;
    my @dialrules = getDialrulesfiles($faxsysconfdir);
    my $fillAction = {
		      dev => [ map { '/dev/' . $_ } qw(ttyS0 ttyS1 cua0 cua1) ],
		      mt => [ map { 'Class'. $_ } qw(1 2 1.0) ],
		      fc => [ qw(xonxoff rtscts) ],
		      dr => [ @dialrules ]
		     };
    $combo->set_popdown_strings(@{$fillAction->{$type}});
    $combo
}
sub quitGlobal {
    Gtk2->main_quit;
}
sub getDialrulesfiles() {
    my $fullpath = shift;
    my @dr = grep { /dialrules/ } all($fullpath);
    @dr
}
sub probeModems {
    my $dev = shift;
    my $probe = `$exec_probe $dev`;
    $probe
}


