#!/usr/bin/perl

#
# Guillaume Cottenceau (gc@mandrakesoft.com)
#
# Copyright 2000, 2001, 2002 MandrakeSoft
#
# 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 lib qw(/usr/lib/libDrakX);

use standalone;     #- warning, standalone must be loaded very first, for 'explanations'

use common;
use detect_devices;
use interactive;
use log;
use c;
use network::netconnect;

$::isInstall and die "Not supported during install.\n";


$::isEmbedded = ($::XID, $::CCPID) = "@ARGV" =~ /--embedded (\w+) (\w+)/;

local $_ = join '', @ARGV;

/-h/ and die "usage: drakgw [--version]\n";
/-version/ and die 'version: $Id$ '."\n";
$::Wizard_pix_up = "wiz_drakgw.png";
$::Wizard_title = _("Internet Connection Sharing");
$::direct = /-direct/;


my $sysconf_network = "/etc/sysconfig/network";
my $sysconf_dhcpd = "/etc/sysconfig/dhcpd";
my $rc_firewall_generic = "/etc/rc.d/rc.firewall";
my $rc_firewall_drakgw = "/etc/rc.d/rc.firewall.inet_sharing";
my $rc_firewall_22 = "/etc/rc.d/rc.firewall.inet_sharing-2.2";
my $rc_firewall_24 = "/etc/rc.d/rc.firewall.inet_sharing-2.4";
my $dhcpd_conf = "/etc/dhcpd.conf";
my $cups_conf = "/etc/cups/cupsd.conf";
my $drakgw_setup = "/etc/sysconfig/inet_sharing";


my ($kernel_version) = c::kernel_version() =~ /(...)/;
log::l("[drakgw] kernel_version $kernel_version");

$kernel_version eq '2.2' || $kernel_version eq '2.4' or die "Only for 2.2 or 2.4 kernels.\n";

my $in = 'interactive'->vnew('su', 'default');

!$::isEmbedded && $in->isa('interactive_gtk') and $::isWizard=1;

pur_gtk_mode() if $::isEmbedded && $in->isa('interactive_gtk');

sub sys { system(@_) == 0 or log::l("[drakgw] Warning, sys failed for $_[0]") }

sub outpend { 
    standalone::explanations("modified file $_[0]");
    my $f = shift; local *F; open F, ">>$f" or die "outpend in file $f failed: $!\n"; print F foreach @_;
}

