#!/usr/bin/perl 
# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*-
# vim: ts=4 sts=4 sw=4:

#ident "$Id: assign-default-networks,v 1.4 2015/05/20 09:28:47 carsten.kuhl Exp $
# Copyright (c) 2014 Bruker BioSpin GmbH"";

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;

#use lib "/usr/share/bruker-setup";

my $program = basename($0);

die "Only root may run $program\n" unless $EFFECTIVE_USER_ID == 0;

sub WriteNetConfig_C5();
sub WriteNetConfig_C7();
sub ShowHashArray($%);
sub GetSmbiosSerialNumber();
sub ShowCurrentNetworkAssignment();
sub SwapMACAssignment();
sub StatusfileUpdate(@);
sub StatusfileInfo($);
sub setMacAdress($);

# for the convenience of &wanted calls, including -eval statements:
use vars qw/*name *dir *prune/;
*name   = *File::Find::name;
*dir    = *File::Find::dir;
*prune  = *File::Find::prune;

####
# Supported options
my $help = 0;
my $man = 0;
my $info = 0;
my $save = 0;
my $test = 0;
my $syslog = 1;
my $kudzu = 0;
my $verbose = 0;

GetOptions(
	   'help|?' => \$help,
	   'man'  => \$man,
	   'verbose+'  => \$verbose,
	   'info'  => \$info,
	   'save'  => \$save,
	   'syslog!'  => \$syslog,
	   'test'  => \$test,
	   'hwconf'  => \$kudzu,
	  ) || pod2usage(2);
pod2usage(1) if $help;
pod2usage(-exitstatus => 0, -verbose => 2) if $man;

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

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

my $cfgENS = '/etc/sysconfig/network-scripts/ifcfg-ens1';

my $OS_Version = get_os_version();

print "OS_Version = $OS_Version\n" if $verbose;

###
# Only curent State required ?
ShowCurrentNetworkAssignment() if $show;

####
# Now get MAC addresses and PCI Bus info of Ethernet Cards
####
my %mac;
my %product;
my %manufacturer;
my $logicalname;
my @EtherDesc;
###
# Call lshw with NETWORK Class option to fetch MAC info
###
my $eth = 'none';
my $netif= -1 ;
my $swaprequired;
my @lines;

die "Missing $lshw\n" unless -x $lshw;
$/ = '*-network';
open(LSHW,"$lshw -quiet -class network|") || die "can't pipe to $lshw: $!\n";
while (<LSHW>)
{
    chomp;
    $logicalname = "";   
    @lines = split("\n",$_);
    foreach my $line (@lines) {
	if ( /logical name:\s([\w\d]*)/ ) {
	  $logicalname = $1;
	  next:
	}
	if (/serial:\s([0-9A-Fa-f:]+)/ && $logicalname ne "") {
	  $mac{$logicalname} = $1;
	  last;
	}
    }
}
close(LSHW);
$/ = "\n";
if ($verbose)
{
    ShowHashArray"MAC:",(%mac);
}

###
# Set MAC Address for the device, which is not eno1
###
if (scalar keys %mac != 2) {
	print "A z440 Workstation should only have 2 network devices, but ". scalar keys(%mac) . " devices were found.\n";
}
# There should only be two network devices eno1 and another one
if (exists $mac{'eno1'}) {
	delete($mac{'eno1'});
} else {
	print "$program aborted: Ethernet device eno1 does not exist, but should be present!\n";
	exit 0;
}

foreach my $dev (keys %mac) {
	if($dev !~ /^enp.s./ ) {
		print "Ethernet device $dev has a different name as expected (enpXsX)\n";
		setMacAdress($mac{$dev});
		last;
	}
}

exit;

###################
##               ##
##  Subroutines  ##
##               ##
###################
sub setMacAdress($) {
	my $address = shift;
    chomp $address;
	my $uuid = `uuidgen`;
	chomp($uuid); 
    open(IFCFG, ">>$netcfg-ens1" ) or die "Cannot open $netcfg-ehs1: $!";
    print IFCFG 'UUID="',$uuid,'"',"\n";
	print IFCFG 'HWADDR="',$address,'"',"\n";
	close(IFCFG);
	$netcfg
}

sub get_os_version
{
    my $querycmd = 'rpm -qf --queryformat %{Name} /etc/redhat-release';
    my $redhat = `$querycmd`;
    
    chomp $redhat;
    $querycmd = 'rpm -q --queryformat %{version} ' . $redhat;
    
    my $redhat_release = `$querycmd`;
    
    my $rh_release = (int $redhat_release);
    return $rh_release;
}

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

openlog('bruker-setup', 'nofatal,pid', 'user') if $syslog;


closelog  if $syslog;

exit;


__END__

=head1 NAME

assign-default-networks - Assign MAC and UUID to ifcfg-ens1 of the second network device

=head1 SYNOPSIS

assign-network-devices [options]

Options:

     -help            brief help message
     -man             prints the manual page
     -verbose         create verbose output

=head1 OPTIONS

=over 8

=item B<-help>

    Print a brief help message and exits.

=item B<-man>

    Prints the manual page and exits.


=item B<-verbose>

    Print additional debug information

=back


=head1 DESCRIPTION

assign-default-networks - Assign MAC and UUID to ifcfg-ens1 of the second network device
 
This script is required during system boot by the service bruker-setup
to assing the MAC addresse in ifcfg-ens1. It assumes that eno1 device is used on the motherboard, which 
should be connected to the spectrometer. The other device is therfore set to ens1.

=cut

