#!/usr/bin/perl 
# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*-
# vim: ts=4 sts=4 sw=4:
# ----------------------------------------------------------------------------------
# $Source$
#
# Copyright (c) 2014
# BRUKER BIOSPIN GMBH
# D-76287 Rheinstetten, Germany
#
# All Rights Reserved
#
# ----------------------------------------------------------------------------------

use strict;
use warnings;
use English;
use Getopt::Long;
use File::Basename;
use File::Spec;
use File::Find ();
use Pod::Usage;
use Sys::Syslog qw(:standard :macros);  # standard functions & macros
use Data::Dumper;

sub ShowHashArray($%);

my $program = basename($0);

####
# Supported options
my $help = 0;
my $man = 0;
my $info = 0;
my $test = 0;
my $syslog = 1;
my $verbose = 1;
my $inputDevices;
GetOptions(
	   'help|?' => \$help,
	   'man'  => \$man,
	   'verbose+'  => \$verbose,
	   'syslog!'  => \$syslog,
	   'test'  => \$test,
	   'device=s'=> \$inputDevices,
	  ) || pod2usage(2);
pod2usage(1) if $help;
pod2usage(-exitstatus => 0, -verbose => 2) if $man;
die "Missing -device argument!\n" unless $inputDevices;

my @networkDevices;

if($inputDevices=~/,/) {
	@networkDevices = split /,/, $inputDevices;
} else {
	$networkDevices[0] = $inputDevices;
}

print "Input network devices are:@networkDevices" if $verbose;

###
# Some info about myself
my @Version =  split(' ','$Revision$ ');
my $Version = $Version[1];
print "$program (Version $Version)\nCopyright (c) 2015 Bruker BioSpin GmbH\n\n" if $verbose;


openlog('topspin-network.service', 'nofatal,pid', 'user') if $syslog;

##
# On master image SELinux is enabled
my $selinuxenabled = 1;
#DESCRIPTION
#  selinuxenabled  Indicates  whether SELinux is enabled or disabled. 
#  It exits with status 0 if SELinux is enabled and 1 if it is not enabled.
system('selinuxenabled')  and $selinuxenabled == 0;


###
# default file names
my $netcfg	= '/etc/sysconfig/network-scripts/ifcfg';
my $statusfile	= '/etc/sysconfig/bruker-setup';
my $grubcfg 	= '/etc/default/grub';
my $sysclass	= '/sys/class/net';

####
# Now get MAC addresses and PCI Bus info of Ethernet Cards
####
my %mac;
my %manufacturer;
my %interface;

opendir(NET,$sysclass) || die "can't open to $sysclass: $!\n";
my @ethdevs = grep(!/^\./, readdir(NET));
closedir(NET);

print "Found Ether Devices: @ethdevs\n" if $verbose;
my %dev;
# Set network devices as hash keys
$dev{$_}++ for (@ethdevs);
my $success = 0;
foreach my $networkDevice (@networkDevices) {
	print "Check device $networkDevice\n" if $verbose;
	if (exists $dev{$networkDevice}) {
		# check for physical devs
	    my $linkname = readlink(join('/',$sysclass,$networkDevice));
		print "Linkname: $linkname\n" if $verbose;

	    # skip virtual
		if ($linkname =~ /virtual\/net/) {
			my $errMessage = "Device ($networkDevice) is a not usable virtual network device";
			print "$errMessage\n" if $verbose;
			syslog(LOG_ERR, $errMessage) if $syslog;
		} else {
			print "Using network interface ($networkDevice) for IP link to eth0\n" if $verbose;
			# get MAC Address from real network device
			my $addrpath = join('/',$sysclass, $networkDevice, 'address');
		    open(ADR,$addrpath) || die "can't open to $addrpath: $!\n";
			my $addr = <ADR>;
			close(ADR);
		    chomp $addr;
			print "MAC address: $addr\n" if $verbose;

			# create IP Link
			my $cmd = 'ip link add link ' . $networkDevice . ' eth0 type macvlan';
			print "$cmd\n" if $verbose;
			syslog(LOG_INFO, $cmd) if $syslog;
			my $returnCode = system($cmd) unless $test;
			if($returnCode != 0 ) {
				my $errMessage = "System call ($cmd) returned an error (Code: $returnCode).";
				exit $returnCode;
			}
			# set MAC Address to cloned device
			$cmd = 'ip link set eth0 address ' . $addr;
			print "$cmd\n" if $verbose;
			syslog(LOG_INFO, $cmd) if $syslog;
			my $returnCode = system($cmd) unless $test;
			if($returnCode != 0) {
				my $errMessage = "System call ($cmd) returned an error (Code: $returnCode).";
				exit $returnCode;
			}
			$success = 1;
			last;
		}
	} else {
		my $errMessage = "Device ($networkDevice) is not an existing network device";
		print "$errMessage\n" if $verbose;
		syslog(LOG_WARNING, $errMessage) if $syslog;
	}
}
if($success==0) {
	my $errMessage = "No configurable network device was found to link to eth0";
	print "$errMessage\n" if $verbose;
	syslog(LOG_ERR, $errMessage) if $syslog;
	exit 1;
}
closelog if $syslog;

exit;


sub ShowHashArray($%)
{
    my $head = shift;
    my %hash = @ARG;
    print "$head:\n";
    while (my($key,$val) = each(%hash))
    {
	print " $key => $val\n";
    }
}