sub start_daemons ()
{
    my $cups_used = 0;
    standalone::explanations("Starting daemons");
    if (-f "/etc/rc.d/init.d/cups") {
        if (system("/etc/rc.d/init.d/cups status >/dev/null") == 0) {
           $cups_used = 1;
           sys("/etc/rc.d/init.d/cups stop");
        }
    }
    system("/etc/rc.d/init.d/dhcpd status >/dev/null") == 0 and sys("/etc/rc.d/init.d/dhcpd stop");
    system("/etc/rc.d/init.d/named status >/dev/null 2>/dev/null") == 0 and sys("/etc/rc.d/init.d/named stop");

    my $netmon = '/usr/sbin/net_monitor';
    my $netmon_need_start;
    if (-x $netmon && `$netmon --status` eq 1) {
	$netmon_need_start = 1;
	system("$netmon --disconnect --force --quiet >/dev/null");
    }
    sys("/etc/rc.d/init.d/network restart");
    $netmon_need_start and system("$netmon --connect --force --quiet >/dev/null");

    sys("sh $rc_firewall_generic");

    sys("/etc/rc.d/init.d/$_ start"), sys("/sbin/chkconfig --level 345 $_ on") foreach 'named', 'dhcpd';
    sys("/etc/rc.d/init.d/cups start") if $cups_used;

    substInFile { s/^INET_SHARING.*\n//; $_ .= "INET_SHARING=enabled\n" if eof } $drakgw_setup;
}

sub stop_daemons ()
{
    standalone::explanations("Stopping daemons");
    system("/etc/rc.d/init.d/dhcpd status >/dev/null") == 0 and sys("/etc/rc.d/init.d/dhcpd stop");
    system("/etc/rc.d/init.d/named status >/dev/null 2>/dev/null") == 0 and sys("/etc/rc.d/init.d/named stop");
    if ($kernel_version eq "2.2") {
	sys("/sbin/ipchains -F");
    } else {
	sys("/sbin/iptables -t nat -F");
    }
    sys("/sbin/chkconfig --level 345 $_ off") foreach 'named', 'dhcpd';

    substInFile { s/^INET_SHARING.*\n//; $_ .= "INET_SHARING=disabled\n" if eof } $drakgw_setup;
}

sub fatal_quit ($)
{
    log::l("[drakgw] FATAL: $_[0]");
    undef $wait_configuring;
    $in->ask_warn('', $_[0]);
    quit_global($in, -1);
}

begin:

#- **********************************
#- * 0th step: verify if we are already set up

if (-f $drakgw_setup) {
    $::Wizard_no_previous = 1;

    if (grep(/enabled/, cat_($drakgw_setup))) {
	my $r = $in->ask_from_list_(_("Internet Connection Sharing currently enabled"),
_("The setup of Internet connection sharing has already been done.
It's currently enabled.

What would you like to do?"),
				   [ __("disable"), __("reconfigure"), __("dismiss") ]) or quit_global($in, 0);
	if ($r eq "disable") {
	    {
		my $wait_disabl = $in->wait_message('', _("Disabling servers..."));
		stop_daemons();
	    }
	    foreach ($dhcpd_conf, $rc_firewall_22, $rc_firewall_24) {
		renamef($_, "$_.drakgwdisable") or die "Could not rename $_ to $_.drakgwdisable" 
	    }
	    log::l("[drakgw] Disabled");
	    $::Wizard_finished = 1;
	    $in->ask_okcancel('', _("Internet connection sharing is now disabled."));
	    quit_global($in, 0);
	}
	if ($r eq "dismiss") {
	    quit_global($in, 0);
	}
    }
    elsif (grep(/disabled/, cat_($drakgw_setup)))
    {
	my $r = $in->ask_from_list_(_("Internet Connection Sharing currently disabled"),
_("The setup of Internet connection sharing has already been done.
It's currently disabled.

What would you like to do?"),
				   [ __("enable"), __("reconfigure"), __("dismiss") ]);
	if ($r eq "enable") {
	    foreach ($dhcpd_conf, $rc_firewall_22, $rc_firewall_24) {
		rename($_, "$_.old") if -f $_;
		rename("$_.drakgwdisable", $_) or die "Could not find configuration. Please reconfigure.";
	    }
	    {
		my $wait_enabl = $in->wait_message('', _("Enabling servers..."));
		start_daemons();
	    }
            log::l("[drakgw] Enabled");
	    $::Wizard_finished = 1;
	    $in->ask_okcancel('', _("Internet connection sharing is now enabled."));
	    quit_global($in, 0);
	}
	if ($r eq "dismiss") {
	    quit_global($in, 0);
	}
    }
    else {
	log::l("[drakgw] Warning, unrecognized config file, ignoring");
	renamef($drakgw_setup, "$drakgw_setup.unrecognized");
    }
}


#- **********************************
#- * 1st step: detect/setup
step_ask_confirm:

$::Wizard_no_previous = 1;
    
$::direct or $in->ask_okcancel(_("Internet Connection Sharing"),
_("You are about to configure your computer to share its Internet connection.
With that feature, other computers on your local network will be able to use this computer's Internet connection.

Note: you need a dedicated Network Adapter to set up a Local Area Network (LAN)."), 1) or quit_global($in, 0);

undef $::Wizard_no_previous;


step_detectsetup:

my @configured_devices = map { /ifcfg-(\S+)/ } glob('/etc/sysconfig/network-scripts/ifcfg*');

my %aliased_devices; 
/^\s*alias\s+(eth[0-9])\s+(\S+)/ and $aliased_devices{$1} = $2 foreach cat_("/etc/modules.conf");

my $card_netconnect = network::netconnect::get_net_device();
defined $card_netconnect and log::l("[drakgw] Information from netconnect: ignore card $card_netconnect");

my @cards = grep {
    log::l("[drakgw] Have network card: $_");
    $_ ne $card_netconnect
} detect_devices::getNet();
log::l("[drakgw] Available network cards: ", join(", ", @cards));

my $format = sub {
    $aliased_devices{$_[0]} ?
      _("Interface %s (using module %s)", $_[0], $aliased_devices{$_[0]}) :
      _("Interface %s", $_[0]);
};

#- setup the network interface we shall use

my $device;
if (!@cards)
{
    $in->ask_warn(_("No network adapter on your system!"), 
		  _("No ethernet network adapter has been detected on your system. Please run the hardware configuration tool."));
    quit_global($in, 0);
}
elsif (@cards == 1)
{
    $device = $cards[0];
    $in->ask_okcancel(_("Network interface"),
_("There is only one configured network adapter on your system:

%s

I am about to setup your Local Area Network with that adapter.", $format->($device)), 1) or goto step_ask_confirm;
}
else
{
    $device = $in->ask_from_listf(_("Choose the network interface"),
				    _("Please choose what network adapter will be connected to your Local Area Network."),
				     $format,
				    \@cards,
				    ) or goto step_ask_confirm;
    defined $device or quit_global($in, 0);
}
standalone::explanations("Choosing network device: $device");


my $lan_address = "192.168.0.0";
my $server_ip = "192.168.0.1";

my $reconf_dhcp_server_intf = 1;

if (grep(/$device/, @configured_devices)) {
  step_warning_already_conf:
    my $auto = _('Yes');
    my $conf = network::read_interface_conf("/etc/sysconfig/network-scripts/ifcfg-$device");
    $in->ask_from(_("Network interface already configured"),
		  _("Warning, the network adapter (%s) is already configured.

Do you want an automatic re-configuration?

You can do it manually but you need to know what you're doing.", $device),
		  [ { label => _("Automatic reconfiguration"), val => \$auto, list => [ _('Yes'), _('No (experts only)') ] },
		    { val => _("Show current interface configuration"), clicked =>
		      sub { $in->ask_warn(_('Current interface configuration'),
					  _("Current configuration of `%s':

Network: %s
IP address: %s
IP attribution: %s
Driver: %s", $device, $conf->{NETWORK}, $conf->{IPADDR}, $conf->{BOOTPROTO}, $aliased_devices{$device} || '(unknown)')) } } ]) or goto step_detectsetup;
    
    if ($auto ne _('Yes')) {
	$reconf_dhcp_server_intf = 0;
	$server_ip = $conf->{IPADDR};
	$lan_address = $conf->{NETWORK};
	$in->ask_from('',
		      _("I can keep your current configuration and assume you already set up a DHCP server; in that case please verify I correctly read the C-Class Network that you use for your local network; I will not reconfigure it and I will not touch your DHCP server configuration.

Else, I can reconfigure your interface and (re)configure a DHCP server for you.

", $device),
		      [ { label => _("C-Class Local Network"), val => \$lan_address, type => 'entry' },
			{ label => _("(This) DHCP Server IP"), val => \$server_ip, type => 'entry' },
			{ label => _("Re-configure interface and DHCP server"), val => \$reconf_dhcp_server_intf, type => 'bool' } ])
	  or goto step_warning_already_conf;
    }
}
    
if (!($lan_address =~ s/\.0$//)) {
    $in->ask_warn('', 
		  _("The Local Network did not finish with `.0', bailing out."));
    quit_global($in, 0);
}
standalone::explanations("Using LAN address <$lan_address>");


#- test for potential conflict with other networks

foreach (grep { $_ ne $device } @configured_devices)
{
    grep(/$lan_address/, cat_("/etc/sysconfig/network-scripts/ifcfg-$_")) and
      ($in->ask_warn('', _("Potential LAN address conflict found in current config of %s!\n", $_)) or goto step_detectsetup);
}


#- test for potential conflict with previous firewall config

if ($kernel_version eq '2.2') {
    if (-f '/etc/sysconfig/ipchains' || -x '/sbin/ipchains' && listlength(`/sbin/ipchains -nL`) > 3) {
	$in->ask_okcancel(_("Firewalling configuration detected!"),
			  _("Warning! An existing firewalling configuration has been detected. You may need some manual fix after installation.")) or goto step_detectsetup;
    }
} else {
    system('modprobe iptable_nat');
    if (-f '/etc/sysconfig/iptables' || -x '/sbin/iptables' && listlength(`/sbin/iptables -t nat -nL`) > 8) {
	$in->ask_okcancel(_("Firewalling configuration detected!"),
			  _("Warning! An existing firewalling configuration has been detected. You may need some manual fix after installation.")) or goto step_detectsetup;
    }
}


#- **********************************
#- * 2nd step: configure

$wait_configuring = $in->wait_message(_("Configuring..."), 
				      _("Configuring scripts, installing software, starting servers..."));


#- setup the /etc/sysconfig/network-script/ script

if ($reconf_dhcp_server_intf) {
    standalone::explanations("Reconfiguring network parameters of $device");
    my $network_scripts = "/etc/sysconfig/network-scripts";
    my $ifcfg = "$network_scripts/ifcfg-$device";
    renamef($ifcfg, "$network_scripts/old.ifcfg-$device");
    output($ifcfg, qq(DEVICE=$device
BOOTPROTO=static
IPADDR=$server_ip
NETMASK=255.255.255.0
NETWORK=$lan_address.0
BROADCAST=$lan_address.255
ONBOOT=yes
));
}


#- install and setup the RPM packages

my $rpms_to_install;
my %rpm2file = ( ipchains => '/sbin/ipchains',
		 iptables => '/sbin/iptables',
		 'dhcp-server' => '/usr/sbin/dhcpd',
		 bind => '/usr/sbin/named',
		 'caching-nameserver' => '/var/named/named.local');

#- first: try to install all in one step
my @needed_to_install = grep { !-e $rpm2file{$_} } keys %rpm2file;
@needed_to_install and $in->do_pkgs->install(@needed_to_install);
#- second: try one by one if failure detected
if (grep { !-e $rpm2file{$_} } keys %rpm2file) {
    foreach (keys %rpm2file) {
	-e $rpm2file{$_} or $in->do_pkgs->install($_);
	-e $rpm2file{$_} or fatal_quit(_("Problems installing package %s", $_));
    }
}


#- setup the masquerading configuration
standalone::explanations("Modifying firewalling configuration");
if (!-f $rc_firewall_generic) {
    output($rc_firewall_generic, "#!/bin/sh
#
# Automatically generated by drakgw
[ -x $rc_firewall_drakgw ] && $rc_firewall_drakgw
");
    chmod 0700, $rc_firewall_generic;
}
elsif (!grep(/drakgw/, cat_($rc_firewall_generic))) {
    outpend($rc_firewall_generic, "
# Automatically added by drakgw
[ -x $rc_firewall_drakgw ] && $rc_firewall_drakgw

");
}

output($rc_firewall_drakgw, q(#!/bin/sh
KERNELMAJ=`uname -r | sed                   -e 's,\..*,,'`
KERNELMIN=`uname -r | sed -e 's,[^\.]*\.,,' -e 's,\..*,,'`

if [ "$KERNELMAJ" -eq 2 -a "$KERNELMIN" -eq 2 ]; then
    [ -x ) . $rc_firewall_22 . ' ] && ' . $rc_firewall_22 . q(
fi
if [ "$KERNELMAJ" -eq 2 -a "$KERNELMIN" -eq 4 ]; then
    [ -x ) . $rc_firewall_24 . ' ] && ' . $rc_firewall_24 . q(
fi
    ));

chmod 0700, $rc_firewall_drakgw;


output($rc_firewall_22, 
qq(#!/bin/sh
#
# rc.firewall - Initial SIMPLE IP Masquerade test for 2.1.x and 2.2.x kernels using IPCHAINS
#
# Load all required IP MASQ modules
#
#   NOTE:  Only load the IP MASQ modules you need.  All current IP MASQ modules
#          are shown below but are commented out from loading.

# Needed to initially load modules
#
/sbin/depmod -a

# Supports the proper masquerading of FTP file transfers using the PORT method
#
/sbin/modprobe ip_masq_ftp

# Supports the masquerading of RealAudio over UDP.  Without this module,
#       RealAudio WILL function but in TCP mode.  This can cause a reduction
#       in sound quality
#
/sbin/modprobe ip_masq_raudio

# Supports the masquerading of IRC DCC file transfers
#
/sbin/modprobe ip_masq_irc


# Supports the masquerading of Quake and QuakeWorld by default.  This modules is
#   for for multiple users behind the Linux MASQ server.  If you are going to play
#   Quake I, II, and III, use the second example.
#
#   NOTE:  If you get ERRORs loading the QUAKE module, you are running an old
#   -----  kernel that has bugs in it.  Please upgrade to the newest kernel.
#
#Quake I / QuakeWorld (ports 26000 and 27000)
#/sbin/modprobe ip_masq_quake
#
#Quake I/II/III / QuakeWorld (ports 26000, 27000, 27910, 27960)
/sbin/modprobe ip_masq_quake 26000,27000,27910,27960


# Supports the masquerading of the CuSeeme video conferencing software
#
/sbin/modprobe ip_masq_cuseeme

#Supports the masquerading of the VDO-live video conferencing software
#
/sbin/modprobe ip_masq_vdolive


#CRITICAL:  Enable IP forwarding since it is disabled by default since
#
#           Redhat Users:  you may try changing the options in /etc/sysconfig/network from:
#
#                       FORWARD_IPV4=false
#                             to
#                       FORWARD_IPV4=true
#
echo 1 > /proc/sys/net/ipv4/ip_forward


# Dynamic IP users:
#
#   If you get your IP address dynamically from SLIP, PPP, or DHCP, enable this following
#       option.  This enables dynamic-ip address hacking in IP MASQ, making the life 
#       with Diald and similar programs much easier.
#
#echo 1 > /proc/sys/net/ipv4/ip_dynaddr


# MASQ timeouts
#
#   2 hrs timeout for TCP session timeouts
#  10 sec timeout for traffic after the TCP/IP "FIN" packet is received
#  160 sec timeout for UDP traffic (Important for MASQ'ed ICQ users) 
#
/sbin/ipchains -M -S 7200 10 160


# DHCP:  For people who receive their external IP address from either DHCP or BOOTP
#        such as ADSL or Cablemodem users, it is necessary to use the following
#        before the deny command.  The "bootp_client_net_if_name" should be replaced
#        the name of the link that the DHCP/BOOTP server will put an address on to?
#        This will be something like "eth0", "eth1", etc.
#
#        This example is currently commented out.
#
#
#/sbin/ipchains -A input -j ACCEPT -i bootp_clients_net_if_name -s 0/0 67 -d 0/0 68 -p udp

# Enable simple IP forwarding and Masquerading
#
#  NOTE:  The following is an example for an internal LAN address in the 192.168.0.x
#         network with a 255.255.255.0 or a "24" bit subnet mask.
#
#         Please change this network number and subnet mask to match your internal LAN setup
#
/sbin/ipchains -P forward DENY
/sbin/ipchains -A forward -s $lan_address.0/24 -j MASQ

# Let incoming packets arrive to our interface, in case there are some firewall rules to come
/sbin/ipchains -A input -i $device -j ACCEPT
));
chmod 0700, $rc_firewall_22;


output($rc_firewall_24, qq(#!/bin/sh
# Load the NAT module (this pulls in all the others).
modprobe iptable_nat

# Turn on IP forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward

# In the NAT table (-t nat), Append a rule (-A) after routing (POSTROUTING)
# which says to MASQUERADE the connection (-j MASQUERADE).
/sbin/iptables -t nat -A POSTROUTING -s $lan_address.0/24 -j MASQUERADE

# Allows forwarding specifically to our LAN
/sbin/iptables -A FORWARD -s $lan_address.0/24 -j ACCEPT

# Allow dhcp requests
/sbin/iptables -A INPUT -i $device -p udp --sport bootpc --dport bootps -j ACCEPT
/sbin/iptables -A INPUT -i $device -p tcp --sport bootpc --dport bootps -j ACCEPT
/sbin/iptables -A INPUT -i $device -p udp --sport bootps --dport bootpc -j ACCEPT
/sbin/iptables -A INPUT -i $device -p tcp --sport bootps --dport bootpc -j ACCEPT

# Allow dns requests
/sbin/iptables -A INPUT -i $device -p udp --dport domain -j ACCEPT
/sbin/iptables -A INPUT -i $device -p tcp --dport domain -j ACCEPT
));
chmod 0700, $rc_firewall_24;


#- be sure that FORWARD_IPV4 is enabled in /etc/sysconfig/network

substInFile { s/^FORWARD_IPV4.*\n//; $_ .= "FORWARD_IPV4=true\n" if eof } $sysconf_network;


#- setup the DHCP server

if ($reconf_dhcp_server_intf) {
    standalone::explanations("Configuring a DHCP server on $lan_address.0");
    renamef($dhcpd_conf, "$dhcpd_conf.old");
    output($dhcpd_conf, qq(subnet $lan_address.0 netmask 255.255.255.0 {
	# default gateway
	option routers $server_ip;
	option subnet-mask 255.255.255.0;

	option domain-name "homelan.org";
	option domain-name-servers $server_ip;

	range dynamic-bootp $lan_address.16 $lan_address.253;
	default-lease-time 21600;
	max-lease-time 43200;
}
));
}

my $update_dhcp = '/usr/sbin/update_dhcp.pl';
-e $update_dhcp and system($update_dhcp);


#- put the interface for the dhcp server in the sysconfig-dhcp config, for the /etc/init.d script of dhcpd

substInFile { s/^INTERFACES\n//; $_ .= "INTERFACES=\"$device\"\n" if eof } $sysconf_dhcpd;


#- Set up /etc/cups/cupsd.conf to make the broadcasting of the printer info
#- working correctly: 
#- 
#-  1. ServerName <server's IP address>  # because clients do necessarily 
#-                                       # know the server's name
#-
#-  2. BrowseAddress <server's Broadcast IP> # broadcast printer info into
#-                                           # the local network.
#-
#-  3. BrowseOrder Deny,Allow
#-     BrowseDeny All
#-     BrowseAllow <IP mask for local net> # Only accept broadcast signals 
#-                                         # coming from local network
#-
#-  4. <Location />
#-     Order Deny,Allow
#-     Deny From All
#-     Allow From <IP mask for local net> # Allow only machines of local 
#-     </Location>                        # network to access the server
#-     
#- These steps are only done when the CUPS package is installed.

#- Modify the root location block in /etc/cups/cupsd.conf

if (-f $cups_conf) {
    standalone::explanations("Updating CUPS configuration accordingly");

    substInFile {
        s/^ServerName[^:].*\n//; $_ .= "ServerName $server_ip\n" if eof;
        s/^BrowseAddress.*\n//; $_ .= "BrowseAddress $lan_address.255\n" if eof;
        s/^BrowseOrder.*\n//; $_ .= "BrowseOrder Deny,Allow\n" if eof;
        s/^BrowseDeny.*\n//; $_ .= "BrowseDeny All\n" if eof;
        s/^BrowseAllow.*\n//; $_ .= "BrowseAllow $lan_address.*\n" if eof;
    } $cups_conf;

    my @cups_conf_content = cat_($cups_conf);
    my @root_location; my $root_location_start; my $root_location_end;

    # Cut out the root location block so that it can be treated seperately
    # without affecting the rest of the file
    if (grep(m|^\s*<Location\s+/\s*>|, @cups_conf_content)) {
	$root_location_start = -1;
	$root_location_end = -1;
	# Go through all the lines, bail out when start and end line found
	for (my $i = 0; $i < @cups_conf_content && $root_location_end == -1; $i++) {
	    if ($cups_conf_content[$i] =~ m|^\s*<\s*Location\s+/\s*>|) {
		$root_location_start = $i;
	    } elsif (($cups_conf_content[$i] =~ m|^\s*<\s*/Location\s*>|) && ($root_location_start != -1)) {
		$root_location_end = $i;
	    }
	}
	# Rip out the block and store it seperately
	@root_location = splice(@cups_conf_content, $root_location_start, $root_location_end - $root_location_start + 1);
    } else {
	# If there is no root location block, create one
	$root_location_start = @cups_conf_content;
	@root_location = ("<Location />\n", "</Location>\n");
    }
 
    # Delete all former "Order", "Allow", and "Deny" lines from the root location block
    s/^\s*Order.*//, s/^\s*Allow.*//, s/^\s*Deny.*// foreach @root_location;
 
    # Add the new "Order" and "Deny" lines, add an "Allow" line for the local network
    splice(@root_location, -1, 0, $_) foreach ("Order Deny,Allow\n", "Deny From All\n", "Allow From 127.0.0.1\n",
					       "Allow From $lan_address.*\n");
 
    # Put the changed root location block back into the file
    splice(@cups_conf_content, $root_location_start, 0, @root_location);
 
    output $cups_conf, @cups_conf_content;
}


#- start the daemons

substInFile { s/^INTERFACE.*\n//; $_ .= "INTERFACE=$device\n" if eof } $drakgw_setup;
start_daemons();


#- bye-bye message

undef $wait_configuring;

$::Wizard_no_previous = 1;
$::Wizard_finished = 1;

$in->ask_okcancel(_("Congratulations!"), 
_("Everything has been configured.
You may now share Internet connection with other computers on your Local Area Network, using automatic network configuration (DHCP)."));


log::l("[drakgw] Installation complete, exiting");
quit_global($in, 0);

sub quit_global {
    my ($in, $exitcode) = @_;
    $in->exit($exitcode);
    goto begin
}

sub pur_gtk_mode
{
    require Gtk;
    init Gtk;
    my $setup_state = grep(/disabled/, cat_($drakgw_setup)) ? _("The setup has already been done, but it's currently disabled.") :
                      grep(/enabled/, cat_($drakgw_setup))  ? _("The setup has already been done, and it's currently enabled.") :
                      _("No Internet Connection Sharing has ever been configured.");
    
    my $window1 = $::isEmbedded ? new Gtk::Plug ($::XID) : new Gtk::Window -toplevel;
    $window1->signal_connect ( delete_event => sub { Gtk->exit(0); });
    $window1->set_position(1);
    $window1->set_title(_("Internet connection sharing configuration"));
    $window1->border_width(10);
    my $vbox1 = new Gtk::VBox(0,0);
    $window1->add($vbox1);
    my $hbox1 = new Gtk::HBox(0,0);
    $vbox1->pack_start($hbox1,1,1,0);
    my $label1 = new Gtk::Label(
_("Welcome to the Internet Connection Sharing utility!

%s

Click on Configure to launch the setup wizard.", $setup_state));
    $hbox1->pack_start($label1,1,1,0);
    my $hbox2 = new Gtk::HBox(0,0);
    $vbox1->pack_start($hbox2,1,1,0);
    
    my $bbox1 = new Gtk::HButtonBox;
    $vbox1->pack_start($bbox1,0,0,0);
    $bbox1->set_layout(-end);
    my $button_conf = new Gtk::Button _("Configure");
    $button_conf->signal_connect ( clicked => sub {
				       system("/usr/sbin/drakgw --wizard");
				       kill(USR1, $::CCPID);
				   });
    $bbox1->add($button_conf);
    my $button_cancel = new Gtk::Button _("Cancel");
    $button_cancel->signal_connect ( clicked => sub {
					 kill(USR1, $::CCPID);
				     });
    $bbox1->add($button_cancel);
    $window1->show_all();
    Gtk->main_iteration while Gtk->events_pending;
    $::isEmbedded and kill USR2, $::CCPID;
    Gtk->main;
    Gtk->exit(0);
    
}


#-------------------------------------------------
#- $Log$
#- Revision 1.60  2002/03/07 13:10:06  gc
#- - call net_monitor to disable internet
#-   connection before network-restart
#- - user return value when status'ing the
#-   initscripts rather than grepping their
#-   text output
#-
#- Revision 1.59  2002/02/22 18:58:22  gc
#- exit the pur_gtk version after launching the wizard version
#-
#- Revision 1.58  2002/01/18 20:19:44  gc
#- - move 'use standalone' up to comply to 'explanations'
#- - write higher-level 'explanations'
#- - small fix, s/`ls ..`/glob(..)/
#-
#- Revision 1.57  2001/12/17 17:58:20  gc
#- drakgw for gold
#-
#- Revision 1.56  2001/10/30 19:10:41  gc
#- use isa rather than ref to test if we're gtk
#-
#- Revision 1.55  2001/10/02 10:28:14  gc
#- don't call pkgs_install when no package needs to be installed
#-
#- Revision 1.54  2001/09/18 20:36:20  damien
#- debug
#-
#- Revision 1.53  2001/09/12 10:57:01  damien
#- corrected wizard mode in newt mode
#-
#- Revision 1.52  2001/09/06 15:38:09  gc
#- works now ;p
#-
#- Revision 1.51  2001/08/29 21:52:34  gc
#- quit_global
#-
#- Revision 1.50  2001/08/18 00:06:32  siegel
#- fixed i18n
#-
#- Revision 1.49  2001/08/09 09:35:37  gc
#- use vnew the right way everywhere
#-
#- Revision 1.48  2001/08/09 09:15:38  gc
#- - if package installs fail, redo one by one to know which one failed
#- - try to not end up with a failing configuration file, if program is brutally stopped
#- - if unrecognized config file, don't fail, rather ignore it and proceed
#- - run dhcpd_update feature (if present) after setup of dhcp server
#-
#- Revision 1.47  2001/08/08 18:26:31  prigaux
#- add interactive_pkgs stuff
#-
#- Revision 1.46  2001/08/06 13:11:35  yduret
#- use MDK::Common;
#- use network::netconnect; and update functions call from netconnect
#-
#- Revision 1.45  2001/07/24 22:39:28  prigaux
#- move to MDK::Common, bool->to_bool
#-
#- Revision 1.44  2001/05/16 11:13:21  damien
#- added icon management
#-
#- Revision 1.43  2001/05/15 14:36:31  gc
#- full path for iptables
#-
#- Revision 1.42  2001/04/12 13:50:24  gc
#- add some rule so later on tinyfirewall will not prevent everything from working
#-
#- Revision 1.41  2001/04/11 15:28:36  gc
#- kosmetik
#-
#- Revision 1.40  2001/04/11 15:16:34  gc
#- do i18n for title also
#-
#- Revision 1.39  2001/04/10 21:33:15  gc
#- add INTERFACE param in sysconfig parameter for smooth interoperation with bastille-firewall
#-
#- Revision 1.38  2001/04/09 18:09:38  yduret
#- deyvounification : remove some un-useful comments in code
#-
#- Revision 1.37  2001/04/09 16:29:20  gc
#- do not die when an initscript returns non-0 (initscripts too buggy)
#-
#- Revision 1.36  2001/04/09 11:39:40  gc
#- fix for when there is an already existing rc.firewall
#- complies with old format of drakgw so that upgrades will work
#-
#- Revision 1.35  2001/04/08 05:33:14  damien
#- updated
#-
#- Revision 1.34  2001/04/06 15:09:15  yduret
#- swap cancel/configure button
#-
#- Revision 1.33  2001/04/06 14:12:06  gc
#- - correct yvounetification in i18n stuff
#- - remove some remaining debugging printings
#- - add a bit more of explanations when starting drakgw in wizard mode
#-
#- Revision 1.32  2001/04/06 01:34:44  yduret
#- recoded a embedded && gtk mode
#-
#- Revision 1.31  2001/03/31 14:21:10  pablo
#- Updated po files and help messages (patch from Pixel)
#-
#- Revision 1.30  2001/03/29 11:52:15  damien
#- updated for new wiz png policy
#-
#- Revision 1.29  2001/03/26 15:29:01  gc
#- first attempt at pixelization of code (till's cups patches)
#-
#- Revision 1.28  2001/03/21 18:07:36  gc
#- honour embedded mode
#-
#- Revision 1.27  2001/03/13 16:23:29  gc
#- fix for bind
#-
#- Revision 1.26  2001/03/13 15:31:05  gc
#- - fix destructive parts of pixelization
#- - fix some own bugs
#-
#- Revision 1.25  2001/03/13 00:00:11  prigaux
#- pixelization
#-
#- Revision 1.24  2001/03/12 18:26:16  gc
#- - make it work as a wizard
#- - make it work with iptables (kernel-2.4)
#-
#- Revision 1.23  2001/03/01 00:18:17  damien
#- updated embedded mode
#-
#- Revision 1.22  2001/02/26 18:39:12  prigaux
#- pixelization
#-
#- Revision 1.21  2001/02/08 10:11:37  damien
#- implemented or updated embedded mode
#-
#- Revision 1.20  2001/02/08 07:00:41  damien
#- added embedded and (ugly) wizard mode.
#-
#- Revision 1.19  2001/01/10 00:32:42  prigaux
#- use standalone and standalone::pkgs_install
#-
#- Revision 1.18  2000/12/16 16:13:34  prigaux
#- use ldetect-lst
#-
#- Revision 1.17  2000/11/13 15:48:33  gc
#- Integrate Till's patches for better work with Cups.
#-
#- Revision 1.16  2000/10/10 15:31:50  gc
#- make only one call to urpmi in order to install all the needed rpm's
#-