#!/usr/bin/perl -w

# created by ml 9.12.2009 (c) IPB GmbH


use DBI;
use Getopt::Long;
&Getopt::Long::config('bundling');

$file = "vif_uuids";


## MySQL

my $database = "yourdatabase";
my $hostname = "yourhostnameorip";
my $user = "youdbuser"; 
my $pass = "yourdbpassword";

$DataHandle         =   DBI->connect("DBI:mysql:database=$database;host=$hostname",
                                     "$user",
                                     "$pass",
                                     { RaiseError => 1,
                                       AutoCommit => 0 }) || die "Unable to connect to $host because $DBI::errstr";



my $status = GetOptions(
	"h|help"           => \$opt_h,
	"v|vlan"	   => \$vlan, 	 
	"H|xenhost=s"	   => \$host
	);

#print "Host : $host\n";

if ($opt_h) {
        print_usage();
}

if ( !$host ) {
	print_usage();
}



@command= `xenstore-list /vm`;

$command= 'brctl show | awk \'{ if($i ~ /xapi/ || $i ~ /xenbr/)   { print $1 "\n" $4 } else {print $1 } }\' | grep -v bridge';
$result =`$command`;
chop($result);


%xapi_vifs =();
%vlan = ();


@array= split("\n",$result);


foreach (@array) {
        if ($_ =~ m/(xapi\d+)/) {
                $tmp2 = "";
                $tmp = $1;
                }

        elsif ($_ =~ m/(xenbr\d+)/) {
                $tmp2 = "";
                $tmp = $1;
                }

        else { $tmp2 = $_;
        $xapi_vifs{$tmp2} = $tmp;}

}


if ($vlan) {

	foreach (@array) {
		if ($_ =~ m/(xapi\d+)/) {
                	$tmp2 = "";
                	$tmp = $1;
                	}

		elsif ($_ =~ m/eth\d+\.(\d+)/) {
			$vlan{$tmp} = $1;
		}
	}
}

else {
        %vlan = (
        xenbr0 =>       '88',
        xenbr1 =>       '777',
        xenbr2 =>       '987',
        xenbr3 =>       '487'
        );      }


#while ( my ($key, $value) = each(%vlan) ) {
#	print "Key $key : Value ${value}##\n";
#}

	
# remove vifx.x if exist tapx.x

while ( my ($key, $value) = each(%xapi_vifs) ) {
	if ($key =~ m/tap(\d+\.\d+)/g) {
		$vif_tmp = "vif".$1;
		delete $xapi_vifs{$vif_tmp};
	}
}


foreach $item (@command) {
	$item =~ s/\s*//g;
	$dom = `xenstore-read /vm/${item}/name`;
	$dom =~ s/Domain-//g;
	$dom =~ s/\s*//g;
	@interfaces = `xe vif-list vm-uuid=$item | grep device | cut -d : -f 2`;

	@name_label = `xe vm-list uuid=$item | grep name-label | cut -d ":" -f2`;
	
	foreach(@interfaces) {
		foreach $name (@name_label) {
		$name =~ s/\s*//g;
		$_ =~ s/\s*//g;
	#	$interfaces .= ";$dom.$_";
		##check ifname 
		while ( my ($key, $value) = each(%xapi_vifs) ) {
			next if (! $vlan{$value});
        		if ($key =~ /tap$dom.$_/g) {
				$value =~ s/\s*//g;
                		$interfaces = "$key";
				$vlan = $vlan{$value};
				db_handle($item,$dom,$interfaces,$vlan,$name,$host);
				$output .= "NULL;$item;$dom;$interfaces;$vlan;$name;$host\n";
            		}
			

        		elsif ($key =~ /vif$dom.$_/g) {
				$value =~ s/\s*//g;
                		$interfaces = "$key";
				$vlan = $vlan{$value};
				db_handle($item,$dom,$interfaces,$vlan,$name,$host);
                                $output .= "NULL;$item;$dom;$interfaces;$vlan;$name;$host\n";
			}
		}

	}
   }
	@interfaces = "";
	$interfaces = "";
	
}

sub db_handle {
	my ($vm_uuid, $dom, $iface_descr, $vlantag, $vm_label, $dom0) = @_;
	#print "$vm_uuid, $dom, $iface_descr, $vlantag, $vm_label, $dom0\n";

	$sql = "SELECT id FROM if_xen WHERE uuid = '$vm_uuid' AND  vlan  = '$vlantag'";
	#print "$sql\n";
	$sth = $DataHandle->prepare($sql);
	$sth->execute();
	@result = $sth->fetchrow_array();
	$sth->finish();

	if (!$result[0]) {
		$DataHandle->do("INSERT INTO if_xen values(NULL,'$vm_uuid','$dom','$iface_descr','$vlantag','$vm_label','$dom0')");
		}
	else {
		chomp($result[0]);	
		$DataHandle->do("UPDATE  if_xen set domid='$dom',if_desc='$iface_descr',vlan='$vlantag',vm_name='$vm_label',wirt='$dom0' WHERE uuid='$vm_uuid' AND vlan='$vlantag'");
		}

	}


$DataHandle->disconnect();

sub print_usage {
	print <<EOU;

    Author: Martin Leucht IPB GmbH	

    Usage: get_vif_xen.pl -H xenhost [-v] [-h]


    Options:

    -H --xenhost STRING or IPADDRESS
        Check vif on the indicated host
    -h --help	Print this help
    -v --vlan   enable VLAN mode

EOU
	exit (0);
}

open(FILE, ">$file") || die "Can not open file $file\n";
print FILE "$output";
close(FILE)

