#!/usr/bin/perl
# IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html
#-------------------------------------------------------

=head1	mkzvmnodes
	
	Description	: This is a script to make definitions for z/VM nodes
    Arguments	: 	mkzvmnodes < Node range > 
    				userid=< UserID range > 
    				ip= <IP address range > 
    				hcp=< Hardware control point > 
    				groups=< Group >
    Returns		: Nothing
    Example		: mkzvmnodes gpok140+9 userid=LINUX140+9 ip=9.60.18.140+9 hcp=gpok456.endicott.ibm.com groups=all
    

=cut

#-------------------------------------------------------
use strict;
use warnings;

# This script makes the following commands for each node in the range:
# mkdef -t node -o gpok123 userid=linux123 ip=9.60.18.123 hcp=gpok456.endicott.ibm.com mgt=zvm groups=all

# Get node range
my $nodeRange = $ARGV[0];

# Get inputs
# Hash array containing arguments
my %args;
my @parms;
my $i;
foreach $i ( 1 .. $#ARGV ) {
	@parms = split( "=", $ARGV[$i] );
	$args{ $parms[0] } = $parms[1];
}

# --- Generate nodes ---
my @nodes;
@parms = split( /\+/, $nodeRange );
my $topNo = $parms[1];

# Get non digits from string
$parms[0] =~ m/(\D+)/;
my $baseStr = $1;

# Get digits from string
$parms[0] =~ m/(\d+)/;
my $baseNo = $1;

my $no;
my $node;
foreach $i ( 0 .. $topNo ) {

	# Node + 1
	$no   = $baseNo + $i;
	$node = $baseStr . $no;
	push( @nodes, $node );
}

# --- Generate user IDs ---
my @userIDs;
@parms = split( /\+/, $args{"userid"} );
$topNo = $parms[1];

# Get non digits from string
$parms[0] =~ m/(\D+)/;
$baseStr = $1;

# Get digits from string
$parms[0] =~ m/(\d+)/;
$baseNo = $1;

my $userID;
foreach $i ( 0 .. $topNo ) {

	# UserID + 1
	$no     = $baseNo + $i;
	$userID = $baseStr . $no;
	push( @userIDs, $userID );
}

# --- Generate IP addresses ---
# Only IPv4 supported
my @ips;
@parms = split( /\+/, $args{"ip"} );
$topNo = $parms[1];

# Get non digits from string
@parms   = split( /\./, $parms[0] );
$baseStr = $parms[0] . "." . $parms[1] . "." . $parms[2] . ".";

# Get digits from string
$baseNo = $parms[3];

my $ip;
foreach $i ( 0 .. $topNo ) {

	# IP address + 1
	$no = $baseNo + $i;
	$ip = $baseStr . $no;
	push( @ips, $ip );
}

# Check if # of nodes = # of user IDs
if ( @nodes != @userIDs || @nodes != @ips ) {
	print "Error: Number of nodes != Number of user IDs or Number of IP addresses\n";
	exit(0);
}

# --- Generate and execute command ---
$i = 0;
my $cmd;
my @cmds;
my $out;

foreach (@nodes) {
	$cmd = "mkdef -t node -o $_ userid=$userIDs[$i] ip=$ips[$i] hcp=$args{'hcp'} mgt=zvm groups=$args{'groups'}";
	$out = `$cmd`;
	print "$_: Done\n";
	$i++;
	push( @cmds, $cmd );
}

