#!/usr/bin/perl -w
#
# $Id$
# Copyright B. Cornec 2005-2014
# Provided under the GPL v2
#
# Get the complete network configuration of the system
#
use strict 'vars';
use IO::Interface::Simple;
use Net::IPv4Addr qw( :all );;
use Socket;
use ProjectBuilder::Base;
use ProjectBuilder::Version;
use Data::Dumper;
use Getopt::Long qw(:config auto_abbrev no_ignore_case);
use English;


=pod

=head1 NAME

mr-net-get-config keeps track of the network configuration of the system studied

=head1 DESCRIPTION

mr-net-get-config keeps track of the network configuration of the system studied wrt a network share passed as first parameter and store the result in the file given as second parameter (typically /tmp/mondorestore.cfg)

=head1 SYNOPSIS

mr-net-get-config [-v][-h][-f /path/to/file] proto://[user@]server/export|[user@]server:/export

=head1 ARGUMENTS

=over 4

=item B<proto://[user@]server/export|[user@]server:/export>

This is the name of the network server, followed by a ':' and the exported directory if nfs or you have to specify the protocol used (nfs, sshfs or smbfs) followed by the network server and the exported directory (without ':'). An optional user name may be provided in case it's needed.

=back 

=head1 OPTIONS

=over 4

=item B<-v|--verbose>

Increase verbosity

=item B<-h|--help>

Print a brief help message and exits.

=item B<--man>

Prints the manual page and exits.

=item B<-f /path/to/file> 

This is the path of the output file into which we want to store the network configuration.
By default the command prints on the standard output.

=back

=head1 WEB SITES

The main Web site of the project is available at L<http://www.mondorescue.org>. Bug reports should be filled using the trac instance of the project at L<http://trac.mondorescue.org/>.

=head1 USER MAILING LIST

For community exchanges around MondoRescue please use the list L<http://sourceforge.net/mailarchive/forum.php?forum_name=mondo-devel>

=head1 AUTHORS

The MondoRescue team lead by Bruno Cornec L<mailto:bruno@mondorescue.org>.

=head1 COPYRIGHT

MondoRescue is distributed under the GPL v2.0 license or later,
described in the file C<COPYING> included with the distribution.

=cut

# Global variables
my ($mrver,$mrrev) = pb_version_init();
my $appname = "mr-net-get-config";
my %opts;					# CLI Options

# Initialize the syntax string

pb_syntax_init("$appname Version $mrver-$mrrev\n");

GetOptions("help|?|h" => \$opts{'h'}, 
		"man" => \$opts{'man'},
		"verbose|v+" => \$opts{'v'},
		"file|f=s" => \$opts{'f'},
) || pb_syntax(-1,0);

if (defined $opts{'h'}) {
	pb_syntax(0,1);
}
if (defined $opts{'man'}) {
	pb_syntax(0,2);
}
if (defined $opts{'v'}) {
	$pbdebug = $opts{'v'};
}
pb_log_init($pbdebug, $pbLOG);

my $fd;
if (defined $opts{'f'}) {
	open(CFG, "> $opts{'f'}") || die "Unable to write into $opts{'f'}: $!";
	$fd=\*CFG;
} else {
	$fd=\*STDOUT;
}

# Normalize URI
my $url = $ARGV[0];
if ($url !~ /:\/\//) {
	# No Protocol given
	# Protocol for sharing is NFS by default
	# Format is without ':' then
	$url =~ s/://;
	$url = "nfs://".$url;
}

# Analyze URI
my ($scheme, $account, $host, $port, $path) = pb_get_uri($url);

# If host is a name transform into an IP
my $hostip = inet_ntoa(scalar gethostbyname($host || 'localhost'));

my $found = 0;

# We need to loop on all if to see which one is on the same LAN as the server
for my $if (IO::Interface::Simple->interfaces) {
	# Skip fake interfaces
	next if (not defined $if->address);
	pb_log(2, "interface = $if\n");
	pb_log(2, "--\n");
	pb_log(2, "addr =      $if->address\n",
		"broadcast = $if->broadcast\n",
		"netmask =   $if->netmask\n",
		"dstaddr =   ",$if->dstaddr,"\n",
		"hwaddr =    $if->hwaddr\n",
		"mtu =       ",$if->mtu,"\n",
		"metric =    ",$if->metric,"\n",
		"index =     ",$if->index,"\n");
	pb_log(2, "is running\n")     if $if->is_running;
	pb_log(2, "is broadcast\n")   if $if->is_broadcast;
	pb_log(2, "is p-to-p\n")      if $if->is_pt2pt;
	pb_log(2, "is loopback\n")    if $if->is_loopback;
	pb_log(2, "is promiscuous\n") if $if->is_promiscuous;
	pb_log(2, "is multicast\n")   if $if->is_multicast;
	pb_log(2, "is notrailers\n")  if $if->is_notrailers;
	pb_log(2, "is noarp\n")       if $if->is_noarp;
	pb_log(2, "--\n");
	if (ipv4_in_network($if->address, $if->netmask, $hostip)) {
		pb_log(1, "Netfs server $host is in network $if->address/$if->netmask\n");
		$found = 1;
		# So generate conf file
		my ($iface,$gw) = mr_net_get_def_gw();
		mr_net_print_conf($fd, $if, $scheme, $if->address, $if->netmask, $if->broadcast, $if->hwaddr, $ARGV[0], $account, $hostip, $gw);
		last if ($pbdebug > 1);
	}
}
if ($found == 0) {
	# Not found yet, so use the default GW to reach the server
	my ($iface,$gw) = mr_net_get_def_gw();
	my $if = IO::Interface::Simple->new($iface);
	mr_net_print_conf($fd, $if, $scheme, $if->address, $if->netmask, $if->broadcast, $if->hwaddr, $ARGV[0], $account, $hostip, $gw);
	}

close($fd);

sub mr_net_get_def_gw {

my ($iface,$dest,$gw,$foo);

open(ROUTE, "/proc/net/route") || die "Unable to read /proc/net/route: $!";
while (<ROUTE>) {
	($iface,$dest,$gw,$foo) = split(/\s+/,$_);
	# Keep only default route
	next if ($dest !~ /^00000000$/);
	$gw =~ s/([A-z0-9]{2})([A-z0-9]{2})([A-z0-9]{2})([A-z0-9]{2})/hex($4).".".hex($3).".".hex($2).".".hex($1)/eg;
	last;
}
close(ROUTE);
return($iface,$gw);
}

sub mr_net_print_conf {

my ($fd, $iface, $scheme, $netfs_ipaddr, $netfs_netmask, $netfs_broadcast, $netfs_hwaddr, $netfs_server_mount, $account, $hostip, $gw) = @_;

print $fd "netfs-dev $iface\n";
print $fd "netfs-proto $scheme\n";
print $fd "netfs-client-ipaddr $netfs_ipaddr\n";
print $fd "netfs-client-netmask $netfs_netmask\n";
print $fd "netfs-client-broadcast $netfs_broadcast\n";
print $fd "netfs-client-hwaddr $netfs_hwaddr\n";
print $fd "netfs-server-mount $ARGV[0]\n";
print $fd "netfs-server-user $account\n";
print $fd "netfs-server-ipaddr $hostip\n";
print $fd "netfs-client-defgw $gw\n";
}
