#!/usr/bin/env python
# -*- coding: utf-8 -*-
# For AIX

# For AIX
# Imports# {{{

import argparse, textwrap
import os, errno
import collections
import subprocess
import re
import inspect
import logging
import sys
import shutil
import json
import socket
import platform
import datetime
import fileinput
import time


# Needed for the chk_initialization file: 
# if __name__ == '__main__':
sys.path.append("/usr/local/rootbin/Pythonlib/")
import amdisplay
import am_premig

import am_aix_user
import am_aix_lvm


main_rc = 0

# }}}
#  Info#{{{
# ----------------------------------------------------------------------------
#
# NAME:         migratevm.py
#
# Purpose:      
#
# Parameter:    see -h
#
# ----------------------------------------------------------------------------
#
# Author:       aldo@metrosystems.net
#
# Date:    27.04.2018  
#
# Disclaimer:   This program should be used for reference only. It has not been
#               submitted to any formal test and is distributed AS IS.
#
# ----------------------------------------------------------------------------
#
# Needed customization in case of porting this Script to other machines:
#
# ----------------------------------------------------------------------------
#
# Well known Bugs:
#               none, it is perfect ;-)
#
# ----------------------------------------------------------------------------
#
#  27.04.2018 v 1.00/history:
#    27.04.2018 v 1.0.0/Fist version
#    05.11.2018 v 1.0.1 # 
#      Updated the Shared Storage Pools from 0 to 1
#    12.11.2018 Updated the get_lpar_id()function
# 
# ----------------------------------------------------------------------------
#
# ToDo:         Further tasks
#
# ----------------------------------------------------------------------------
#
#}}}


# Global Variable

eth_slot_a=2
eth_slot_b=3
eth_slot_c=4

root_vg_slot_a=5    # Used for VIOS_A Logical Unit
root_vg_slot_b=6    # used for VIOS_B Logical Unit

data_vg1_slot_a=7
data_vg1_slot_b=9

data_vg2_slot_a=8
data_vg2_slot_b=10

datavg1_fcs = "fcs5"   # The physical fc port for datavg1
datavg2_fcs = "fcs7"   # The physical fc port for datavg2

resolv_conf_name="resolvconf"   # NIM: Hard coded, internal review required


# Initial parser
## Parser: I'm using ArgumentParser for this solution: # {{{

def check_positive(value):# {{{
    try:
       ivalue = int(value)
    except Exception as e:
       raise argparse.ArgumentTypeError( "%s: Please enter an integer" %value)
    if ivalue <= 0:
         raise argparse.ArgumentTypeError("%s Are you sure you want to look into the future ?\n\
               Please enter a positive integer" % value)
    return ivalue
# }}}

parser = argparse.ArgumentParser(
        description= "LPAR migration from one Managed System to another\n \
              e.g. Migrate an LPAR:\
  migratevm.py -s s303en0 -S S8 -D S04 -H lxsrvmgi0001 \n \
              e.g. Check if mksys is up to date:\
  migratevm.py -s s303en0  -c mk \n \
              e.g. Collect live_node_conf , live_wwns_conf data from s303en0\
  migratevm.py -q -1 s303en0 " ,
        formatter_class=argparse.RawTextHelpFormatter
        )

#              e.g. Collect live_node_conf , live_wwns_conf data from s303en0\
#  migratevm.py -q -1 s303en0 " 

# Adding the action mutually exclusive groups
action_group = parser.add_argument_group()


action_group.add_argument("-S","--source_managed_system",
        action="store",
        help="The name of the source Managed System: e.g. S8")




action_group.add_argument("-l","--list",
        action="store_true",
        help="list")


action_group.add_argument("-L","--longlist",
        action="store_true",
        help="dev: to implement the logging module , "\
              "same as -lv")

action_group.add_argument("-C","--SOURCE_CSM",
        action="store",
        help="SOURCE CSM: the hostname of the source CMS:.e.g aix00p04")


action_group.add_argument("-a","--mksysb_age",
        action="store",
        type=check_positive,
        help="Specifies the max mksysb age in days. Default=3")



action_group.add_argument("-t","--type",
        type=str,
        nargs='?',
        const="nono",
        choices=["sap","todoN"],
         help= textwrap.dedent('''\n\
sap:        Cluster type=sap
ms:         Check the Managed System
nim:        Check if NIM master is properly configured
hmc:        Check if the HMC is reachable:
wwn_file:   Check if the wwwn_file exists and if its content matches the \
lpar WWN configuration
ame:        Check if AME is configured on the target LPAR:
node_conf_file:    Check if node_conf_file is in place and valid: 
node_firstboot_file:    Check if node_first_boot is in place and valid: \n
        '''))






action_group.add_argument("-z","--test",
        action="store_true",
        help="Test various functions")

action_group.add_argument("-r","--restore_type",
        type=str,
        nargs='?',
        const="fixall",
        choices=["unattended","sms"],
         help= textwrap.dedent('''\n\
unattended: do a full unattended migration : default
console:    do a lpar netboot and let me take over the console\n \n'''))




action_group.add_argument("-T","--test2",
        action="store_true",
        help="Test various functions")


check_group=parser.add_mutually_exclusive_group()
check_group.add_argument("-c","--check",
        type=str,
        nargs='?',
        const="fixall",
        choices=["mksysb","ms","nim","hmc","wwn_file","node_conf_file", "ame"],
         help= textwrap.dedent('''\n\
mksysb:     Check if mksysb exists and it is newer than 3 days:
ms:         Check the Managed System
nim:        Check if NIM master is properly configured
hmc:        Check if the HMC is reachable:
wwn_file:   Check if the wwwn_file exists and if its content matches the \
lpar WWN configuration
ame:        Check if AME is configured on the target LPAR:
node_conf_file:    Check if node_conf_file is in place and valid: 
node_firstboot_file:    Check if node_first_boot is in place and valid: \n
        '''))


# Adding the required parameters
required_group=parser.add_argument_group("Required arguments")
required_group.add_argument("-s","--source_lpar",
        action="store",
        help="the name of the source lpar. e.g. s303en0",
        required=True)

required_group.add_argument("-D","--destination_managed_system",
        action="store",
        help="The name of the destination Managed System: e.g. S04",
        required=True)


required_group.add_argument("-H","--hmc",
        action="store",
        help="The name of the HMC used: e.g.:lxsrvhmc0001", 
        required=True)





# Adding the -v/-q mutually exclusive group
verbose_group=parser.add_mutually_exclusive_group()
verbose_group.add_argument("-v","--verbose",
        action="count",
        help="Show what is going on")



# Adding the -q for specific stages
stages_group=parser.add_mutually_exclusive_group()
stages_group.add_argument("-q","--stage",
        type=int,
        nargs='?',
        const="fixall",
        choices=[-7,-6,-5,-4,-1,1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11,12],
         help= textwrap.dedent('''\n\
-7 perform prompted installation e.g. OK PROMPT
-6 perform nim operations:  deallocate NIM resources
-5 perform nim operations:  remove NIM resources
-4 perform LPAR deactivation: e.g. shutdown the lpar 
-1 dev:collect live_node_conf and live_wwns_conf file: The lpar must be UP 
        This action (-1) is needed if AME or DATAVG, DBVG have been migrated
        Please collect this data before the maintenance window
1    perform  infrastructure prerequisites
2    perform  premigration operations e.g. mksysb processing, fb, ini, vlan
3    perform  hmc  operations e.g. define target lpar
4    perform  LPAR activation e.g. bring the lpar into open firmware state
5    perform  nim  operations:  define NIM resources
6    perform  nim  operations:  allocate NIM resources
7    perform unattended installation e.g. lpar netboot using bosinst.data
8    dev:perform post installation actions e.g. import user defined VGs
9    dev:perform post migration actions: e.g networking, vgs, /etc/nostart  
10   dev:perform post migration checks e.g. adjust lpar properties if necessary 
11   my_test: do all
12   my_test: devel_tests
       \n '''))



# Adding the -f/--force group
force_group=parser.add_mutually_exclusive_group()
force_group.add_argument("-F","--FORCE",
        action="store_true",
        help="Force a specific operation")



# Parsing all the arguments
args=parser.parse_args()

# }}}


## Display module initialization 
amd=amdisplay.AmDisplay()

## Global variables: # {{{

amux = am_aix_user.am_aix_user()    # AIX User operations

# }}}
# CLASSES# {{{
class amgi():# AIX Metro  # {{{
    """AIX Metro class\
        Used to retrieve lpar info such as: 
            Funktion:
            Criticality"""
    
    # Class Variables: 
    MGI_FILE="/etc/mgi_config"
    STATUS_TYPE=["Production","Unused", "prod","preprod","dev","development"]
    ENV_TYPE_LIST=["Prod",
         "PreProd",
         "Dev",
         "QA",
         "Offline"]

# }}}

    def __init__(self,verbose=False):# {{{
        """docstring for __init__"""
        self.verbose=verbose
    # }}}
    def is_MGI_FILE(self,local_verbose=False): # Return : True of False# {{{
        """Checking if the MGI_FILE is present on the system\
            It will generate an error message if file is not found\
            It will return: True or False"""
        self.local_verbose=local_verbose

        if self.local_verbose:
            ok_msg("Checking if /etc/mgi_file exists.")

        if not os.path.isfile(self.MGI_FILE):
            err_msg("The /etc/mgi_config file does not exist.",\
                    emsg_var=False,\
                    call_admins=[False,False],\
                    local_exit=True)
        else:
            return os.path.isfile(self.MGI_FILE)
    # }}}
    def get_status(self):# returns str: status{{{
        """Retrieving the Funktion name from the /etc/mgi_file"""
        # Checking if mgi_file exists:
        is_mgi_file=self.is_MGI_FILE()
        try:
            file = open(self.MGI_FILE)
        except Exception as e:
            raise e
        else:
            is_status_line=False
            for line in file:
                if "Status" in line:
                    # print line
                    is_status_line=True
                    break

            if is_status_line:
                #print "Parsing the Status line to extract the env type"
                for env in self.STATUS_TYPE:
                    if env in line:
                        status = env
                        break
                    else:
                        status = "undefined"
            file.close()
        return status 
    # }}}
    def get_funktion(self):# returns str: Funktion: line{{{
        """Retrieving the Funktion line from the /etc/mgi_file
           e.g: MMS-Store MCC France Prod VI """
                
        # Checking if mgi_file exists:
        is_mgi_file=self.is_MGI_FILE()
        try:
            file = open(self.MGI_FILE)
        except Exception as e:
            raise e
        else:
        
            funktion_line=False
            for line in file:
                if "Funktion" in line:
                    # print line
                    funktion_line=line
                    break

            file.close()
        return funktion_line
    # }}}
    def get_env_type(self):# returns str: env_type .e.g prod{{{
       """Retrieve the env_type of a server .e.g prod
       from the funktion line: get_funktion()
       e.g: Prod, PreProd, Dev"""

       # Rertrieving the Funcktion line
       funktion_line = self.get_funktion()

       env_type = "offline"
       for env_type in self.ENV_TYPE_LIST:
           p = re.compile(r'\b{}\b'.format(env_type),re.IGNORECASE)
           m = p.search(funktion_line)
           if m:
              env_type = env_type
              return env_type
              break

       return env_type


    # }}}
    def get_iron(self):# returns str: Blech e.g I4: {{{
        """Retrieving the Managed System from /etc/mgi_config
           e.g: I4"""
                
        # Checking if mgi_file exists:
        is_mgi_file=self.is_MGI_FILE()
        
        try:
            file = open(self.MGI_FILE)
        except Exception as e:
            raise e
        else:
        
            Iron=False
            for line in file:
                if "Blech" in line:
                    # print line
                    Blech_line=line
                    # Retrieving the Blech: e.g. I4
                    Iron=Blech_line.split()[1].strip()
                    break
            file.close()

        return Iron 
    # }}}

    def get_service_hostname(self):# returns str: service_hostname e.g i133serv: {{{
        """Retrieving the service hostname from /etc/mgi_config
           e.g: i33serv"""
                
        # Checking if mgi_file exists:
        is_mgi_file=self.is_MGI_FILE()
        
        try:
            file = open(self.MGI_FILE)
        except Exception as e:
            raise e
        else:
        
            service_line=False
            for line in file:
                if "Service" in line:
                    # print line
                    service_line=line
                    # Retrieving the service hostname: e.g. i133serv
                    service_hostname=service_line.split()[1].strip()
                    break
            file.close()

        return service_hostname
    # }}}
    def get_service_IP(self,quit=False):# returns str (IP): service_IP e.g i133serv: {{{
        """Retrieving service_IP address associate with the service_hostname
           e.g: i33serv"""
                
        # Retrieving the service_hostname by calling get_service_hostname()
        service_hostname=self.get_service_hostname()
        
        # Retrieving the service_IP address:
        try:
            service_IP = socket.gethostbyname(service_hostname)
            return service_IP
        except Exception as e:
            err_msg("Unable to retrieve the service IP address.")
            raise e

    # }}}
    def get_service_fqdn(self,quit=False):# returns service fqdn or FALSE: {{{
        """Retrieving the service fqdn based on the  service_IP address
           e.g: i33serv"""
                
        # Retrieving the service_hostname by calling get_service_hostname()
        service_IP=self.get_service_IP()
        service_hostname =  False       # Assuming It cannot be retrieved\
                                        # a check is needed 
        
        unix_cmd = ("nslookup "\
               "-timeout=5 "\
               "{}"\
               ).format(service_IP) 
#         print ("Unix_cmd is: {} : ").format(unix_cmd) # FOR TESTING

        p = subprocess.Popen(unix_cmd,\
                shell=True, stdout=subprocess.PIPE,\
                stderr=subprocess.STDOUT)
        rc = p.wait()
        output_list=p.stdout.readlines()
        

        if self.verbose == 2:
            print "# unix_cmd is :{}".format(unix_cmd)     ##-- FOR_TESTING --##

        if rc!=0:           
            # unix_cmd has failed
            if self.verbose:
                err_msg("Unable to retrieve the service fqdn.\n"\
                        "    Please ensure that it is properly configured\n"\
                        "    e.g. i333serv.metro-dus.de", \
                        call_admins=[False,False])
            return service_hostname

        elif rc==0:         
            # unix_cmd executed successfully  
            # Parsing the output to retrieve the hostname line
            # 95.52.243.10.in-addr.arpa       name = i333serv.metro-dus.de.

            for i in output_list:
                if "name" in i:
                    return i.split("=")[1].strip()[:-1]

        # }}}
    def get_omd_criticality(self): # Compiling the OMD criticality  {{{
        """Determining  the OMD criticality based on the environment type
        generated by the get_env_type method. There are 4 OMD criticality
        fields: [prod, qa, test, offline]. They are matched as follows: 
        OMD     env_type
        prod    prod, production
        qa      preproduction
        test    dev
        offline offline
        "id": "criticality",
                "values": [
                    "Prod",
                    "PP",
                    "QA",
                    "Dev",
                    "Offline"
 
        """


        # Determining the env_type:
        env_type = self.get_env_type()

        # Determining criticality based on env_type
        criticality = "Offline"     # Assuming offline 
        if env_type == "Prod" or env_type == "production":
            criticality = "Prod"
            return criticality
        elif env_type == "PreProd" or env_type == "preproduction":
            criticality = "PP"
            return criticality
        elif env_type == "QA":
            criticality = env_type
            return criticality
        elif env_type == "Dev" or env_type == "Development":
            criticality = "Dev"
            return criticality
        else:
            return criticality

        # }}}



# TODO# {{{
# get_iron
# get_domain
# get_PscNumber
# }}}




# }}}

# FUNCTIONS
   # PREPARE THE ENVIRONMENT


# COLLECT configuration file
# TODO,
def is_source_csm_accesible(host,user="root", verbose=False, silent=False, quit=False ): # {{{
    """Checking if a host is accessible over ssh"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    is_ssh_accesible(host,
            user,
            verbose=args.verbose,
            quit=True)

# }}}
##def is_source_lpar_dsh_accesible(source_csm, client_name, verbose=False, silent=False, quit=False ): # {{{
##    """Checking if a host is accessible over dsh"""
##
##    unix_cmd=dsh -n host "hostname"
##
##    if verbose >= 2:
##       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])
##
##    opt1="hostnamne"
##
##
##
############################
##    user = "root"
##    opt1="dsh -n {} \"hostname\"".format(host)
##    opt2=" -m {} {} default {}".format(mac, client_name, ms)
##
##    unix_cmd=("ssh "\
##            "{}"\
##            "@{} "\
##            "{}"\
##            " {}"\
##            ).format(user,c, opt1, opt2)
##
##
##
##
##
##
##
##    unix_cmd=("/usr/bin/dsh -n"\
##            "{} "\
##            " {}"
##            ).format(host, opt1)
##    
##    if verbose >= 2 and not silent:
##        amd.info_msg("  unix_cmd is: ", unix_cmd)
##    
##    p = subprocess.Popen(unix_cmd,\
##            shell=True, stdout=subprocess.PIPE,\
##            stderr=subprocess.STDOUT)
##    rc = p.wait()
##    
##    
##        # Unix_cmd has failed
##    if rc!=0:
##        if quit:
##           amd.err_msg("Unable to access source lpar over dsh",
##               exit_code=13)
##        else:
##           amd.err_msg("Unable to access source lpar over dsh")
##        return False
##    
##        # Unix_cmd executed successfully
##    elif rc==0:
##       if verbose >= 1 and not silent:
##           amd.ok_msg("   >>" The client can be accessed over dsh" )
##       return True
## 
##
### }}}


def get_node_conf_from_source(s_csm, client_name, verbose=False, quit=False, silent=False, force=False, prereq=False):# {{{

    """Collecting node_conf from the lpar
    This function leverages the get_nodeconf.pl 
    located on the /usr/local/rootbin/LPAR on the LPAR
    Because I can't use a general user to connect directly to the lpar, 
    CMS is going to be used to run this scrop throug dsh
    :s_csm: source csm hosname
    :s_ms: source manages server: not really needed

    :client_name The name of the lpar
    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :force:     force an operation if TRUE
    :prereq:   do infrastructure prerequisites if necessary
    :returns:   bool

     UNIX_CMD: 
     ssh root@s_csm dsh -n client_name /usr/local/rootbin/LPAR/get_nodeconf.pl
     ssh root@s_csm scp root@client_name:/space/node_conf_client_name /csmimages/

     lpar_netboot -T off -d auto -s auto -t ent -m 826FDE2EB302 s370en0 default S04 """

    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Starting to collect the node_conf file")

        

    # Unix_cmd
    user = "root"
    opt1="dsh -n {} \"/usr/local/rootbin/LPAR/get_nodeconf.pl\"".format(client_name)
    opt2="; scp {}@{}:/space/node_conf_{} /csmimages/".format(user, client_name, client_name)

    unix_cmd=("ssh "\
            "{}"\
            "@{} "\
            "{}"\
            " {}"\
            ).format(user, s_csm, opt1, opt2)
    
    
    if verbose >= 2 and not silent:
        amd.info_msg("  unix_cmd is: ", unix_cmd)
    
#    p = subprocess.Popen(unix_cmd,\
#            shell=True, stdout=subprocess.PIPE,\
#            stderr=subprocess.STDOUT)
#    rc = p.wait()
#    
#    
#        # Unix_cmd has failed
#    if rc:
#        if quit:
#           amd.err_msg("Unable to perform the unattended installation",
#               exit_code=13)
#       else:
#           if verbose >= 1 and not silent:
#               amd.ok_msg("   >>The unattended installation has been started")
#           return False
#
#        # Unix_cmd executed successfully
#    else:
#       if verbose >= 1 and not silent:
#           amd.ok_msg("   >>node_conf has been copied to the source CSM")
#       return True
   
# }}}


# NODE PREREQ
def is_node_in_host_conf(client_name):# {{{
    """Checking if node in in resolv.conf

    :client_name: The name of the client
    :returns: bool

    """
    is_client_host_conf=False

    local_file="/etc/hosts"
    with open(local_file,'r') as f:
        # Read file line by line: 
        lines = f.readlines()
        # Print lines or do something else
        for line in lines:
            if line.startswith("#"):
                pass
            else:
                if client_name in line:
                    is_client_host_conf=True
                    break
    
    f.close()
    return is_client_host_conf
# }}}

# FILE CONFIGURATION PROCESSING
    # node_conf
def get_node_conf_path(): # {{{
    """Returns the path of the node_conf file e.g node_conf_s248en0"""
    node_conf_path ="/csmimages/node_conf_" + str.strip(args.source_lpar)
    return node_conf_path
   
# }}}
def is_node_conf_file(node_conf_path, verbose=False, silent=False, quit=False):# {{{
    """Checking if the node_conf_$node file exist
    - The default path of the file is /csmimages
    - This function does a very simple file check
    usage: is_node_conf_file(get_node_conf_path())"""
    if os.path.isfile(node_conf_path):
        if verbose and not silent:
            amd.ok_msg("   >> File is in place:",
                    node_conf_path)
        return True
    else:
        if quit:
            amd.err_msg("   >> Inexistelt file:",
                    get_node_conf_path(),
                    exit_code=16)
        else:
            return False
# }}}
def is_valid_node_conf_file(node_conf_path, verbose=False, silent=False, quit=False ): # {{{
    """Checking if the node_conf_$node file is valid"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])
           
    # checking if file exists, exit otherwise
    node_conf_path=get_node_conf_path()
    is_node_conf_file(node_conf_path,
            verbose=args.verbose,
            silent=True,
            quit=True)

    # Start the validation process
    if verbose and not silent:
        amd.ok_msg("   >> Starting the validity check for:",
                node_conf_path)

    with open(node_conf_path,'r') as f:
       # Read file line by line: 
       invalid=False
       lines = f.readlines()
       for line in lines:
           if not line.startswith("#"):
              if not line.isspace():
                 if "%CONFIG"  not in line:
                    if ");"  not in line:
                        if not "=>" in line:
                            invalid=True
                            if verbose >= 1 and not silent:
                                amd.err_msg("Invalid lines:", str.strip(line))
    f.close()

    if invalid:
        if quit:
           amd.err_msg("Invalid node_conf file:",
           node_conf_path,
           exit_code=17)
        else:
           amd.err_msg("Invalid node_conf file:", node_conf_path)

           return False
    else:
        if verbose >= 1 and not silent:
           amd.ok_msg("   >> Configuration file is valid:", node_conf_path)



# }}}
def get_node_conf_options_dic(node_conf_path, verbose=False, silent=False, quit=False ): # {{{
    """Extracting the option:value from node_conf -> dictionary"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])
       
    # checking if file exists, exit otherwise
    node_conf_path=get_node_conf_path()
    is_node_conf_file(node_conf_path,
            verbose=args.verbose,
            silent=True,
            quit=True)

    # checking if file is valid, exit otherwise
    if not silent:
       is_valid_node_conf_file(node_conf_path,
           verbose=args.verbose,
           quit=True)


    # Start extraction options:
    if verbose and not silent:
        amd.ok_msg("   >> Parsing LPAR options from:",
                node_conf_path)




    with open(node_conf_path,'r') as f:
       # Read file line by line: 
       local_error=False
       node_conf_dic={}
       lines = f.readlines()
       for line in lines:
           if not line.startswith("#"):
              if not line.isspace():
                 if "%CONFIG"  not in line:
                    if ");"  not in line:
                        # Stripping "'" and "," from line
                        new_line=(line.replace("'","").replace(",","")).strip()
                        (option,value) = new_line.split("=>")
                        node_conf_dic[option.strip()] = value.strip()
    f.close()




    if verbose >= 1 and not silent:
        amd.ok_msg("   >> Compiled node_conf option:value dictionary" )

    return  node_conf_dic


# }}}
def get_node_conf_string(verbose=False, silent=False, quit=False ): # {{{
    """Extracting the configuration string for the lpar profile
    one should append specific options to this string when configuring 
    the lpar -> string"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    # Start extraction options:
    if verbose and not silent:
        amd.ok_msg("   >> Compiling the node_conf string:")


    node_conf_string=""
    node_conf_dic=get_node_conf_options_dic(get_node_conf_path(),
            verbose=args.verbose, 
            quit=True)

    node_conf_string +="min_mem={}".format(node_conf_dic['LPAR_MEM_MIN'])+",";
    node_conf_string +="desired_mem={}".format(node_conf_dic['LPAR_MEM_DES'])+",";
    node_conf_string +="max_mem={}".format(node_conf_dic['LPAR_MEM_MAX'])+",";
    node_conf_string +="proc_mode={}".format(node_conf_dic['LPAR_PROC_MODE'])+",";
    node_conf_string +="min_proc_units={}".format(node_conf_dic['LPAR_PROC_UNITS_MIN'])+",";
    node_conf_string +="desired_proc_units={}".format(node_conf_dic['LPAR_PROC_UNITS_DES'])+",";
    node_conf_string +="max_proc_units={}".format(node_conf_dic['LPAR_PROC_UNITS_MAX'])+",";
    node_conf_string +="min_procs={}".format(node_conf_dic['LPAR_PROC_MIN'])+",";
    node_conf_string +="desired_procs={}".format(node_conf_dic['LPAR_PROC_DES'])+",";
    node_conf_string +="max_procs={}".format(node_conf_dic['LPAR_PROC_MAX'])+",";
    node_conf_string +="sharing_mode={}".format(node_conf_dic['LPAR_SHARING_MODE'])+",";

    if verbose >= 1 and not silent:
        amd.ok_msg("   >> Compiled the the node_conf string" )
    if verbose >= 3 and not silent:
        amd.ok_msg("   >> node_conf string:",
                node_conf_string)
    return  node_conf_string


# }}}
    # wwws_conf
def get_wwns_conf_path(): # {{{
    """Returns the path of the wwns_conf file e.g node_wwns_s248en0"""
    wwns_conf_path ="/csmimages/node_wwns_" + str.strip(args.source_lpar)
    return wwns_conf_path
   
# }}}
def is_wwns_conf_file(wwns_conf_path,verbose=False, silent=False, quit=False):# {{{
    """Checking if the node_wwns_$node file exist
    - The default path of the file is /csmimages
    - This function does a very simple file check
    usage: is_wwns_conf_file(get_wwns_conf_path())"""
    if os.path.isfile(wwns_conf_path):
        if verbose and not silent:
            amd.ok_msg("   >> File is in place:",
                    wwns_conf_path)
        return True
    else:
        if quit:
            amd.err_msg("   >> Inexistent file:",
                    get_wwns_conf_path(),
                    exit_code=16)
        else:
            return False
# }}}
def is_valid_wwns_conf_file(wwns_conf_path, verbose=False, silent=False, quit=False ): # {{{
    """Checking if the wwns_conf_$node file is valid"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])
      
    wwns_conf_path = get_wwns_conf_path()
    # checking if file exists, exit otherwise
    is_wwns_conf_file(wwns_conf_path,
            verbose=args.verbose,
            silent=True,
            quit=True)

    # Start the validation process
    if verbose and not silent:
        amd.ok_msg("   >> Starting the validity check for:",
                wwns_conf_path)


    with open(wwns_conf_path,'r') as f:
       # Read file line by line: 
       invalid=False
       lines = f.readlines()
       for line in lines:
           if not line.startswith("#"):
              if not line.isspace():
                 if "%WWNS"  not in line:
                    if ");"  not in line:
                        if not "=>" in line:
                            invalid=True
                            if verbose >= 1 and not silent:
                                amd.err_msg("Invalid lines:", str.strip(line))
    f.close()

    if invalid:
        if quit:
           amd.err_msg("Invalid wwns_conf file:",
           wwns_conf_path,
           exit_code=17)
        else:
           amd.err_msg("Invalid wwns_conf file:", node_conf_path)

           return False
    else:
        if verbose >= 1 and not silent:
           amd.ok_msg("   >> Configuration file is valid:", wwns_conf_path)



# }}}
def get_wwns_conf_options_dic(wwns_conf_path, verbose=False, silent=False, quit=False ): # {{{
    """Extracting the option:value from wwns_conf -> dictionary"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])
       
    # checking if file exists, exit otherwise
    wwns_conf_path=get_wwns_conf_path()
    is_wwns_conf_file(wwns_conf_path,
            verbose=verbose,
            silent=True,
            quit=True)

    # checking if file is valid, exit otherwise
    is_valid_wwns_conf_file(wwns_conf_path,
        verbose=verbose,
        quit=True)


    # Start extraction options:
    if verbose and not silent:
        amd.ok_msg("   >> Parsing LPAR options from:",
                wwns_conf_path)


    with open(wwns_conf_path,'r') as f:
       # Read file line by line: 
       local_error=False
       wwns_conf_dic={}
       lines = f.readlines()
       for line in lines:
         if not line.startswith("#"):
           if not line.isspace():
             if "%WWNS"  not in line:
               if ");"  not in line:
                  # Stripping "'" and "," from line
                  new_line=(line.replace('"','').rstrip().rstrip(',').strip())
#                   print new_line
                  (wwn,value) = new_line.split("=>")
                  wwns_conf_dic[wwn.strip()] = value.strip()
    f.close()


    if verbose >= 1 and not silent:
        amd.ok_msg("   >> Compiled wwns_conf option:value dictionary" )

    return  wwns_conf_dic


# }}}
    # node_firstboot
def get_node_firstboot_path(): # {{{
    """Returns the path of the node_firstboot file e.g node_firstboot"""
    node_firstboot_path ="/csmimages/node_firstboot_" + str.strip(args.source_lpar)
    return node_firstboot_path
   
# }}}
def is_node_firstboot_file(node_firstboot_path,verbose=False, silent=False, quit=False):# {{{
    """Checking if the node_firstboot_path file exist
    - The default path of the file is /csmimages
    - This function does a very simple file check
    usage: is_node_firstboot_file(get_node_firstboot_path())"""

    if os.path.isfile(node_firstboot_path):
        if verbose and not silent:
            amd.ok_msg("   >> File is in place:",
                    node_firstboot_path)
        return True
    else:
        if quit:
            amd.err_msg("   >> Inexistent file:",
                    get_node_firstboot_path(),
                    exit_code=16)
        else:
            return False
# }}}
    # node_ini
def get_node_ini_path(): # {{{
    """Returns the path of the node_ini file e.g node_ini_s230"""
    node_ini_path ="/csmimages/node_ini_" + str.strip(args.source_lpar)
    return node_ini_path
   
# }}}
def is_node_ini_file(node_ini_path,verbose=False, silent=False, quit=False):# {{{
    """Checking if the node_ini_path file exist
    - The default path of the file is /csmimages
    - This function does a very simple file check
    usage: is_node_ini_file(get_node_firstboot_path())"""

    if os.path.isfile(node_ini_path):
        if verbose and not silent:
            amd.ok_msg("   >> File is in place:",
                    node_ini_path)
        return True
    else:
        if quit:
            amd.err_msg("   >> Inexistent file:",
                    node_ini_path,
                    exit_code=16)
        else:
            return False
# }}}



# MKSYSB PROCESSING
def get_mksysb_path(): # {{{
    """Returns the path of the mksysb image processing directory"""
    mksysb_dir ="/csmimages/bos.obj." + str.strip(args.source_lpar)
    return mksysb_dir
   
# }}}
def get_mksysb_image_processing_dir(): # {{{
    """Returns the path of the mksysb image processing directory"""
    dir_path = "/csmimages/ssp_migration/"+str.strip(args.source_lpar)+"/mksysb_config/"
    return dir_path
   
# }}}
def get_mksysb_image_data_path(): # {{{
    """Returns the path of the mksysb image processing directory"""
    file_path = "/csmimages/ssp_migration/"+str.strip(args.source_lpar)+"/mksysb_config/image.data"
    return file_path 
   
# }}}
def get_mksysb_bosinst_data_path(): # {{{
    """Returns the path of bosinst.data file  """
    file_path = "/csmimages/ssp_migration/"+str.strip(args.source_lpar)+"/mksysb_config/bosinst.data"
    return file_path 
   
# }}}
def mk_mksysb_processing_dir(verbose=False, quit=False, silent=False): # {{{
    """Creating the dir_path directory to where the 
    image.data of the mksysb should be processed

    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bood
            Default location:    /cmsimages/ssp_migration/$node/mksysb_config/
    """
    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    if verbose >= 2 and not silent:
        amd.ok_msg("Creating the working dir_path for the mksysb processing to:")
        amd.info_msg("     /csmimages/ssp_migration/$source_lpar/mksysb_config")

    
    dir_path = get_mksysb_image_processing_dir()
    if os.path.isdir(dir_path):
      if verbose >= 2 and not silent:
         amd.ok_msg("The mksysb image processing dir exists.")
      return True
    else:
      unix_cmd=("mkdir -p "\
              " {}"\
              ).format(dir_path)
      
      if verbose >= 2 and not silent:
          amd.info_msg("unix_cmd is: ",
                  unix_cmd)

      p = subprocess.Popen(unix_cmd,\
              shell=True, stdout=subprocess.PIPE,\
              stderr=subprocess.STDOUT)
      rc = p.wait()
      
      
          # Unix_cmd has failed
      if rc!=0:
         return False
      
          # Unix_cmd executed successfully
      elif rc==0:
         if verbose >= 1 and not silent:
           amd.ok_msg("   >> The mksysb image processing directory has been created")
         return True
          
   
# }}}
def is_mksysb(mksysb_path):# {{{
    """Checking if the mksysb file exists
    - The default path of the file is /csmimages
    - This function does os very simple file check
    """
    if os.path.isfile(mksysb_path):
        return True
    else:
        return False
# }}}
def is_mksysb_new(mksysb_path, age=2):# {{{
    """Determines if the mksysb is older than age

    :age: the number of days
    :returns: BOOL

    """
    today = datetime.datetime.today()
    modified_age = datetime.datetime.\
            fromtimestamp(os.path.getmtime(mksysb_path))
    mksysb_age = today - modified_age
    if mksysb_age.days > age:
        return False
    else:
        return True
# }}}
def is_mksysb_valid(mksysb_path,verbose=False, quit=False, silent=False):# {{{
    """Check if mksysb is a valid mksysb file

    :mksysb_path: The path of the mksysb
    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :returns:   BOOL
    """
    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    var1 = mksysb_path
    opt1 = "lf"
    unix_cmd=("/usr/bin/lsmksysb"\
            " -{} "\
            "{}"\
            ).format(opt1,var1)
    
    if verbose >= 2:
        amd.info_msg("  unix_cmd is: ", unix_cmd)
    
    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    
        # Unix_cmd has failed
    if rc!=0:
       amd.err_msg("The mksysb file is invalid",
               exit_code=3)
       return False
    
        # Unix_cmd executed successfully
    elif rc==0:
        if verbose >= 2 and not silent:
            for line in p.stdout:
               print "\t" + str.strip(line)
        else:
               amd.ok_msg("   >> The mksysb file is valid")
        return True
   
# }}}
def is_mksysb_rootvg_mirrored(mksysb_path,verbose=False, quit=False, silent=False):# {{{
    """Check if rootvg in the mksysb is mirrored 

    :mksysb_path: The path of the mksysb
    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :returns:   mirrored_rtoovg = bool
    """
    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    is_rootvg_mirrored = False          # Asume not mirrored VG

    var1 = mksysb_path
    opt1 = "lf"
    unix_cmd=("/usr/bin/lsmksysb"\
            " -{} "\
            "{}"\
            ).format(opt1,var1)
    
    if verbose >= 2:
        amd.info_msg("unix_cmd is: ",
                unix_cmd)
    
    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    
        # Unix_cmd has failed
    if rc!=0:
       amd.err_msg("The mksysb file is invalid",
               exit_code=3)
       return False
    
        # Unix_cmd executed successfully
    elif rc==0:
       do_compare=False
       for line in p.stdout:
           if "TYPE" and "LPs" in line:
               do_compare=True

           if do_compare and not ("TYPE" in line):
               columns = line.split()       # Split it into columnts
               if len(columns)> 5:          # Check if it has at least 5 columns
                                            # next, check if PP is >= to LP
                   if int(columns[3]) > int(columns[2]):
                       is_rootvg_mirrored = True
                       if not silent:
                           amd.info_msg("   >> The rootvg inside the mksysb IS mirrored")
                       return is_rootvg_mirrored

    if not is_rootvg_mirrored:
        if not silent:
           amd.ok_msg("   >> The rootvg inside the mksysb is NOT mirrored")
    return is_rootvg_mirrored
        
   
# }}}
def goto_mksysb_processing_dir(verbose=False, quit=False, silent=False): # {{{
    """Changing the directory to where the bosinst.data of the mksysb should be

    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bood
            Default location:    /cmsimages/ssp_migration/$node/mksysb_config/
    """
    if verbose >= 2 and not silent:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])
    
    #  Create mksysb image processing dir if it does not exist
    mk_mksysb_processing_dir(verbose=verbose)

   
    local_dir=get_mksysb_image_processing_dir()

    if verbose >= 1 and not silent:
        amd.ok_msg("   >> Changing the working dir for the mksysb processing to:")
        amd.info_msg(" >> ", local_dir)

    try:
       os.chdir(local_dir)
    except Exception as e:
       if quit:
         amd.err_msg("Unable to change dir to", local_dir, exit_code=8)
       else:
          amd.err_msg("Unable to change dir to", local_dir)
       raise e
   
# }}}
def extract_mksysb_image_data(verbose=False, quit=False, silent=False): # {{{
    """Extracting the rootvg image.data

    :mksysb_path: The path of the mksysb
    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   mksysb_image_data_path 
            Default location:    /cmsimages/ssp_migration/node/mksyb_config/

     UNIX_CMD: 
      # cd /tmp 
      2. Restore the image.data file to your current location: 
      # restore -xqvf </location/of/mksysb/file> ./image.data 
      ***The image.data file from the mksysb image \
            will be restored to the /tmp directory 
    """
    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    # Changing the directory to the mksysb image processing dir
    # Exit the program if you cannot access it: quit=True
    goto_mksysb_processing_dir(verbose=args.verbose,
       quit=True,
       silent=True)
    # Start the extraction process 
    dir_path = get_mksysb_image_processing_dir()
    if verbose >= 2 and not silent:
        amd.ok_msg("   >> Extracting the image data to:", dir_path)

    # Unix_cmd: 
    mksysb_path=get_mksysb_path()
    opt1 = "xqvf"
    file_to_extract = "./image.data"
    unix_cmd=("/usr/sbin/restore "\
            " -{} "\
            "{}"\
            " {}"\
            ).format(opt1,mksysb_path, file_to_extract)
  
    if verbose >= 2 and not silent:
        amd.info_msg("  unix_cmd is: ", unix_cmd)
    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
        # Unix_cmd has failed
    if rc!=0:
       if quit:
          if  not silent:
             amd.err_msg("Unable to extract the mysysb image data",
                   exit_code=7)
       else:
         if not silent:
             amd.err_msg("Unable to extract the mysysb image data")
       return False
        # Unix_cmd executed successfully
    elif rc==0:
       if verbose >= 2 and not silent:
          for line in p.stdout:
              print "\t" + str.strip(line)
       return True
# }}}
def extract_mksysb_bosinst_data(verbose=False, quit=False, silent=False): # {{{
    """Extracting the ./bosinst.data for unattended instalaltion

    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   mksysb_image_data_path 
            Default location:    /cmsimages/ssp_migration/node/mksyb_config/

     UNIX_CMD: 
      # cd /tmp 
      2. Restore the image.data file to your current location: 
      # restore -xqvf </location/of/mksysb/file> ./bosinst.data
      - nonprompted IBM example 
      https://www.ibm.com/support/knowledgecenter/en/ssw_aix_71/\
            com.ibm.aix.install/bosinst.data_file_nonprompted_nw_install.htm

      - general documentation: 
      https://www.ibm.com/support/knowledgecenter/en/ssw_aix_71/\
            com.ibm.aix.install/bosinst_data_file_intro.htm
    """
    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    # Changing the directory to the mksysb image processing 
    # Exit the program if you cannot access it: quit=True
    goto_mksysb_processing_dir(verbose=args.verbose,
       quit=True,
       silent=True)

    # Start the extraction process 
    dir_path = get_mksysb_image_processing_dir()
    if verbose >= 2 and not silent:
        amd.ok_msg("  Extracting the bosinst.data file to:", dir_path)

    # Unix_cmd: 
    mksysb_path=get_mksysb_path()
    opt1 = "xqvf"
    file_to_extract = "./bosinst.data"
    unix_cmd=("/usr/sbin/restore "\
            " -{} "\
            "{}"\
            " {}"\
            ).format(opt1,mksysb_path, file_to_extract)
  
    if verbose >= 2 and not silent:
        amd.info_msg("  unix_cmd is: ", unix_cmd)

    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()

        # Unix_cmd has failed
    if rc!=0:
       if quit:
          if  not silent:
             amd.err_msg("Unable to extract the bosinst.data from the mksysb",
                   exit_code=9)
       else:
         if not silent:
             amd.err_msg("Unable to extract the bosinst.data from the mksysb")
       return False

        # Unix_cmd executed successfully
    elif rc==0:
       if verbose >= 2 and not silent:
          for line in p.stdout:
              print "\t" + str.strip(line)
       return True
# }}}
def unmirror_mksysb_image_data(verbose=False, quit=False, silent=False): # {{{
    """UnMirroring the  rootvg image.data

    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   mksysb_image_data_path 
            Default location:    /cmsimages/ssp_migration/node/mksyb_config/
    """
    if verbose >=2 and not silent:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    

    # Start the image_data file processing
    image_data_file_path = get_mksysb_image_data_path()
    if verbose >= 1 and not silent:
        amd.ok_msg("   >> Starting the processing of the image.data file:")

    # Print the values to be modified before they are modified
    if verbose >= 2 and not silent:
       amd.info_msg("Listing image.data BEFORE UnMirroring")
       pattern_to_modify=["PP=", "LV_SOURCE_DISK_LIST=", "COPIES="]
       with open(image_data_file_path,'r') as f:
          # Read/print file line by line: 
          for line in f:
             if any(x in line for x in pattern_to_modify ):
                print "\t Initial  values: {}".format(str.strip(line))
       f.close()




    # Replacing LV_SOURCE_DISK_LST
    for line in fileinput.FileInput(image_data_file_path, inplace=1):
       if "LV_SOURCE_DISK_LIST=" not in line:
          print str.strip(line)
       else:
            # Extracting only the "LV_SOURCE_DISK_LST=" part of the line
            # Line looks li: LV_SOURCE_DISK_LIST= hdisk0 hdiskN
           lv_source_string=line.split("=")[0] 
           initial_line=line
           lv_source_string +="= hdisk0" 

           line=line.replace(initial_line, lv_source_string)
           print str.strip(line)


    # Replacing COPIES
    for line in fileinput.FileInput(image_data_file_path, inplace=1):
       if "COPIES=" not in line:
          print str.strip(line)
       else:
            # Extracting only the "COPIES=" part of the line
            # Line looks like: COPIES= 2 or COPIES= N
           copies_string=line.split("=")[0] 
           initial_line=line
           copies_string +="= 1" 

           line=line.replace(initial_line, copies_string)
           print str.strip(line)


    # Replacing PP SIZE  ... Splitting it half
    for line in fileinput.FileInput(image_data_file_path, inplace=1):
       if "PP=" not in line:
          print str.strip(line)
       else:
            # Extracting the PP integers
          double_PP_int= int(str.strip(line.split("PP=")[1]))
          unmirrored_PP_int=double_PP_int/2
          PP_mirrored_string=line
          PP_unmirrored_sting="PP= {}".format(str(unmirrored_PP_int))
            # Compiling the string to be matched
          line=line.replace(PP_mirrored_string, PP_unmirrored_sting)
          print str.strip(line)



    # Print the values to be modified after they are modified
    if verbose >= 2 and not silent:
       amd.info_msg("Listing image.data AFTER UnMirroring")
       pattern_to_modify=["PP=", "LV_SOURCE_DISK_LIST=", "COPIES=", "LVVV"]
       with open(image_data_file_path,'r') as f:
          # Read/print file line by line: 
          for line in f:
             if any(x in line for x in pattern_to_modify ):
                print "\t Modified values: {}".format(str.strip(line))
       f.close()






#       line=line.replace("COPIES= 2","COPIES= 1")
#         #  The next line is needed to actualy moidfy the data 
#       print line
#
   
# }}}
def is_bosinst_data_valid(verbose=False, quit=False, silent=False):# {{{

    """Checking if  ./bosinst.data is valid -> bool

    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   mksysb_image_data_path 
            Default location:    /cmsimages/ssp_migration/node/mksyb_config/

     UNIX_CMD: 
     /usr/lpp/bosinst/bicheck bosinst.data
     https://www.ibm.com/support/knowledgecenter/en/ssw_aix_71/\
           com.ibm.aix.install/bosinst.data_file_example.htm
    """



    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    # Changing the directory to the mksysb image processing 
    # Exit the program if you cannot access it: quit=True
    goto_mksysb_processing_dir(verbose=args.verbose,
       quit=True,
       silent=True)


    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Starting validation for:  bosinst.data")

    # Unix_cmd
    bosinst_file_path=get_mksysb_bosinst_data_path()
    unix_cmd=("/usr/lpp/bosinst/bicheck"\
            "  {}"\
            ).format(bosinst_file_path)
    
    if verbose >= 2 and not silent:
        amd.info_msg("  unix_cmd is: ", unix_cmd)
    
    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    
        # Unix_cmd has failed
    if rc!=0:
       amd.err_msg("The bosinst.file is NOT  valid",
               exit_code=10)
       return False
    
        # Unix_cmd executed successfully
    elif rc==0:
       if verbose >= 1 and not silent:
           amd.ok_msg("   >> The bosinst.file  is valid")
       return True
   
# }}}
def mk_boinst_data(verbose=False, quit=False, silent=False): # {{{
    """UnMirroring the  rootvg image.data

    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   mksysb_image_data_path 
            Default location:    /cmsimages/ssp_migration/node/mksyb_config/
    """
    if verbose >=2 and not silent:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    

    # Start the bosinst_data file processing
    bosinst_file_path = get_mksysb_bosinst_data_path()


    # Print the values to be modified before they are modified# {{{
    if verbose >= 2 and not silent:
       amd.info_msg("Listing bosinst.data BEFORE:")
       pattern_to_modify=["CONSOLE",
          "INSTALL_METHOD",
          "PROMPT",
          "EXISTING_SYSTEM_OVERWRITE",
          "ACCEPT_LICENSES",
          "target_disk_data",
          "RECOVER_DEVICES",
          "target_disk_data",
          "SIZE_MB",
          "HDISKNAME"]
       with open(bosinst_file_path,'r') as f:
          # Read/print file line by line: 
          for line in f:
             if any(x in line for x in pattern_to_modify ):
                if "#" not in line:
                   print "\t Initial  values: {}".format(str.strip(line))
       f.close()
# }}}
     
    if verbose >= 1 and not silent:
        amd.ok_msg("   >> Configuring the control_flow stanza:")

    # Replacing CONSOLE # {{{
    for line in fileinput.FileInput(bosinst_file_path, inplace=1):
       if "CONSOLE =" not in line:
          print str.strip(line)
       else:
            # Modify only the actual stanza, and not the comments
          if "#" not in line: 
              # Extracting only the "PROMPT =" part of the line
              # Line looks like: PROMPT = yes
             pattern_string=line.split("=")[0] 
             initial_line=line
             pattern_string +="= Default" 

             line=line.replace(initial_line, pattern_string)
             print str.strip(line)
          else:
             # preserve the comments
             print str.strip(line)


# }}}
    # Replacing PROMPT # {{{
    for line in fileinput.FileInput(bosinst_file_path, inplace=1):
       if "PROMPT =" not in line:
          print str.strip(line)
       else:
            # Modify only the actual stanza, and not the comments
          if "#" not in line: 
              # Extracting only the "PROMPT =" part of the line
              # Line looks like: PROMPT = yes
             pattern_string=line.split("=")[0] 
             initial_line=line
             pattern_string +="= no" 

             line=line.replace(initial_line, pattern_string)
             print str.strip(line)
          else:
             # preserve the comments
             print str.strip(line)


# }}}
    # Replacing RECOVER_DEVICES # {{{
    for line in fileinput.FileInput(bosinst_file_path, inplace=1):
       if "RECOVER_DEVICES" not in line:
          print str.strip(line)
       else:
            # Modify only the actual stanza, and not the comments
          if "#" not in line: 
              # Extracting only the "PROMPT =" part of the line
              # Line looks like: PROMPT = yes
             pattern_string=line.split("=")[0] 
             initial_line=line
             pattern_string +="= no" 

             line=line.replace(initial_line, pattern_string)
             print str.strip(line)
          else:
             # preserve the comments
             print str.strip(line)


# }}}
    # Replacing  INSTALL_METHOD # {{{
    for line in fileinput.FileInput(bosinst_file_path, inplace=1):
       if "INSTALL_METHOD =" not in line:
          print str.strip(line)
       else:
            # Modify only the actual stanza, and not the comments
          if "#" not in line: 
              # Extracting only the "PROMPT =" part of the line
              # Line looks like: PROMPT = yes
             pattern_string=line.split("=")[0] 
             initial_line=line
             pattern_string +="= migrate" 

             line=line.replace(initial_line, pattern_string)
             print str.strip(line)
          else:
             # preserve the comments
             print str.strip(line)


# }}}
    # Replacing  EXISTING_SYSTEM_OVERWRITE # {{{
    for line in fileinput.FileInput(bosinst_file_path, inplace=1):
       if "EXISTING_SYSTEM_OVERWRITE =" not in line:
          print str.strip(line)
       else:
            # Modify only the actual stanza, and not the comments
          if "#" not in line: 
              # Extracting only the "PROMPT =" part of the line
              # Line looks like: PROMPT = yes
             pattern_string=line.split("=")[0] 
             initial_line=line
             pattern_string +="= yes" 

             line=line.replace(initial_line, pattern_string)
             print str.strip(line)
          else:
             # preserve the comments
             print str.strip(line)


# }}}
    # Replacing  ACCEPT_LICENSES # {{{
    for line in fileinput.FileInput(bosinst_file_path, inplace=1):
       if "ACCEPT_LICENSES =" not in line:
          print str.strip(line)
       else:
            # Modify only the actual stanza, and not the comments
          if "#" not in line: 
              # Extracting only the "PROMPT =" part of the line
              # Line looks like: PROMPT = yes
             pattern_string=line.split("=")[0] 
             initial_line=line
             pattern_string +="= yes" 

             line=line.replace(initial_line, pattern_string)
             print str.strip(line)
          else:
             # preserve the comments
             print str.strip(line)


# }}}
    # Processing target_disk_data code-block# {{{
    if verbose >= 1 and not silent:
        amd.ok_msg("   >> Configuring the target_disk_data stanza:")

    processing_file = fileinput.FileInput(bosinst_file_path, inplace=1)
    remove_until_end=False
    for line in processing_file:
      if not remove_until_end:
         print str.strip(line)
         if "target_disk_data:" in line:
            print str.strip("SIZE_MB = 122880")
            print str.strip("HDISKNAME = hdisk0")
            remove_until_end=True

      
# }}}

    # Print the values to be modified before they are modified# {{{
    if verbose >= 2 and not silent:
       amd.info_msg("Listing bosinst.data AFTER:")
       pattern_to_modify=["CONSOLE",
          "INSTALL_METHOD",
          "PROMPT",
          "EXISTING_SYSTEM_OVERWRITE",
          "ACCEPT_LICENSES",
          "target_disk_data",
          "RECOVER_DEVICES",
          "target_disk_data",
          "SIZE_MB",
          "HDISKNAME"]
       with open(bosinst_file_path,'r') as f:
          # Read/print file line by line: 
          for line in f:
             if any(x in line for x in pattern_to_modify ):
                if "#" not in line:
                   print "\t Modified  values: {}".format(str.strip(line))
       f.close()

    if verbose >= 2 and not silent:
      amd.refactoring_msg("I know it's bad:\n \
       Further selection criteria needed for  target_disk_data.\n \
       PHYSICAL_LOCATION, CONNECTION to be used after\
 the HMC module is completed")
# }}}



    # # Control_flow: 
      # PROMPT = no
      # INSTALL_METHOD = overwrite
      # target_disk_data = hdisk0
      #  CONSOLE ?
      # INSTALL_METHOD = overwrite
      # ACCEPT_LICENSES = yes
      # RECOVER_DEVICES

      # target_disk_data:








   
# }}}
def get_oslevel_from_mksysbd(mksysb_path,verbose=False, quit=False, silent=False):# {{{
    """Retrieving the OSLEVEL [SERVICELEVEL ] from mksysb: str:e.g.7200-01-01-1642

    :mksysb_path: The path of the mksysb
    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :returns:   BOOL
    """
    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Retrieving the OSLEVEL from the mksysb")

    var1 = mksysb_path
    opt1 = "lf"
    unix_cmd=("/usr/bin/lsmksysb"\
            " -{} "\
            "{}"\
            ).format(opt1,var1)
    
    if verbose >= 2:
        amd.info_msg("  unix_cmd is: ", unix_cmd)
    
    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
        # Unix_cmd has failed
    if rc!=0:
       amd.err_msg("Unable to determine the OSLEVE from the mksysb",
               exit_code=3)
       return False
   
        # Unix_cmd executed successfully
    elif rc==0:
        for line in p.stdout:
           if "SERVICEPACK LEVEL" in line:
               oslevel=line.split(":")[1].strip()
               if verbose >= 1 and not silent:
                  amd.ok_msg("   >>",oslevel, "is the OSLEVEL of the mksysb")
               return oslevel
        return False
   
# }}}

# NIM OPERATIONS
# DEFINITIONS
def am_i_nim_master(verbose=False, quit=False, silent=False):# {{{

    """Checking if the local system is a NIM Master -> bool

    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool

     UNIX_CMD: lsnim
    """

    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    if verbose >= 1 and not silent:
       amd.ok_msg("   >> AM I the master, the NIM MASTER, that is ?")

    # Unix_cmd
    unix_cmd=("lsnim")
    
    if verbose >= 2 and not silent:
        amd.info_msg("  unix_cmd is: ", unix_cmd)
    
    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    
        # Unix_cmd has failed
    if rc!=0:
       return False
    
        # Unix_cmd executed successfully
    elif rc==0:
       if verbose >= 1 and not silent:
           amd.ok_msg("   >> Yes, I am.")
       return True
   
# }}}
def get_nim_server_name(): # {{{
    """Returns the name of the NIM server: master"""
    # Refactoring: I need to determine a reliable method for this function
    nim_server_name = "master"
    return nim_server_name
# }}}
def get_nim_res_processing_dir(): # {{{
    """Returns the path of the NIM resource processing directory"""
    dir_path="/csmimages/ssp_migration/"+str.strip(args.source_lpar)+"/nim_res/"
    return dir_path
   
# }}}
def get_nim_bosinst_data_res_path(): # {{{
    """Returns the path of the NIM bosinst_data file"""
    file_path="/csmimages/ssp_migration/"+\
            str.strip(args.source_lpar)+\
            "/nim_res/bosinst.data"
    return file_path
# }}}
def get_nim_image_data_res_path(): # {{{
    """Returns the path of the NIM bosinst_data file"""
    file_path="/csmimages/ssp_migration/"+\
            str.strip(args.source_lpar)+\
            "/nim_res/image.data"
    return file_path
# }}}
def get_nim_fb_res_path(): # {{{
    """Returns the path of the first_boot script path"""
    file_path="/csmimages/ssp_migration/"+\
            str.strip(args.source_lpar)+\
            "/nim_res/node_firstboot_"+\
            str.strip(args.source_lpar)
    return file_path
# }}}
def mk_nim_processing_dir(verbose=False, quit=False, silent=False): # {{{
    """Creating the directory where NIM resource will reside aftre i
    they are defined:  

    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bood
            Default location:    /cmsimages/ssp_migration/$node/nim_res/
    """
    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    if verbose >= 2 and not silent:
        amd.ok_msg("Creating the working dir NIM resources:")

    
        amd.info_msg(get_nim_res_processing_dir())

    nim_dir = get_nim_res_processing_dir()
    if os.path.isdir(nim_dir):
      if verbose >= 1 and not silent:
         amd.ok_msg("   >> The NIM resource processing directory exists")
      return True
    else:
      unix_cmd=("mkdir -p "\
              " {}"\
              ).format(nim_dir)
      
      if verbose >= 2 and not silent:
          amd.info_msg("unix_cmd is: ",
                  unix_cmd)

      p = subprocess.Popen(unix_cmd,\
              shell=True, stdout=subprocess.PIPE,\
              stderr=subprocess.STDOUT)
      rc = p.wait()
      
      
          # Unix_cmd has failed
      if rc!=0:
         return False
      
          # Unix_cmd executed successfully
      elif rc==0:
         if verbose >= 1 and not silent:
           amd.ok_msg("  >>The NIM resource processing dir has been created.")
         return True
          
   
# }}}
   # NIM BOSINST.DATA {noprompt install and hdisk0 modification}
def cp_bosinst_data_to_nim_res(verbose=False, quit=False, silent=False):# {{{

    """Copying  the processed bosinst.data file from mksysb_config dir
    to the nim_res dir. It is here where it will be defined as a 
    nim resource by nim_define_bosinst_data_res()-> bool

    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool

     UNIX_CMD: cp
    """

    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Copying the bosinst_data to the nim_res dir")

    # Unix_cmd
    bosinst_file_source_path=get_mksysb_bosinst_data_path()
    bosinst_file_destination_dir=get_nim_res_processing_dir()
    unix_cmd=("cp  "\
            " {}"\
            " {}"
            ).format(bosinst_file_source_path,
            bosinst_file_destination_dir)


    
    if verbose >= 2 and not silent:
        amd.info_msg("  unix_cmd is: ", unix_cmd)
    
    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    
        # Unix_cmd has failed
    if rc!=0:
       if quit:
           amd.err_msg("Unable to copy the bosinst.data file to the\
 nim_res processing directory", 
            exit_code=10)
       else:
           return False
    
        # Unix_cmd executed successfully
    elif rc==0:
       if verbose >= 1 and not silent:
           amd.ok_msg("   >> bosinst.data file successfully copied")
       return True
   
# }}}
def is_nim_bosinst_data_res(verbose=False, quit=False, silent=False):# {{{

    """Checking if the bosinst.data resource exists: -> bool

    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/ssp_migration/node/nim_res/

     UNIX_CMD: 
     lsnim -l resource_name

    """



    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Checking if the resource is already defined")

    # Unix_cmd
    bosinst_data_name = "noprompt_data_{}".format(args.source_lpar)
    unix_cmd=("lsnim -l  "\
            " {}"
            ).format(bosinst_data_name)
    
    if verbose >= 2 and not silent:
        amd.info_msg("  unix_cmd is: ", unix_cmd)
    
    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    
        # Unix_cmd has failed
    if rc!=0:
       return False
    
        # Unix_cmd executed successfully
    elif rc==0:
       if verbose >= 1 and not silent:
           amd.ok_msg("   >> The bosinst.data for",
                  args.source_lpar,
                  "exits")
       return True
   
# }}}
def nim_define_bosinst_data_res(verbose=False, quit=False, silent=False, force=False):# {{{

    """Defining a NIM bosinst.data resource: -> bool

    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/ssp_migration/node/nim_res/

     UNIX_CMD: 
     nim -o define -t bosinst_data -a Attribute=Value ... bosinst_dataName
    """
    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    if is_nim_bosinst_data_res(silent=True):
       if verbose >= 1 and not silent:
           amd.ok_msg("   >> The bosinst.data for",
                  args.source_lpar,
                  "exists, nothing to do")
           return True
    else:


        # Copying the bosinst.data file from mksysb_config to nim_res dir
        cp_bosinst_data_to_nim_res(verbose=args.verbose,
                quit=True,
                silent=False)

        if verbose >= 1 and not silent:
           amd.ok_msg("   >> Starting the NIM definition for  bosinst_data")

        # Unix_cmd
        bosinst_file_res_location=get_nim_bosinst_data_res_path()
        nim_server_name = get_nim_server_name()
        bosinst_data_name = "noprompt_data_{}".format(args.source_lpar)

        comments= "\"bosinst.data for {} migration\"".format(args.source_lpar)
        unix_cmd=("nim -o define "\
                " -t bosinst_data "\
                " -a location={}"\
                " -a server={}"\
                " -a comments={}"\
                " {}"
                ).format(bosinst_file_res_location,
                nim_server_name,
                comments,
                bosinst_data_name)
        
        if verbose >= 2 and not silent:
            amd.info_msg("  unix_cmd is: ", unix_cmd)
        
        p = subprocess.Popen(unix_cmd,\
                shell=True, stdout=subprocess.PIPE,\
                stderr=subprocess.STDOUT)
        rc = p.wait()
        
        
            # Unix_cmd has failed
        if rc!=0:
            if quit:
               amd.err_msg("Unable to define the bosinst.data nim resource",
                   exit_code=11)
            else:
               amd.err_msg("Unable to define the bosinst.data nim resource")
            return False
        
            # Unix_cmd executed successfully
        elif rc==0:
           if verbose >= 1 and not silent:
               amd.ok_msg("   >> The bosinst.data for",
                      args.source_lpar,
                      "has been defined")
           return True
   
# }}}
def nim_remove_bosinst_data_res(verbose=False, quit=False, silent=False):# {{{

    """Removing a NIM bosinst.data resource: -> bool

    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/ssp_migration/node/nim_res/

     UNIX_CMD: 
     nim -o remove  bosinst_dataName
    """

    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    bosinst_data_name = "noprompt_data_{}".format(args.source_lpar)

    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Starting to remove ",
       bosinst_data_name)

    if is_nim_bosinst_data_res(silent=True):
        # Unix_cmd
        if args.FORCE:
            unix_cmd=("nim -o remove "\
                " -F "\
                " {}"
                ).format(bosinst_data_name)
        else:
            unix_cmd=("nim -o remove "\
                " {}"
                ).format(bosinst_data_name)

        if verbose >= 2 and not silent:
            amd.info_msg("  unix_cmd is: ", unix_cmd)
        
        p = subprocess.Popen(unix_cmd,\
                shell=True, stdout=subprocess.PIPE,\
                stderr=subprocess.STDOUT)
        rc = p.wait()
        
            # Unix_cmd has failed
        if rc!=0:
            if quit:
                amd.err_msg("Unable to remove ",
                   bosinst_data_name,
                   exit_code=12)
            else:
                amd.err_msg("Unable to remove ",
                   bosinst_data_name)
                return False
        
            # Unix_cmd executed successfully
        elif rc==0:
           if verbose >= 1 and not silent:
               amd.ok_msg("   >> NIM resource has been removed: ",
               bosinst_data_name)
           return True
   
# }}}
   # NIM IMAGE.DATA {spited/unmirrored rootvg}
def cp_image_data_to_nim_res(verbose=False, quit=False, silent=False):# {{{

    """Copying  the processed image.data file from mksysb_config dir
    to the nim_res dir. It is here where it will be defined as a 
    nim resource by nim_define_image_data_res()-> bool

    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool

     UNIX_CMD: cp
    """

    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Copying the image.data to the nim_res dir")

    # Unix_cmd
    image_data_file_path=get_mksysb_image_data_path()
    image_data_file_destination_dir=get_nim_res_processing_dir()
    unix_cmd=("cp  "\
            " {}"\
            " {}"
            ).format(image_data_file_path,
            image_data_file_destination_dir)

    if verbose >= 2 and not silent:
        amd.info_msg("  unix_cmd is: ", unix_cmd)
    
    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
        # Unix_cmd has failed
    if rc!=0:
       if quit:
           amd.err_msg("Unable to copy the image.data file to the\
 nim_res processing directory", 
            exit_code=13)
       else:
           return False
    
        # Unix_cmd executed successfully
    elif rc==0:
       if verbose >= 1 and not silent:
           amd.ok_msg("   >> image.data file successfully copied")
       return True
   
# }}}
def is_nim_image_data_res(verbose=False, quit=False, silent=False):# {{{

    """Checking if the image.data resource exists: -> bool

    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/ssp_migration/node/nim_res/

     UNIX_CMD: 
     lsnim -l resource_name

    """



    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Checking if the resource is already defined")

# HERE
    # Unix_cmd
    image_data_name = "image_data_{}".format(args.source_lpar)
    unix_cmd=("lsnim -l  "\
            " {}"
            ).format(image_data_name)
    
    if verbose >= 2 and not silent:
        amd.info_msg("  unix_cmd is: ", unix_cmd)
    
    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    
        # Unix_cmd has failed
    if rc!=0:
       return False
    
        # Unix_cmd executed successfully
    elif rc==0:
       if verbose >= 1 and not silent:
           amd.ok_msg("   >> The image.data for",
                  args.source_lpar,
                  "exits")
       return True
   
# }}}
def nim_define_image_data_res(verbose=False, quit=False, silent=False, force=False):# {{{

    """Defining a NIM image.data resource: -> bool

    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/ssp_migration/node/nim_res/

     UNIX_CMD: 
     nim -o define -t bosinst_data -a Attribute=Value ... inst_data_dataName
    """

    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    if is_nim_image_data_res(silent=True):
       if verbose >= 1 and not silent:
           amd.ok_msg("   >> The image.data for",
                  args.source_lpar,
                  "exists, nothing to do")
           return True
    else:


        # Copying the image.data file from mksysb_config to nim_res dir
        cp_image_data_to_nim_res(verbose=args.verbose,
                quit=True,
                silent=False)

        if verbose >= 1 and not silent:
           amd.ok_msg("   >> Starting the NIM definition for image_data")

        # Unix_cmd
        image_file_res_location=get_nim_image_data_res_path()

        nim_server_name = get_nim_server_name()
        image_data_name = "image_data_{}".format(args.source_lpar)
        comments= "\"image.data for {} migration\"".format(args.source_lpar)
        unix_cmd=("nim -o define "\
                " -t image_data "\
                " -a location={}"\
                " -a server={}"\
                " -a comments={}"\
                " {}"
                ).format(image_file_res_location,
                nim_server_name,
                comments,
                image_data_name)
        
        if verbose >= 2 and not silent:
            amd.info_msg("  unix_cmd is: ", unix_cmd)
        
        p = subprocess.Popen(unix_cmd,\
                shell=True, stdout=subprocess.PIPE,\
                stderr=subprocess.STDOUT)
        rc = p.wait()
        
        
            # Unix_cmd has failed
        if rc!=0:
            if quit:
               amd.err_msg("Unable to define the image.data nim resource",
                   exit_code=11)
            else:
               amd.err_msg("Unable to define the image.data nim resource")
            return False
        
            # Unix_cmd executed successfully
        elif rc==0:
           if verbose >= 1 and not silent:
               amd.ok_msg("   >> The image.data for",
                      args.source_lpar,
                      "has been defined")
           return True
   
# }}}
def nim_remove_image_data_res(verbose=False, quit=False, silent=False):# {{{

    """Removing a NIM image.data resource: -> bool

    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/ssp_migration/node/nim_res/

     UNIX_CMD: 
     nim -o remove  image_dataName
    """

    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    image_data_name = "image_data_{}".format(args.source_lpar)

    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Starting to remove ",
       image_data_name)

    if is_nim_image_data_res(silent=True):
        # Unix_cmd
        if args.FORCE:
            unix_cmd=("nim -o remove "\
                " -F "\
                " {}"
                ).format(image_data_name)
        else:
            unix_cmd=("nim -o remove "\
                " {}"
                ).format(image_data_name)

        if verbose >= 2 and not silent:
            amd.info_msg("  unix_cmd is: ", unix_cmd)
        
        p = subprocess.Popen(unix_cmd,\
                shell=True, stdout=subprocess.PIPE,\
                stderr=subprocess.STDOUT)
        rc = p.wait()
        
            # Unix_cmd has failed
        if rc!=0:
            if quit:
                amd.err_msg("Unable to remove ",
                   image_data_name,
                   exit_code=12)
            else:
                amd.err_msg("Unable to remove ",
                   image_data_name)
                return False
        
            # Unix_cmd executed successfully
        elif rc==0:
           if verbose >= 1 and not silent:
               amd.ok_msg("   >> NIM resource has been removed: ",
               image_data_name)
           return True
   
# }}}
   # NIM  MKSYSB 
def is_nim_mksysb_res(verbose=False, quit=False, silent=False):# {{{

    """Checking if the mksysb resource exists: -> bool

    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/

     UNIX_CMD: 
     lsnim -l resource_name
    """



    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Checking if the resource is already defined")

    # Unix_cmd
    mksysb_res_name = "mksysb_{}".format(args.source_lpar)
    unix_cmd=("lsnim -l  "\
            " {}"
            ).format(mksysb_res_name)
    
    if verbose >= 2 and not silent:
        amd.info_msg("  unix_cmd is: ", unix_cmd)
    
    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    
        # Unix_cmd has failed
    if rc!=0:
       return False
    
        # Unix_cmd executed successfully
    elif rc==0:
       if verbose >= 1 and not silent:
           amd.ok_msg("   >> The mksysb for",
                  args.source_lpar,
                  "exits")
       return True
# }}}
def nim_define_mksysb_res(verbose=False, quit=False, silent=False, force=False):# {{{

    """Defining a NIM mksysb resource resource: -> bool

    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/

     UNIX_CMD: 
     nim -o define -t mksysb -a Attribute=Value ... mksysb_image_name
    """

    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    if is_nim_mksysb_res(silent=True):
       if verbose >= 1 and not silent:
           amd.ok_msg("   >> The mksysb resource for",
                  args.source_lpar,
                  "exists, nothing to do")
           return True
    else:


        if verbose >= 1 and not silent:
           amd.ok_msg("   >> Starting the NIM definition for mksysb")

        # Unix_cmd
        mksysb_source_path=get_mksysb_path()
        nim_server_name = get_nim_server_name()

        mksysb_res_name = "mksysb_{}".format(args.source_lpar)
        comments= "\"mksysb for {} migration\"".format(args.source_lpar)
        unix_cmd=("nim -o define "\
                " -t mksysb "\
                " -a location={}"\
                " -a server={}"\
                " -a comments={}"\
                " {}"
                ).format(mksysb_source_path,
                nim_server_name,
                comments,
                mksysb_res_name)
        
        if verbose >= 2 and not silent:
            amd.info_msg("  unix_cmd is: ", unix_cmd)
        
        p = subprocess.Popen(unix_cmd,\
                shell=True, stdout=subprocess.PIPE,\
                stderr=subprocess.STDOUT)
        rc = p.wait()
        
        
            # Unix_cmd has failed
        if rc!=0:
            if quit:
               amd.err_msg("Unable to define the mksysb nim resource",
                   exit_code=13)
            else:
               amd.err_msg("Unable to define the mksysb nim resource")
            return False
        
            # Unix_cmd executed successfully
        elif rc==0:
           if verbose >= 1 and not silent:
               amd.ok_msg("   >> The mksysb resource for",
                      args.source_lpar,
                      "has been defined")
           return True
   
# }}}
def nim_remove_mksysb_res(verbose=False, quit=False, silent=False):# {{{

    """Removing a NIM mksysb resource: -> bool

    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/

     UNIX_CMD: 
     nim -o remove mksysb_name
    """

    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    mksysb_res_name = "mksysb_{}".format(args.source_lpar)

    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Starting to remove ",
       mksysb_res_name)

    if is_nim_mksysb_res(verbose=args.verbose):
        # Unix_cmd
        if args.FORCE:
            unix_cmd=("nim -o remove "\
                " -F "\
                " {}"
                ).format(mksysb_res_name)
        else:
            unix_cmd=("nim -o remove "\
                " {}"
                ).format(mksysb_res_name)

        if verbose >= 2 and not silent:
            amd.info_msg("  unix_cmd is: ", unix_cmd)
        
        p = subprocess.Popen(unix_cmd,\
                shell=True, stdout=subprocess.PIPE,\
                stderr=subprocess.STDOUT)
        rc = p.wait()
        
            # Unix_cmd has failed
        if rc!=0:
            if quit:
                amd.err_msg("Unable to remove ",
                   mksysb_res_name,
                   exit_code=15)
            else:
                amd.err_msg("Unable to remove ",
                   mksysb_res_name)
                return False
        
            # Unix_cmd executed successfully
        elif rc==0:
           if verbose >= 1 and not silent:
               amd.ok_msg("   >> NIM resource has been removed: ",
               mksysb_res_name)
           return True
   
# }}}


   # NIM  SPOT_CLIENT_DEDICATED
def is_nim_spot_res(verbose=False, quit=False, silent=False):# {{{

    """Checking if the sport resource exists: -> bool

    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/

     UNIX_CMD: 
     lsnim -l resource_name
    """



    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Checking if the resource is already defined")

    # Unix_cmd
    spot_res_name = "spot_{}".format(args.source_lpar)
    unix_cmd=("lsnim -l  "\
            " {}"
            ).format(spot_res_name)
    
    if verbose >= 2 and not silent:
        amd.info_msg("  unix_cmd is: ", unix_cmd)
    
    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    
        # Unix_cmd has failed
    if rc!=0:
       return False
    
        # Unix_cmd executed successfully
    elif rc==0:
       if verbose >= 1 and not silent:
           amd.ok_msg("   >> The spot for",
                  args.source_lpar,
                  "exits")
       return True
# }}}
def nim_define_spot_res(verbose=False, quit=False, silent=False, force=False):# {{{

    """Defining a NIM spot resource resource: -> bool

    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/

     UNIX_CMD: 
     nim -o define -t spot -a source=mksysb1 -a server=master -a location=/export/spot spot1
    """

    amd.info_msg(" !!! REFACTORING: Internal rev. required for a unified SPOT arch.")
    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    if is_nim_spot_res(silent=True):
       if verbose >= 1 and not silent:
           amd.ok_msg("   >> The spot resource for",
                  args.source_lpar,
                  "exists, nothing to do")
           return True
    else:


        if verbose >= 1 and not silent:
           amd.ok_msg("   >> Starting the NIM definition for spot")

        # Unix_cmd
        mksysb_source_path=get_mksysb_path()
        nim_server_name = get_nim_server_name()

        spot_res_name = "spot_{}".format(args.source_lpar)
        comments= "\"spot_for_{}_migration\"".format(args.source_lpar)
        mksysb_res_name = "mksysb_{}".format(args.source_lpar)
        spot_location=get_nim_res_processing_dir()
        unix_cmd=("nim -o define "\
                " -t spot "\
                " -a source={}"\
                " -a server={}"\
                " -a location={}"\
                " -a comments={}"\
                " {}"
                ).format(mksysb_res_name,
                nim_server_name,
                spot_location,
                comments,
                spot_res_name)
        
        if verbose >= 2 and not silent:
            amd.info_msg("  unix_cmd is: ", unix_cmd)
        
        p = subprocess.Popen(unix_cmd,\
                shell=True, stdout=subprocess.PIPE,\
                stderr=subprocess.STDOUT)
        rc = p.wait()
        
        
            # Unix_cmd has failed
        if rc!=0:
            if quit:
               amd.err_msg("Unable to define the spot nim resource",
                   exit_code=13)
            else:
               amd.err_msg("Unable to define the spot nim resource")
            return False
        
            # Unix_cmd executed successfully
        elif rc==0:
           if verbose >= 1 and not silent:
               amd.ok_msg("   >> The spot resource for",
                      args.source_lpar,
                      "has been defined")
           return True
   
# }}}
def nim_remove_spot_res(verbose=False, quit=False, silent=False):# {{{

    """Removing a SPOT  resource: -> bool

    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /csmimages/ssp_migration/$node/nim_res/

     UNIX_CMD: 
     nim -o remove spot_name
    """

    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    spot_res_name = "spot_{}".format(args.source_lpar)

    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Starting to remove ",
       spot_res_name)

    if is_nim_spot_res(verbose=args.verbose):
        # Unix_cmd
        if args.FORCE:
            unix_cmd=("nim -o remove "\
                " -F "\
                " {}"
                ).format(spot_res_name)
        else:
            unix_cmd=("nim -o remove "\
                " {}"
                ).format(spot_res_name)

        if verbose >= 2 and not silent:
            amd.info_msg("  unix_cmd is: ", unix_cmd)
        
        p = subprocess.Popen(unix_cmd,\
                shell=True, stdout=subprocess.PIPE,\
                stderr=subprocess.STDOUT)
        rc = p.wait()
        
            # Unix_cmd has failed
        if rc!=0:
            if quit:
                amd.err_msg("Unable to remove ",
                   spot_res_name,
                   exit_code=15)
            else:
                amd.err_msg("Unable to remove ",
                   spot_res_name)
                return False
        
            # Unix_cmd executed successfully
        elif rc==0:
           if verbose >= 1 and not silent:
               amd.ok_msg("   >> NIM resource has been removed: ",
               spot_res_name)
           return True
   
# }}}


   # NIM  FB First Boot
def cp_node_firstboot_to_nim_res(verbose=False, quit=False, silent=False):# {{{

    """Copying the initial node_firstboot_* file into nim_re directory

    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool

     UNIX_CMD: cp
    """

    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Copying the node_firstboot* to the nim_res dir")

    # Unix_cmd
    initial_node_fb_file=get_node_firstboot_path()
    destination_node_fb_file=get_nim_fb_res_path()
    unix_cmd=("cp  "\
            " {}"\
            " {}"
            ).format(initial_node_fb_file,destination_node_fb_file)

    if verbose >= 2 and not silent:
        amd.info_msg("  unix_cmd is: ", unix_cmd)
    
    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
        # Unix_cmd has failed
    if rc!=0:
       if quit:
           amd.err_msg("Unable to copy the node_firstboot file to the\
 nim_res processing directory", 
            exit_code=13)
       else:
           return False
    
        # Unix_cmd executed successfully
    elif rc==0:
       if verbose >= 1 and not silent:
           amd.ok_msg("   >> node_firstboot file successfully copied")
       return True
   
# }}}
                # Not needed for migration
def generate_fb_to_nim_res(verbose=False, quit=False, silent=False):# {{{

    """Generating a First boot script tailored for the lapr 
    and place it in the nim_res file

    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool

     UNIX_CMD: cp
    """

    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Generating the first_boot content for:",
               args.source_lpar)

    first_boot_path=get_nim_fb_res_path()
    with open(first_boot_path,'a') as f:
       # Append with a new line
       f.write("# test"+ "\n")
    f.close()

    return True
   
# }}}
def is_nim_fb_res(verbose=False, quit=False, silent=False):# {{{

    """Checking if the fb resource exists: -> bool

    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/ssp_migration/node/nim_res/

     UNIX_CMD: 
     lsnim -l resource_name

    """



    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Checking if the resource is already defined")

    # Unix_cmd
    fb_script_name = "node_firstboot_{}".format(args.source_lpar)
    unix_cmd=("lsnim -l  "\
            " {}"
            ).format(fb_script_name)
    
    if verbose >= 2 and not silent:
        amd.info_msg("  unix_cmd is: ", unix_cmd)
    
    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    
        # Unix_cmd has failed
    if rc!=0:
       return False
    
        # Unix_cmd executed successfully
    elif rc==0:
       if verbose >= 1 and not silent:
           amd.ok_msg("   >> The first_boot for",
                  args.source_lpar,
                  "exits")
       return True
   
# }}}
def nim_define_fb_script_res(verbose=False, quit=False, silent=False, force=False):# {{{

    """Defining a NIM fb  resource: -> bool

    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/ssp_migration/node/nim_res/

     UNIX_CMD: 
     nim -o define -t fb_script  -a Attribute=Value ... inst_data_dataName
    """

    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    if is_nim_fb_res(silent=True):
       if verbose >= 1 and not silent:
           amd.ok_msg("   >> The fb_script for",
                  args.source_lpar,
                  "exists, nothing to do")
           return True
    else:


        if verbose >= 1 and not silent:
           amd.ok_msg("   >> Starting the NIM definition for fb_script")

        # Copying the node_firtboot file from /csmimages/ to nim_res dir
        cp_node_firstboot_to_nim_res(verbose=args.verbose,
                quit=True,
                silent=False)



        # Unix_cmd
        fb_script_res_location=get_nim_fb_res_path()

        nim_server_name = get_nim_server_name()
        fb_script_name = "node_firstboot_{}".format(args.source_lpar)
        comments= "\"fb_script for {} migration\"".format(args.source_lpar)
        unix_cmd=("nim -o define "\
                " -t fb_script "\
                " -a location={}"\
                " -a server={}"\
                " -a comments={}"\
                " {}"
                ).format(fb_script_res_location,
                nim_server_name,
                comments,
                fb_script_name)
        
        if verbose >= 2 and not silent:
            amd.info_msg("  unix_cmd is: ", unix_cmd)
        
        p = subprocess.Popen(unix_cmd,\
                shell=True, stdout=subprocess.PIPE,\
                stderr=subprocess.STDOUT)
        rc = p.wait()
        
        
            # Unix_cmd has failed
        if rc!=0:
            if quit:
               amd.err_msg("Unable to define the fb_script nim resource",
                   exit_code=11)
            else:
               amd.err_msg("Unable to define the fb_script nim resource")
            return False
        
            # Unix_cmd executed successfully
        elif rc==0:
           if verbose >= 1 and not silent:
               amd.ok_msg("   >> The fb_script for",
                      args.source_lpar,
                      "has been defined")
           return True
   
# }}}
def nim_remove_fb_script_res(verbose=False, quit=False, silent=False):# {{{

    """Removing a NIM fb_script resource: -> bool

    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/ssp_migration/node/nim_res/

     UNIX_CMD: 
     nim -o remove fb_script_name
    """

    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    fb_script_name = "node_firstboot_{}".format(args.source_lpar)

    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Starting to remove ",fb_script_name)

    if is_nim_fb_res(silent=True):
        # Unix_cmd
        if args.FORCE:
            unix_cmd=("nim -o remove "\
                " -F "\
                " {}"
                ).format(fb_script_name)
        else:
            unix_cmd=("nim -o remove "\
                " {}"
                ).format(fb_script_name)

        if verbose >= 2 and not silent:
            amd.info_msg("  unix_cmd is: ", unix_cmd)
        
        p = subprocess.Popen(unix_cmd,\
                shell=True, stdout=subprocess.PIPE,\
                stderr=subprocess.STDOUT)
        rc = p.wait()
        
            # Unix_cmd has failed
        if rc!=0:
            if quit:
                amd.err_msg("Unable to remove ",
                   fb_script_name,
                   exit_code=12)
            else:
                amd.err_msg("Unable to remove ",
                   fb_script_name)
                return False
        
            # Unix_cmd executed successfully
        elif rc==0:
           if verbose >= 1 and not silent:
               amd.ok_msg("   >> NIM resource has been removed: ",
               fb_script_name)
           return True
   
# }}}
# RESOLVCONF
    # Refactoring
    # The next code block is using a hardcoded value: resolvconf
def is_nim_resolvconf(verbose=False, quit=False, silent=False):# {{{

    """Checking if the resov_conf  resource exists: -> bool

    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/ssp_migration/node/nim_res/

     UNIX_CMD: 
     lsnim -l resource_name

    """



    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Checking if the resource is already defined")

    # Unix_cmd
    
    unix_cmd=("lsnim -l  "\
            " {}"
            ).format(resolv_conf_name)
    
    if verbose >= 2 and not silent:
        amd.info_msg("  unix_cmd is: ", unix_cmd)
    
    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    
        # Unix_cmd has failed
    if rc!=0:
       return False
    
        # Unix_cmd executed successfully
    elif rc==0:
       if verbose >= 1 and not silent:
           amd.ok_msg("   >> The global resolv_conf resource exits")
       return True
   
# }}}

   # NIM  NETWORKS
def get_nim_all_networks(verbose=False, silent=False, quit=False): # {{{
    """Identifying all NIM networks : all_nim_networks -> list """

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    all_nim_networks=[] 
    unix_cmd=("lsnim -c networks")

    if verbose >= 2 and not silent:
       amd.info_msg("  unix_cmd is: ", unix_cmd)

    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
        # Unix_cmd has failed
    if rc!=0:
        if verbose >= 2 and not silent:
            for line in p.stdout:
                print line.strip()

        if quit:
           amd.err_msg("Unable to Identify all the NIM networks",
                   exit_code=25)
        else:
           return False
    
        # Unix_cmd executed successfully
    elif rc==0:
        for line in p.stdout:
            all_nim_networks.append(line.split()[0])

    return all_nim_networks

# }}}
def get_nim_network(all_nim_networks, ms, verbose=False, silent=False, quit=False): # {{{
    """Identifying all NIM networks : all_nim_networks -> list
    ms:     Target Managed System :
    all_nim_networks: get_nim_all_networks()
        This value is used to extract the network containg it as a comment
       # lsnim -l  ms_net198
       ms_net198:
       comments   = internes Netz csm4
        """

#    if verbose >= 2:
#       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    nim_netwok=False
    csm_pattern = "csm"+ms.strip()[-1]

    if "s03" in ms.lower():
        return "ms_net198"

    
    for network in all_nim_networks:

        unix_cmd=("lsnim -lZ "\
                "{}").format(network)

        if verbose >= 2 and not silent:
           amd.info_msg("  unix_cmd is: ", unix_cmd)

        p = subprocess.Popen(unix_cmd,\
                shell=True, stdout=subprocess.PIPE,\
                stderr=subprocess.STDOUT)
        rc = p.wait()
        
            # Unix_cmd has failed
        if rc!=0:
            if verbose >= 2 and not silent:
                for line in p.stdout:
                    print line.strip()

            if quit:
               amd.err_msg("Unable to Identify the right NIM network",
                       exit_code=25)
            else:
               return False


            # Unix_cmd executed successfully
        elif rc==0:
            for line in p.stdout:
                if csm_pattern in line:
                    if verbose and not silent:
                       amd.ok_msg("   >> The nim network to be used is:", network)
                    return network



# }}}
   # NIM  NODE/CLIENT
def is_nim_client(client_name, verbose=False, quit=False, silent=False):# {{{

    """Checking if the mksysb resource exists: -> bool

    :client_name    The name of the client lpar. e.g s370en0
    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/

     UNIX_CMD: 
     lsnim -l resource_name
    """



    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Checking if the client is already defined")

    # Unix_cmd
    unix_cmd=("lsnim -l "\
            " {}"
            ).format(client_name)
    
    if verbose >= 2 and not silent:
        amd.info_msg("  unix_cmd is: ", unix_cmd)
    
    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    
        # Unix_cmd has failed
    if rc!=0:
       return False
    
        # Unix_cmd executed successfully
    elif rc==0:
       if verbose >= 1 and not silent:
           amd.ok_msg("   >> The client",
                  args.source_lpar,
                  "exits")
       return True
# }}}
def nim_define_client(client_name, network, verbose=False, quit=False, silent=False, force=False):# {{{

    """Defining a NIM client: -> bool

    :client_name    The name of the client lpar. e.g s370en0
    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/

     UNIX_CMD: 
    ="nim -o define -t standalone\
            -a if1=\"ms_net $NODE $MAC\" -a mgmt_profile1=\"$HMC $ID $BLECH\" \
            -a comments=\"$CONFIG{FUNCTION}\" $NODE";
    """

    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    if is_nim_client(client_name, silent=True):
       if verbose >= 1 and not silent:
           amd.ok_msg("   >> The nim client exists",
                  args.source_lpar,
                  "nothing to do")
           return True
    else:


        if verbose >= 1 and not silent:
           amd.ok_msg("   >> Starting the NIM definition for the client lpar")

        # Unix_cmd
        nim_server_name = get_nim_server_name()

        # Retrieving the mac address
        mac=get_lpar_mac(args.hmc,
            args.destination_managed_system,
            args.source_lpar, 
            quit=True)

        if1_string="{} {} {}".format(network, client_name, mac)

        # Compiling the mgmt_profile
        lpar_id= get_lpar_id(args.hmc,
                  args.destination_managed_system,
                  args.source_lpar,
                  verbose=silent,
                  quit=True)

        mgmt_string=str(args.hmc)+" "+str(lpar_id)+" "+str(args.destination_managed_system)

        mksysb_res_name = "mksysb_{}".format(args.source_lpar)
        comments= "\"migration of {}\"".format(args.source_lpar)
        unix_cmd=("nim -o define "\
                " -t standalone "\
                " -a platform=\"chrp\""\
                " -a netboot_kernel=\"64\""\
                " -a if1=\"{}\""\
                " -a mgmt_profile1=\"{}\""\
                " -a comments={}"\
                " {}"
                ).format(if1_string,
                mgmt_string,
                comments,
                client_name)
        
        if verbose >= 2 and not silent:
            amd.info_msg("  unix_cmd is: ", unix_cmd)
        
        p = subprocess.Popen(unix_cmd,\
                shell=True, stdout=subprocess.PIPE,\
                stderr=subprocess.STDOUT)
        rc = p.wait()
        
        
            # Unix_cmd has failed
        if rc!=0:
            if quit:
               amd.err_msg("Unable to define the  nim client",
                   exit_code=13)
            else:
               amd.err_msg("Unable to define the  nim client")
            return False
        
            # Unix_cmd executed successfully
        elif rc==0:
           if verbose >= 1 and not silent:
               amd.ok_msg("   >> The nim client",
                      args.source_lpar,
                      "has been defined")
           return True
   
# }}}
def nim_remove_client(client_name, verbose=False, quit=False, silent=False):# {{{

    """Removing a NIM client: -> bool

    :client_name = the name of the NIM client to remove: 
    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/

     UNIX_CMD: 
     nim -o remove client_name 
    """

    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])



    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Starting to remove ", client_name)

    if is_nim_client(client_name, silent=True):
        # Unix_cmd
        if args.FORCE:
            unix_cmd=("nim -o remove "\
                " -F "\
                " {}"
                ).format(client_name)
        else:
            unix_cmd=("nim -o remove "\
                " {}"
                ).format(client_name)

        if verbose >= 2 and not silent:
            amd.info_msg("  unix_cmd is: ", unix_cmd)
        
        p = subprocess.Popen(unix_cmd,\
                shell=True, stdout=subprocess.PIPE,\
                stderr=subprocess.STDOUT)
        rc = p.wait()
        
            # Unix_cmd has failed
        if rc!=0:
            if quit:
                amd.err_msg("Unable to remove ",
                   client_name,
                   exit_code=15)
            else:
                amd.err_msg("Unable to remove ",
                   client_name)
                return False
        
            # Unix_cmd executed successfully
        elif rc==0:
           if verbose >= 1 and not silent:
               amd.ok_msg("   >> NIM client has been removed: ",
               client_name)
           return True
   
# }}}
def nim_reset_client(client_name, verbose=False, quit=False, silent=False, force=False):# {{{

    """Reseting the resources allocated to the LPAR

    :client_name = the name of the NIM client to remove: 
    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/

     UNIX_CMD: 
     nim -o remove client_name 
    """

    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])



    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Starting to reset ", client_name)

    if is_nim_client(client_name, silent=True):
        # Unix_cmd
        if force:
            unix_cmd=("nim -o reset "\
                " -F "\
                " {}"
                ).format(client_name)
        else:
            unix_cmd=("nim -o reset "\
                " {}"
                ).format(client_name)

        if verbose >= 2 and not silent:
            amd.info_msg("  unix_cmd is: ", unix_cmd)
        
        p = subprocess.Popen(unix_cmd,\
                shell=True, stdout=subprocess.PIPE,\
                stderr=subprocess.STDOUT)
        rc = p.wait()
        
            # Unix_cmd has failed
        if rc!=0:
            if quit:
                amd.err_msg("Unable to reset ",
                   client_name,
                   exit_code=15)
            else:
                amd.err_msg("Unable to reset ",
                   client_name)
                return False
        
            # Unix_cmd executed successfully
        elif rc==0:
           if verbose >= 1 and not silent:
               amd.ok_msg("   >> NIM client is reset: ",
               client_name)
           return True
   
# }}}





# NIM Allocation/deallocation
   # NIM BOSINST.DATA
def nim_allocate_bosinst_data(client_name, verbose=False, quit=False, silent=False, force=False):# {{{

    """Allocating bosinst_data to an lpar: -> bool
    : lpar_name The name of the lpar
    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool

     UNIX_CMD: 
     nim -o allocate -a bosinst_data=bosinst_data_s370en0 s370en0
    """

    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    if not is_nim_image_data_res(silent=True): 
        amd.err_msg("Inexistent bosinst_data, please define it and retry")
        if not is_nim_client(client_name, silent=True):
            amd.err_msg("Inexistent client, please define it and retry")




    if is_nim_bosinst_data_res(silent=True): 
        if is_nim_client(client_name, silent=True):

            if verbose >= 2 and not silent:
               amd.ok_msg("   >> Starting the bosinst_data allocation")

            # Unix_cmd
            bosinst_data_name = "noprompt_data_{}".format(args.source_lpar)
            client_name=str(client_name).strip()
            unix_cmd=("nim -o allocate -a bosinst_data="\
                    "{} "\
                    " {}"
                    ).format(bosinst_data_name, client_name)
            
            if verbose >= 2 and not silent:
                amd.info_msg("  unix_cmd is: ", unix_cmd)
            
            p = subprocess.Popen(unix_cmd,\
                    shell=True, stdout=subprocess.PIPE,\
                    stderr=subprocess.STDOUT)
            rc = p.wait()
            
            
                # Unix_cmd has failed
            if rc!=0:
                if quit:
                   amd.err_msg("Unable to allocate the bosinst_data resource",
                       exit_code=13)
                else:
                   amd.err_msg("Unable to allocate the bosinst_data  resource")
                return False
            
                # Unix_cmd executed successfully
            elif rc==0:
               if verbose >= 1 and not silent:
                   amd.ok_msg("   >>",
                         bosinst_data_name,
                         "is allocated to:", 
                         args.source_lpar)
               return True
   
# }}}
def nim_deallocate_bosinst_data(client_name, verbose=False, quit=False, silent=False, force=False):# {{{

    """Deallocating a bosinst_dat resource to an lpar: -> bool
    : lpar_name The name of the lpar
    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/

     UNIX_CMD: 
     nim -o deallocate -a bosinst_data=noprompt_data_s370en0  s370en0
    """

    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    if is_nim_bosinst_data_res(silent=True): 
        if is_nim_client(client_name, silent=True):

            if verbose >= 1 and not silent:
               amd.ok_msg("   >> Starting the bosinst_data deallocation")

            # Unix_cmd
            bosinst_data_name = "noprompt_data_{}".format(args.source_lpar)
            client_name=str(client_name).strip()
            unix_cmd=("nim -o deallocate -a bosinst_data="\
                    "{} "\
                    " {}"
                    ).format(bosinst_data_name, client_name)
            
            if verbose >= 2 and not silent:
                amd.info_msg("  unix_cmd is: ", unix_cmd)
            
            p = subprocess.Popen(unix_cmd,\
                    shell=True, stdout=subprocess.PIPE,\
                    stderr=subprocess.STDOUT)
            rc = p.wait()
            
            
                # Unix_cmd has failed
            if rc!=0:
                if quit:
                   amd.err_msg("Unable to deallocate the bosinst_data  resource",
                       exit_code=13)
                else:
                   amd.err_msg("Unable to deallocate the bosinst_data  resource")
                return False
            
                # Unix_cmd executed successfully
            elif rc==0:
               if verbose >= 1 and not silent:
                   amd.ok_msg("   >>",
                         bosinst_data_name,
                         "has been  deallocated from:", 
                         args.source_lpar)
               return True
   
# }}}
   # NIM IMAGE.DATA
def nim_allocate_image_data(client_name, verbose=False, quit=False, silent=False, force=False):# {{{

    """Allocating image_data to an lpar: -> bool
    : lpar_name The name of the lpar
    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/

     UNIX_CMD: 
     nim -o allocate -a image_data=image_data_s370en0 s370en0
    """

    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    if not is_nim_image_data_res(silent=True): 
        amd.err_msg("Inexistent image_data, please define it and retry")
        if not is_nim_client(client_name, silent=True):
            amd.err_msg("Inexistent client, please define it and retry")




    if is_nim_image_data_res(silent=True): 
        if is_nim_client(client_name, silent=True):

            if verbose >= 1 and not silent:
               amd.ok_msg("   >> Starting the image_data allocation")

            # Unix_cmd
            image_data_name = "image_data_{}".format(args.source_lpar)
            client_name=str(client_name).strip()
            unix_cmd=("nim -o allocate -a image_data="\
                    "{} "\
                    " {}"
                    ).format(image_data_name, client_name)
            
            if verbose >= 2 and not silent:
                amd.info_msg("  unix_cmd is: ", unix_cmd)
            
            p = subprocess.Popen(unix_cmd,\
                    shell=True, stdout=subprocess.PIPE,\
                    stderr=subprocess.STDOUT)
            rc = p.wait()
            
            
                # Unix_cmd has failed
            if rc!=0:
                if quit:
                   amd.err_msg("Unable to allocate the image_data resource",
                       exit_code=13)
                else:
                   amd.err_msg("Unable to allocate the image_data  resource")
                return False
            
                # Unix_cmd executed successfully
            elif rc==0:
               if verbose >= 1 and not silent:
                   amd.ok_msg("   >>",
                         image_data_name,
                         "is allocated to:", 
                         args.source_lpar)
               return True
   
# }}}
def nim_deallocate_image_data(client_name, verbose=False, quit=False, silent=False, force=False):# {{{

    """Deallocating a image_data resource to an lpar: -> bool
    : lpar_name The name of the lpar
    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/

     UNIX_CMD: 
     nim -o deallocate -a image_data=image_data_s370en0  s370en0
    """

    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    if is_nim_image_data_res(silent=True): 
        if is_nim_client(client_name, silent=True):

            if verbose >= 1 and not silent:
               amd.ok_msg("   >> Starting the image_data deallocation")

            # Unix_cmd
            image_data_name = "image_data_{}".format(args.source_lpar)
            client_name=str(client_name).strip()
            unix_cmd=("nim -o deallocate -a image_data="\
                    "{} "\
                    " {}"
                    ).format(image_data_name, client_name)
            
            if verbose >= 2 and not silent:
                amd.info_msg("  unix_cmd is: ", unix_cmd)
            
            p = subprocess.Popen(unix_cmd,\
                    shell=True, stdout=subprocess.PIPE,\
                    stderr=subprocess.STDOUT)
            rc = p.wait()
            
            
                # Unix_cmd has failed
            if rc!=0:
                if quit:
                   amd.err_msg("Unable to deallocate the image_data  resource",
                       exit_code=13)
                else:
                   amd.err_msg("Unable to deallocate the image_data  resource")
                return False
            
                # Unix_cmd executed successfully
            elif rc==0:
               if verbose >= 1 and not silent:
                   amd.ok_msg("   >>",
                         image_data_name,
                         "has been  deallocated from:", 
                         args.source_lpar)
               return True
   
# }}}
   # NIM  MKSYSB 
def nim_allocate_mksysb_res(client_name, verbose=False, quit=False, silent=False, force=False):# {{{

    """Allocating a mksysb resource to an lpar: -> bool
    : lpar_name The name of the lpar
    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/

     UNIX_CMD: 
     nim -o allocate -a mksysb=mksysb_s370en0 s370en0
    """

    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    if not is_nim_mksysb_res(silent=True): 
        amd.err_msg("Inexistent mksysb, please define it and retry")
        if not is_nim_client(client_name, silent=True):
            amd.err_msg("Inexistent client, please define it and retry")




    if is_nim_mksysb_res(silent=True): 
        if is_nim_client(client_name, silent=True):

            if verbose >= 1 and not silent:
               amd.ok_msg("   >> Starting the mksysb allocation")

            # Unix_cmd
            mksysb_res_name = "mksysb_{}".format(args.source_lpar)
            client_name=str(client_name).strip()
            unix_cmd=("nim -o allocate -a mksysb="\
                    "{} "\
                    " {}"
                    ).format(mksysb_res_name, client_name)
            
            if verbose >= 2 and not silent:
                amd.info_msg("  unix_cmd is: ", unix_cmd)
            
            p = subprocess.Popen(unix_cmd,\
                    shell=True, stdout=subprocess.PIPE,\
                    stderr=subprocess.STDOUT)
            rc = p.wait()
            
            
                # Unix_cmd has failed
            if rc!=0:
                if quit:
                   amd.err_msg("Unable to allocate the mksysb nim resource",
                       exit_code=13)
                else:
                   amd.err_msg("Unable to allocate the mksysb nim resource")
                return False
            
                # Unix_cmd executed successfully
            elif rc==0:
               if verbose >= 1 and not silent:
                   amd.ok_msg("   >>",
                         mksysb_res_name,
                         "is allocated to:", 
                         args.source_lpar)
               return True
   
# }}}
def nim_deallocate_mksysb_res(client_name, verbose=False, quit=False, silent=False, force=False):# {{{

    """Deallocating a mksysb resource to an lpar: -> bool
    : lpar_name The name of the lpar
    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/

     UNIX_CMD: 
     nim -o deallocate -a mksysb=mksysb_s370en0 s370en0
    """

    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    if is_nim_mksysb_res(silent=True): 
        if is_nim_client(client_name, silent=True):

            if verbose >= 1 and not silent:
               amd.ok_msg("   >> Starting the mksysb deallocation")

            # Unix_cmd
            mksysb_res_name = "mksysb_{}".format(args.source_lpar)
            client_name=str(client_name).strip()
            unix_cmd=("nim -o deallocate -a mksysb="\
                    "{} "\
                    " {}"
                    ).format(mksysb_res_name, client_name)
            
            if verbose >= 2 and not silent:
                amd.info_msg("  unix_cmd is: ", unix_cmd)
            
            p = subprocess.Popen(unix_cmd,\
                    shell=True, stdout=subprocess.PIPE,\
                    stderr=subprocess.STDOUT)
            rc = p.wait()
            
            
                # Unix_cmd has failed
            if rc!=0:
                if quit:
                   amd.err_msg("Unable to deallocate the mksysb nim resource",
                       exit_code=13)
                else:
                   amd.err_msg("Unable to deallocate the mksysb nim resource")
                return False
            
                # Unix_cmd executed successfully
            elif rc==0:
               if verbose >= 1 and not silent:
                   amd.ok_msg("   >>",
                         mksysb_res_name,
                         "has been  deallocated from:", 
                         args.source_lpar)
               return True
   
# }}}
   # NIM  FIRST_BOOT
def nim_allocate_fb_script(client_name, verbose=False, quit=False, silent=False, force=False):# {{{

    """Allocating a first_boot_script to an lpar: -> bool
    : lpar_name The name of the lpar
    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/

     UNIX_CMD: 
     nim -o allocate -a mksysb=mksysb_s370en0 s370en0
    """

    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    if not is_nim_fb_res(silent=True): 
        amd.err_msg("Inexistent first_boot script, please define it and retry")
        if not is_nim_client(client_name, silent=True):
            amd.err_msg("Inexistent client, please define it and retry")




    if is_nim_fb_res(silent=True): 
        if is_nim_client(client_name, silent=True):

            if verbose >= 1 and not silent:
               amd.ok_msg("   >> Starting the first_boot allocation")

            # Unix_cmd
            fb_script_name = "node_firstboot_{}".format(args.source_lpar)
            client_name=str(client_name).strip()
            unix_cmd=("nim -o allocate -a fb_script="\
                    "{} "\
                    " {}"
                    ).format(fb_script_name, client_name)
            
            if verbose >= 2 and not silent:
                amd.info_msg("  unix_cmd is: ", unix_cmd)
            
            p = subprocess.Popen(unix_cmd,\
                    shell=True, stdout=subprocess.PIPE,\
                    stderr=subprocess.STDOUT)
            rc = p.wait()
            
            
                # Unix_cmd has failed
            if rc!=0:
                if quit:
                   amd.err_msg("Unable to allocate the fb_script resource",
                       exit_code=13)
                else:
                   amd.err_msg("Unable to allocate the fb_script nim resource")
                return False
            
                # Unix_cmd executed successfully
            elif rc==0:
               if verbose >= 1 and not silent:
                   amd.ok_msg("   >>",
                         fb_script_name,
                         "is allocated to:", 
                         args.source_lpar)
               return True
   
# }}}
def nim_deallocate_fb_script(client_name, verbose=False, quit=False, silent=False, force=False):# {{{

    """Deallocating a fb_script resource to an lpar: -> bool
    : lpar_name The name of the lpar
    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/

     UNIX_CMD: 
     nim -o deallocate -a fb_script=fb_script_s370en0  s370en0
    """

    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    if is_nim_mksysb_res(silent=True): 
        if is_nim_client(client_name, silent=True):

            if verbose >= 1 and not silent:
               amd.ok_msg("   >> Starting the fb_script deallocation")

            # Unix_cmd
            fb_script_name = "node_firstboot_{}".format(args.source_lpar)
            client_name=str(client_name).strip()
            unix_cmd=("nim -o deallocate -a fb_script="\
                    "{} "\
                    " {}"
                    ).format(fb_script_name, client_name)
            
            if verbose >= 2 and not silent:
                amd.info_msg("  unix_cmd is: ", unix_cmd)
            
            p = subprocess.Popen(unix_cmd,\
                    shell=True, stdout=subprocess.PIPE,\
                    stderr=subprocess.STDOUT)
            rc = p.wait()
            
            
                # Unix_cmd has failed
            if rc!=0:
                if quit:
                   amd.err_msg("Unable to deallocate the fb_script nim resource",
                       exit_code=13)
                else:
                   amd.err_msg("Unable to deallocate the fb_script nim resource")
                return False
            
                # Unix_cmd executed successfully
            elif rc==0:
               if verbose >= 1 and not silent:
                   amd.ok_msg("   >>",
                         fb_script_name,
                         "has been  deallocated from:", 
                         args.source_lpar)
               return True
   
# }}}
    # NIM SPOT_client_specific
def nim_allocate_spot_client_specific(client_name, verbose=False, quit=False, silent=False, force=False):# {{{

    """Allocating a spot to an lpar: -> bool
    : lpar_name The name of the lpar
    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/

     UNIX_CMD: 
     nim -o allocate -a spot=spot_AIX720101 s370en0
    """
    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Starting the SPOT  allocation")

    # Unix_cmd
    local_spot = "spot_{}".format(args.source_lpar)
    client_name=str(client_name).strip()
    unix_cmd=("nim -o allocate -a spot="\
            "{} "\
            " {}"
            ).format(local_spot, client_name)
    
    if verbose >= 2 and not silent:
        amd.info_msg("  unix_cmd is: ", unix_cmd)
    
    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    
        # Unix_cmd has failed
    if rc!=0:
        if quit:
           amd.err_msg("Unable to allocate the SPOT resource",
               exit_code=13)
        else:
           amd.err_msg("Unable to allocate the SPOT  resource")
        return False
    
        # Unix_cmd executed successfully
    elif rc==0:
       if verbose >= 1 and not silent:
           amd.ok_msg("   >>",
                 local_spot,
                 "is allocated to:", 
                 args.source_lpar)
       return True
   
# }}}
def nim_deallocate_spot_client_specific(client_name, verbose=False, quit=False, silent=False, force=False):# {{{

    """Deallocating a spot to an lpar: -> bool
    : lpar_name The name of the lpar
    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/

     UNIX_CMD: 
     nim -o deallocate -a spot=spot_AIX720101 s370en0
    """
    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Starting the SPOT deallocation")

    # Unix_cmd
    local_spot = "spot_{}".format(args.source_lpar)
    client_name=str(client_name).strip()
    unix_cmd=("nim -o deallocate -a spot="\
            "{} "\
            " {}"
            ).format(local_spot, client_name)
    
    if verbose >= 2 and not silent:
        amd.info_msg("  unix_cmd is: ", unix_cmd)
    
    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    
#        # Unix_cmd has failed
#    if rc!=0:
#        if quit:
#           amd.err_msg("Unable to deallocate the SPOT resource",
#               exit_code=13)
#        else:
#           amd.err_msg("Unable to deallocate the SPOT  resource")
#        return False
#    
#        # Unix_cmd executed successfully
#    elif rc==0:
#       if verbose >= 1 and not silent:
#           amd.ok_msg("   >>",
#                 local_spot,
#                 "had been allocated from:", 
#                 args.source_lpar)
#       return True
   
# }}}



    # NIM SPOT_general
def get_nim_highest_aix_spot(verbose=False, silent=False, quit=False): # {{{
    """Identifying the highest AIX SPOT str: -> spot
    This function makes two assumtions: 
        all AIX SPOTS contain the AIX substring
        the newers SPOT can be used for older AIX OSs"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    spot_patter="AIX"
    all_aix_spots=[] 
    all_aix_spots_numerical_version=[] 
    unix_cmd=("lsnim -t spot")

    if verbose >= 2 and not silent:
       amd.info_msg("  unix_cmd is: ", unix_cmd)

    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
        # Unix_cmd has failed
    if rc!=0:
        if verbose >= 2 and not silent:
            for line in p.stdout:
                print line.strip()

        if quit:
           amd.err_msg("Unable to Identify a valid  SPOT",
                   exit_code=25)
        else:
           return False
    
        # Unix_cmd executed successfully
    elif rc==0:
        for line in p.stdout:
            if spot_patter in line:
                all_aix_spots.append(line.split()[0])

    # processing the all_aix_spots list 
    for item in all_aix_spots:
        all_aix_spots_numerical_version.\
                append(int(str(item).split("spot_AIX")[1]))

    highest_numerical_spot=str(max(all_aix_spots_numerical_version))

    for item in all_aix_spots:
        if highest_numerical_spot in item:
            return item
    # Return False if none found
    return False




# }}}
def get_nim_all_aix_spot_lit(verbose=False, silent=False, quit=False): # {{{
    """Identifying the highest AIX SPOT list: -> spot
    This function returns all defined aix spots
        all AIX SPOTS contain the AIX substring
        the newest SPOT can be used for older AIX OSs"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    spot_patter="AIX"
    all_aix_spots=[] 
#     all_aix_spots_numerical_version=[] 
    unix_cmd=("lsnim -t spot")

    if verbose >= 2 and not silent:
       amd.info_msg("  unix_cmd is: ", unix_cmd)

    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
        # Unix_cmd has failed
    if rc!=0:
        if verbose >= 2 and not silent:
            for line in p.stdout:
                print line.strip()

        if quit:
           amd.err_msg("Unable to Identify a valid  SPOT",
                   exit_code=25)
        else:
           return False
    
        # Unix_cmd executed successfully
    elif rc==0:
        for line in p.stdout:
            if spot_patter in line:
                all_aix_spots.append(line.split()[0])
        return all_aix_spots



# }}}
def get_nim_aix_spot_based_on_oslevel(oslevel, verbose=False, silent=False, quit=False): # {{{
    """Identifying the AIX SPOT based on the oslevel str: -> spot
    This function makes two assumptions: 
        all AIX SPOTS contain the AIX substring
        the newers SPOT can be used for older AIX OSs
       oslevel: str: e.g. 7200-01-01-1642 
        """

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    all_aix_spots=get_nim_all_aix_spot_lit(quit=True)




    for spot in all_aix_spots:
        unix_cmd=("lsnim -l {}").format(spot)

        if verbose >= 2 and not silent:
           amd.info_msg("  unix_cmd is: ", unix_cmd)
           amd.info_msg("  oslevel is: ", oslevel)

        p = subprocess.Popen(unix_cmd,\
                shell=True, stdout=subprocess.PIPE,\
                stderr=subprocess.STDOUT)
        rc = p.wait()
        
            # Unix_cmd has failed
        if rc!=0:
            if verbose >= 2 and not silent:
                for line in p.stdout:
                    print line.strip()
            if quit:
               amd.err_msg("Unable to Identify a valid  SPOT",
                       exit_code=25)
        
            # Unix_cmd executed successfully
        elif rc==0:
            for line in p.stdout:
                if oslevel in line:
                    if verbose >= 1 and not silent:
                        amd.ok_msg("   >> Spot to be used is:",spot)
                    return spot





# }}}
def nim_allocate_spot(client_name, spot, verbose=False, quit=False, silent=False, force=False):# {{{

    """Allocating a spot to an lpar: -> bool
    : lpar_name The name of the lpar
    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/

     UNIX_CMD: 
     nim -o allocate -a spot=spot_AIX720101 s370en0
    """
    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Starting the SPOT  allocation")

    # Unix_cmd
    local_spot = spot.strip()
    client_name=str(client_name).strip()
    unix_cmd=("nim -o allocate -a spot="\
            "{} "\
            " {}"
            ).format(local_spot, client_name)
    
    if verbose >= 2 and not silent:
        amd.info_msg("  unix_cmd is: ", unix_cmd)
    
    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    
        # Unix_cmd has failed
    if rc!=0:
        if quit:
           amd.err_msg("Unable to allocate the SPOT resource",
               exit_code=13)
        else:
           amd.err_msg("Unable to allocate the SPOT  resource")
        return False
    
        # Unix_cmd executed successfully
    elif rc==0:
       if verbose >= 1 and not silent:
           amd.ok_msg("   >>",
                 local_spot,
                 "is allocated to:", 
                 args.source_lpar)
       return True
   
# }}}
def nim_deallocate_spot(client_name, spot, verbose=False, quit=False, silent=False, force=False):# {{{

    """Dellocating a spot to an lpar: -> bool
    : lpar_name The name of the lpar
    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/

     UNIX_CMD: 
     nim -o deallocate -a spot=spot_AIX720101 s370en0
    """
    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Starting the SPOT deallocation")

    # Unix_cmd
    local_spot = spot.strip()
    client_name=str(client_name).strip()
    unix_cmd=("nim -o deallocate -a spot="\
            "{} "\
            " {}"
            ).format(local_spot, client_name)
    
    if verbose >= 2 and not silent:
        amd.info_msg("  unix_cmd is: ", unix_cmd)
    
    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    
#        # Unix_cmd has failed
#    if rc!=0:
#        if quit:
#           amd.err_msg("Unable to deallocate the SPOT resource",
#               exit_code=13)
#        else:
#           amd.err_msg("Unable to deallocate the SPOT  resource")
#        return False
#    
#        # Unix_cmd executed successfully
#    elif rc==0:
#       if verbose >= 1 and not silent:
#           amd.ok_msg("   >>",
#                 local_spot,
#                 "had been allocated from:", 
#                 args.source_lpar)
#       return True
   
# }}}



    # NIM LPPP_SOURCE
def get_nim_all_lpp_source_list(verbose=False, silent=False, quit=False): # {{{
    """Retrieving a list of all the lpp_sources :list:
    This function returns all defined lpp_sources
        all lpp_sources contain the lppsource substring
        all lpp_sources contain the AIX substring"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    lpp_pattern="AIX"
    all_lpp_sources_list=[] 
    unix_cmd=("lsnim -t lpp_source")

    if verbose >= 2 and not silent:
       amd.info_msg("  unix_cmd is: ", unix_cmd)

    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
        # Unix_cmd has failed
    if rc!=0:
        if verbose >= 2 and not silent:
            for line in p.stdout:
                print line.strip()

        if quit:
           amd.err_msg("Unable to Identify a valid lpp_source",
                   exit_code=25)
        else:
           return False
    
        # Unix_cmd executed successfully
    elif rc==0:
        for line in p.stdout:
            if lpp_pattern in line:
                all_lpp_sources_list.append(line.split()[0])
        return all_lpp_sources_list



# }}}
def get_nim_aix_lpp_source_based_on_oslevel(oslevel, verbose=False, silent=False, quit=False): # {{{
    """Identifying the AIX SPOT based on the oslevel str: -> spot
    This function makes two assumptions: 
        The standard for lpp_source name is: lppsource_AIXNNMMQQ
        where: 
        NN = realease : e.g. 72 or 71
        MM = Technology level .e.g 01, 09
        QQ = Service Packe nr: e.g. 01, 03
       oslevel: str: e.g. 7200-01-01-1642 
        """

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    all_lpp_sources_list=get_nim_all_lpp_source_list(quit=True)

    # Converting OSLEVEL to the AIXNNMMQQ FORMAT
    str_oslevel=str(oslevel).split("-",3)[:3]
    new_oslevel=str_oslevel[0][:2]+str_oslevel[1]+str_oslevel[2]
#     print new_oslevel
    
    is_lpp=False

    for lpp_source in all_lpp_sources_list:
        if new_oslevel in lpp_source:
            is_lpp=lpp_source
            break

    if quit and not is_lpp:
               amd.err_msg("Unable to Identify a valid lpp_source",
                       exit_code=25)

    if is_lpp:
       if verbose >= 1 and not silent:
           amd.ok_msg("   >>", is_lpp, "is the lpp_source to be used:")

    return is_lpp






# }}}
def nim_allocate_lpp_source(client_name, lpp_source, verbose=False, quit=False, silent=False, force=False):# {{{

    """Allocating an lpp_source  to an lpar: -> bool
    :client_name The name of the lpar
    :lpp_source: The lpp_source to be allocated. 
        usually retrieved by get_nim_aix_lpp_source_based_on_oslevel()
    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool
            Default location:    /cmsimages/

     UNIX_CMD: 
     nim -o allocate -a lpp_source=lppsource_AIX720101 s370en0
    """
    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Starting the lpp_source allocation")

    # Unix_cmd
    local_lpp_source = lpp_source.strip()
    client_name=str(client_name).strip()
    unix_cmd=("nim -o allocate -a lpp_source="\
            "{} "\
            " {}"
            ).format(local_lpp_source, client_name)
    
    if verbose >= 2 and not silent:
        amd.info_msg("  unix_cmd is: ", unix_cmd)
    
    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    
        # Unix_cmd has failed
    if rc!=0:
        if quit:
           amd.err_msg("Unable to allocate the lpp_source resource",
               exit_code=13)
        else:
           amd.err_msg("Unable to allocate the lpp_source  resource")
        return False
    
        # Unix_cmd executed successfully
    elif rc==0:
       if verbose >= 1 and not silent:
           amd.ok_msg("   >>",
                 local_lpp_source,
                 "is allocated to:", 
                 args.source_lpar)
       return True
   
# }}}
def nim_deallocate_lpp_source(client_name, lpp_source, verbose=False, quit=False, silent=False, force=False):# {{{

    """Deallocating a lpp_source fro an lpar: -> bool
    :client_name The name of the lpar
    :lpp_source The name of the lpar
    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool

     UNIX_CMD: 
     nim -o deallocate -a lpp_source=lppsource_AIX720101 s370en0
    """
    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Starting the lpp_source deallocation")

    # Unix_cmd
    local_lpp_source = lpp_source.strip()
    client_name=str(client_name).strip()
    unix_cmd=("nim -o deallocate -a lpp_source="\
            "{} "\
            " {}"
            ).format(local_lpp_source, client_name)
    
    if verbose >= 2 and not silent:
        amd.info_msg("  unix_cmd is: ", unix_cmd)
    
    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    
        # Unix_cmd has failed
#    if rc!=0:
#        if quit:
#           amd.err_msg("Unable to deallocate the lpp_source resource",
#               exit_code=13)
#        else:
#           amd.err_msg("Unable to deallocate the lpp_source  resource")
#        return False
#    
#        # Unix_cmd executed successfully
#    elif rc==0:
#       if verbose >= 1 and not silent:
#           amd.ok_msg("   >>",
#                 local_lpp_source,
#                 "had been deallocated from:", 
#                 args.source_lpar)
#       return True
   
# }}}
    # NIM RESOLV_CONF
def nim_allocate_resolv_conf(client_name, lpp_source, verbose=False, quit=False, silent=False, force=False):# {{{

    """Deallocating a resolv_conf from an lpar: -> bool
    :client_name The name of the lpar
    :lpp_source The name of the lpar
    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool

     UNIX_CMD: 
     nim -o allocate -a resolv_conf=resolvconf s370en0
    """
    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Starting the resolv_conf allocation")

    # Unix_cmd
    local_lpp_source = lpp_source.strip()
    client_name=str(client_name).strip()
    unix_cmd=("nim -o allocate -a resolv_conf="\
            "{} "\
            " {}"
            ).format(resolv_conf_name, client_name)
    
    if verbose >= 2 and not silent:
        amd.info_msg("  unix_cmd is: ", unix_cmd)
    
    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    
        # Unix_cmd has failed
    if rc!=0:
        if quit:
           amd.err_msg("Unable to allocate the resolv_conf resource",
               exit_code=13)
        else:
           amd.err_msg("Unable to allocate the resolv_conf  resource")
        return False
    
        # Unix_cmd executed successfully
    elif rc==0:
       if verbose >= 1 and not silent:
           amd.ok_msg("   >>",
                 resolv_conf_name,
                 "is allocated to:", 
                 args.source_lpar)
       return True
   
# }}}
def nim_deallocate_resolv_conf(client_name, lpp_source, verbose=False, quit=False, silent=False, force=False):# {{{

    """Deallocating a resolv_conf from an lpar: -> bool
    :client_name The name of the lpar
    :lpp_source The name of the lpar
    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool

     UNIX_CMD: 
     nim -o deallocate -a resolv_conf=resolvconf s370en0
    """
    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Starting the resolv_conf deallocation")

    # Unix_cmd
    local_lpp_source = lpp_source.strip()
    client_name=str(client_name).strip()
    unix_cmd=("nim -o deallocate -a resolv_conf="\
            "{} "\
            " {}"
            ).format(resolv_conf_name, client_name)
    
    if verbose >= 2 and not silent:
        amd.info_msg("  unix_cmd is: ", unix_cmd)
    
    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    
#        # Unix_cmd has failed
#    if rc!=0:
#        if quit:
#           amd.err_msg("Unable to deallocate the resolv_conf resource",
#               exit_code=13)
#        else:
#           amd.err_msg("Unable to deallocate the resolv_conf  resource")
#        return False
#    
#        # Unix_cmd executed successfully
#    elif rc==0:
#       if verbose >= 1 and not silent:
#           amd.ok_msg("   >>",
#                 resolv_conf_name,
#                 "had been deallocated from:", 
#                 args.source_lpar)
#       return True
   
# }}}
   # NIM netboot
def get_nim_client_cstate(client_name, verbose=False, quit=False, silent=False, force=False):# {{{

    """Retrieving the current client state
    :client_name The name of the lpar
    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool

     UNIX_CMD: 
     lsnim -a Cstate client_name"""

    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Determining the current state of the client")

    # Unix_cmd
    unix_cmd=("lsnim -a Cstate {}".format(client_name))
    
    if verbose >= 2 and not silent:
        amd.info_msg("  unix_cmd is: ", unix_cmd)
    
    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    
        # Unix_cmd has failed
    if rc!=0:
        if quit:
           amd.err_msg("Unable Identify the current state of the nim client",
               exit_code=13)
        else:
           amd.err_msg("Unable Identify the current state of the nim clien")
        return False
    
        # Unix_cmd executed successfully
    elif rc==0:
        for line in p.stdout:
            if "Cstate" in line:
                current_state=line.split("=")[1].strip()
        if verbose >= 1 and not silent:
            amd.ok_msg("   >> Lpar state is:",current_state)
        return current_state
   
# }}}
def nim_do_initiate_restore(client_name, verbose=False, quit=False, silent=False, force=False):# {{{

    """Peforming NIM unattended BOS installation
    :client_name The name of the lpar
    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool

     UNIX_CMD: 
    nim -o bos_inst -a source=mksysb -a accept_licenses=yes  -a preserve_res=no -a resolv_conf=resolvconf s370en0 """
    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Starting NIM bos_inst operation")

    # Unix_cmd
    bosinst_data_name = "noprompt_data_{}".format(args.source_lpar)
    fb_script_name = "node_firstboot_{}".format(args.source_lpar)
    unix_cmd=("nim -o bos_inst -a source=mksysb -a accept_licenses=yes -a resolv_conf={} -a fb_script={}  -a bosinst_data={} -a no_client_boot=yes"\
            " {}"
            ).format(resolv_conf_name,
                fb_script_name,
                bosinst_data_name,            
                client_name)
    
    if verbose >= 2 and not silent:
        amd.info_msg("  unix_cmd is: ", unix_cmd)
    
    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    
        # Unix_cmd has failed
    if rc!=0:
        if quit:
           amd.err_msg("Unable to perform the nim restore operation",
               exit_code=13)
        else:
           amd.err_msg("Unable to perform the nim restore operation")
        return False
    
        # Unix_cmd executed successfully
    elif rc==0:
       if verbose >= 1 and not silent:
           amd.ok_msg("   >> NIM restore successfully completed")
       return True
   
# }}}
def nim_do_unattended_install(client_name, verbose=False, quit=False, silent=False, force=False):# {{{

    """Peforming NIM unattended BOS installation
    :client_name The name of the lpar
    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool

     UNIX_CMD: 
    nim -o bos_inst -a source=mksysb -a accept_licenses=yes  -a preserve_res=no -a resolv_conf=resolvconf s370en0 """
    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Starting the lpar_netboot operation")

    # Unix_cmd
    resolv_conf_name
    fb_script_name = "node_firstboot_{}".format(args.source_lpar)
    unix_cmd=("nim -o bos_inst -a source=mksysb -a accept_licenses=yes -a resolv_conf={} -a fb_script={}"\
            " {}"
            ).format(resolv_conf_name,
                fb_script_name,
                client_name)
    
    if verbose >= 2 and not silent:
        amd.info_msg("  unix_cmd is: ", unix_cmd)
    
    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    
        # Unix_cmd has failed
    if rc!=0:
        if quit:
           amd.err_msg("Unable to perform the unattended installation",
               exit_code=13)
        else:
           amd.err_msg("Unable to perform the unattended installation")
        return False
    
        # Unix_cmd executed successfully
    elif rc==0:
       if verbose >= 1 and not silent:
           amd.ok_msg("   >> The unattended installation has been started")
       return True
   
# }}}
   # NIM client_ lpar_netboot
def nim_do_unattended_install(hmc, ms, client_name, verbose=False, quit=False, silent=False, force=False):# {{{

    """Peforming NIM unattended BOS installation
    :client_name The name of the lpar
    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bool

     UNIX_CMD: 
     lpar_netboot -T off -d auto -s auto -t ent -m 826FDE2EB302 s370en0 default S04 """

    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    if verbose >= 1 and not silent:
       amd.ok_msg("   >> Starting the lpar_netboot operation")

        
    mac=get_lpar_mac(args.hmc,
        args.destination_managed_system,
        args.source_lpar, 
        quit=True)

    # Unix_cmd
    user = "hscroot"
    opt1="lpar_netboot -T off -d auto -s auto -t ent"
    opt2=" -m {} {} default {}".format(mac, client_name, ms)

    unix_cmd=("ssh "\
            "{}"\
            "@{} "\
            "{}"\
            " {}"\
            ).format(user,hmc, opt1, opt2)
    
    
    if verbose >= 2 and not silent:
        amd.info_msg("  unix_cmd is: ", unix_cmd)
    
    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    
        # Unix_cmd has failed
    if rc!=0:
        if quit:
           amd.err_msg("Unable to perform the unattended installation",
               exit_code=13)
        else:
           amd.err_msg("Unable to perform the unattended installation")
        return False
    
        # Unix_cmd executed successfully
    elif rc==0:
       if verbose >= 1 and not silent:
           amd.ok_msg("   >>The unattended installation has been started")
       return True
   
# }}}






# TARGET LPAR PROCESSING
# LPAR
def get_template(verbose=False, silent=False, quit=False ): # {{{
    """Templating"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])
      

    # Start the validation process
    if verbose and not silent:
        amd.ok_msg("   >> Starting :")


    if verbose >= 1 and not silent:
        amd.ok_msg("   >> Configuration")



# }}}
def get_lpar_string(verbose=False, quit=False, silent=False):# {{{
    """Compiles the target lpar_string -> string """
    pass
# }}}
def get_domain(verbose=False, silent=False, quit=False ): # {{{
    """Determinig the domain of the host/lpar"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])
      

    # Starting the process 
    if verbose and not silent:
        amd.ok_msg("   >> Retrieving the domain name :")

    opt1 = args.source_lpar
    unix_cmd=("host"\
            " {}"\
            ).format(opt1)
    
    if verbose >= 2 and not silent:
       amd.info_msg("  unix_cmd is: ", unix_cmd)
    
    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    
        # Unix_cmd has failed
    if rc!=0:
       if quit:
           amd.err_msg("Unable to retrive the domain name",
                   exit_code=17)
       else:
           return False
    
        # Unix_cmd executed successfully
    elif rc==0:
       for line in p.stdout:
           if "Aliases" in line:
               domain = line.split(" ")[0].strip()
               break

    if domain:
        if verbose >= 1 and not silent:
            amd.ok_msg("   >> Domain name is:", domain)
        return domain
    else:
       if quit:
           amd.err_msg("Unable to retrive the domain name",
                   exit_code=17)
       return False


# }}}

# TARGET MS / BLECH
def is_target_ms(verbose=False, silent=False, quit=False ): # {{{
    """Checks if the Target MS exists or it is defined on the NIM"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])
      

    # Starting the process 
    if verbose and not silent:
        amd.ok_msg("   >> Checking if the Destination MS exits/is configured")

    opt1 = args.destination_managed_system
    unix_cmd=("lsnim "\
            " {}"\
            ).format(opt1)
    
    if verbose >= 2 and not silent:
       amd.info_msg("  unix_cmd is: ", unix_cmd)

    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    is_target_ms = False
        # Unix_cmd has failed
    if rc!=0:
       if quit:
           amd.err_msg("Unable to determine if target MS exists",
                   exit_code=19)
       else:
         return is_target_ms
    
        # Unix_cmd executed successfully
    elif rc==0:
       if verbose >= 1 and not silent:
          amd.ok_msg("   >> Target MS is defined in the NIM env.")
       is_target_ms = True

    return is_target_ms


# }}}
def get_target_ms_serial(verbose=False, silent=False, quit=False ): # {{{
    """ Determines the serial number of the targert managed system"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])
      


    # Checking if the target MS exists/is defined in the NIM server
    is_target_ms(verbose=args.verbose, quit=True)


    # Starting the process 
    if verbose and not silent:
        amd.ok_msg("   >> Retrieving the serial number of the Managed System:")

    opt1 = args.destination_managed_system
    unix_cmd=("lsnim -a serial "\
            " {}"\
            ).format(opt1)
    
    if verbose >= 2 and not silent:
       amd.info_msg("  unix_cmd is: ", unix_cmd)

    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    serial = False    
        # Unix_cmd has failed
    if rc!=0:
       if quit:
           amd.err_msg("Unable to retrieve the serial of the MS",
                   exit_code=18)
       else:
           return False
    
        # Unix_cmd executed successfully
    elif rc==0:
       for line in p.stdout:
           if "serial" in line:
               serial = line.split("=")[1].strip()
               break

    if serial:
        if verbose >= 1 and not silent:
            amd.ok_msg("   >> Target MS serial is: ", serial)
        return serial
    else:
       if quit:
           amd.err_msg("Unable to retrieve the Target Managed System serial nr.",
                   exit_code=18)
       return False


# }}}

# HMC -> LPAR
def is_hmc_accesible(host,user="hscroot", verbose=False, silent=False, quit=False ): # {{{
    """Checking if a host is accessible over ssh"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    is_ssh_accesible(host,
            user,
            verbose=args.verbose,
            quit=True)

# }}}
def is_lpar_in_hmc(hmc, ms, lpar_name, verbose=False, silent=False, quit=False, do_prereq=False ): # {{{
    """Determines if the lpar is configured in HMC/MS: -> bool
    hmc:    Target HMC name
    ms:     Target Managed System
    lpar_name: The name of the lpar: e.g. s134en0"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])
      

    if do_prereq:
        # Checking if the target MS exists/is defined in the NIM server
        is_target_ms(verbose=args.verbose, quit=True)

        # Checking if hmc is accessible
        is_hmc_accesible(args.hmc,
                user="hscroot",
                verbose=args.verbose,
                silent=True,
                quit=True)


    # Starting the process 
    if verbose and not silent:
        amd.ok_msg("   >> Checking if the lpar is already defined/configured\
in the hmc/MS:")

    # lssyscfg -r lpar -m S04 --filter "lpar_names=s134en0"


    user = "hscroot"
    opt1 = "lssyscfg -r lpar -m "
    opt2 = " --filter \"lpar_names={}\"".format(lpar_name)
    unix_cmd=("ssh "\
            "{}"\
            "@{} "\
            "{}"\
            "{}"\
            " {}"\
            ).format(user,hmc, opt1, ms, opt2)
    
    if verbose >= 2 and not silent:
       amd.info_msg("  unix_cmd is: ", unix_cmd)

    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    is_lpar = False    
        # Unix_cmd has failed
    if rc!=0:
        for line in p.stdout:
           if "HSCL8012" in line:
               return is_lpar
           


    
        # Unix_cmd executed successfully
    elif rc==0:
       is_lpar = True

       if verbose >= 2 and not silent:
            for line in p.stdout:
                print line
       if verbose and not silent:
          amd.ok_msg("   >> The LPAR:",args.source_lpar,
                "is already defined in the HMC on MS:", ms)

       return is_lpar




#  }}}
def get_lpar_id(hmc, ms, lpar_name, verbose=False, silent=False, quit=False, do_prereq=False ): # {{{
    """Determines the  LPAR ID available on the MS -> int: lpar_id
    hmc:    Target HMC name
    ms:     Target Managed System
    lpar_name: The name of the lpar: e.g. s134en0
    do_prereq: Check if HMC is accesible, if MS exists"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])
      

    if do_prereq:
        # Checking if the target MS exists/is defined in the NIM server
        is_target_ms(verbose=args.verbose, quit=True)

        # Checking if hmc is accessible
        is_hmc_accesible(args.hmc,
                user="hscroot",
                verbose=args.verbose,
                silent=True,
                quit=True)



    # Starting the process 
    if verbose and not silent:
        amd.ok_msg("   >> Retrieving LPAR ID:")

    # lssyscfg -r lpar -m S04 --filter "lpar_names=s134en0" -F "lpar_id"


    user = "hscroot"
    opt1 = "lssyscfg -r lpar -m "
    opt2 = " --filter \"lpar_names={}\"".format(lpar_name)
    opt3 = "-F \"lpar_id\""
    unix_cmd=("ssh "\
            "{}"\
            "@{} "\
            "{}"\
            "{}"\
            "{}"\
            " {}"\
            ).format(user,hmc, opt1, ms, opt2, opt3)
    
    if verbose >= 2 and not silent:
       amd.info_msg("  unix_cmd is: ", unix_cmd)

    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    lpar_id = False    
        # Unix_cmd has failed
    if rc!=0:
       if quit:
           amd.err_msg("Unable to determine the  LPAR ID",
                   exit_code=21)
       else:
           return False
    
        # Unix_cmd executed successfully
    elif rc==0:
       id_list=[]
       for line in p.stdout:
           id_list.append(line.strip())


    lpar_id = int(id_list[0])
    if not  isinstance(lpar_id, int):
       amd.err_msg("Unable to determine the PAR ID", exit_code=22)
    else:
      if verbose and not silent:
         amd.ok_msg("   >> The  LPAR ID of:",
                 lpar_name,
                 "is:",
                 lpar_id)
      return lpar_id




#  }}}
def get_next_lpar_id(hmc, ms, verbose=False, silent=False, quit=False, do_prereq=False ): # {{{
    """Determines the next LPAR ID available on the MS -> int next_lpar_id
    hmc:    Target HMC name
    ms:     Target Managed System
    do_prereq: Check if HMC is accesible, if MS exists"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])
      

    if do_prereq:
        # Checking if the target MS exists/is defined in the NIM server
        is_target_ms(verbose=args.verbose, quit=True)

        # Checking if hmc is accessible
        is_hmc_accesible(args.hmc,
                user="hscroot",
                verbose=args.verbose,
                silent=True,
                quit=True)


    # Starting the process 
    if verbose and not silent:
        amd.ok_msg("   >> Retrieving the next available LPAR ID:")

    # unix_cmd: ssh hscroot@hmc lssyscfg -r lpar -m ms -F "lpar_id, name"

    user = "hscroot"
    opt1 = "lssyscfg -r lpar -m "
    opt2 = "-F \"lpar_id,name\""
    unix_cmd=("ssh "\
            "{}"\
            "@{} "\
            "{}"\
            "{}"\
            " {}"\
            ).format(user,hmc, opt1, ms, opt2)
    
    if verbose >= 2 and not silent:
       amd.info_msg("  unix_cmd is: ", unix_cmd)

    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    lpar_id = False    
        # Unix_cmd has failed
    if rc!=0:
       if quit:
           amd.err_msg("Unable to determine the next LPAR ID",
                   exit_code=21)
       else:
           return False
    
        # Unix_cmd executed successfully
    elif rc==0:
       id_list=[]
       for line in p.stdout:
           if verbose >= 2 and not silent:
               amd.info_msg("   >> Exiting partitions:", line.strip())

           lp_id=line.split(",",1)
           id_list.append(lp_id[0])

           int_id_list=map(int,id_list)
           max_id=max(int_id_list)
    try:
        next_id=max_id+1
    except Exception as e:
          amd.err_msg("Unable to determine the next LPAR ID", exit_code=21)

    if verbose and not silent:
        amd.ok_msg("   >> The next available LPAR ID is:", next_id)
    return next_id
# }}}




# HMC -> VIOS
    # VIOS PROCESSING DIRECTORY
def get_vios_processing_dir(): # {{{
    """Returns the path of the vios processing directory"""
    dir_path="/csmimages/ssp_migration/"+str.strip(args.source_lpar)+"/vios_data/"
    return dir_path
   
# }}}
def mk_vios_processing_dir(verbose=False, quit=False, silent=False): # {{{
    """Creating the directory where VIOS-LPAR conf data resides
    they are defined:  

    :verbose: Print output if TRUE
    :quit:      quit if TRUE      
    :silent:    silent output if TRUE
    :returns:   bood
            Default location:    /cmsimages/ssp_migration/$node/vios_config/
    """
    if verbose >= 2:
        amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    if verbose >= 2 and not silent:
        amd.ok_msg("Creating VIOS working directory:")

    
        amd.info_msg(get_vios_processing_dir())

    vios_dir = get_vios_processing_dir()
    if os.path.isdir(vios_dir):
      if verbose >= 1 and not silent:
         amd.ok_msg("   >> The VIOS working directory exists")
      return True
    else:
      unix_cmd=("mkdir -p "\
              " {}"\
              ).format(vios_dir)
      
      if verbose >= 2 and not silent:
          amd.info_msg("unix_cmd is: ",
                  unix_cmd)

      p = subprocess.Popen(unix_cmd,\
              shell=True, stdout=subprocess.PIPE,\
              stderr=subprocess.STDOUT)
      rc = p.wait()
      
      
          # Unix_cmd has failed
      if rc!=0:
         return False
      
          # Unix_cmd executed successfully
      elif rc==0:
         if verbose >= 1 and not silent:
           amd.ok_msg("   >> The VIOS working dir has been created.")
         return True
          
   
# }}}
def get_vios_slot_file(): # {{{
    """Returns the path of the vios slots file"""
    vios_dir=get_vios_processing_dir()
    vios_slots_file=vios_dir+"/vios_slots"
    return vios_slots_file
   
# }}}
def get_vios_fcs_file(vios): # {{{
    """Returns the path of the vios fcs file"""
    vios_dir=get_vios_processing_dir()
    vios_fcs_file=vios_dir+"fcs_"+str(vios)
    return vios_fcs_file
   
# }}}
def get_vios_vfchost_file(vios): # {{{
    """Returns the path of the vios vfchost file"""
    vios_dir=get_vios_processing_dir()
    vios_vfchost_file=vios_dir+"vfchost_"+str(vios)
    return vios_vfchost_file
   
# }}}
def get_vios_vhost_file(vios): # {{{
    """Returns the path of the vios vhost file"""
    vios_dir=get_vios_processing_dir()
    vios_vhost_file=vios_dir+"vhost_"+str(vios)
    return vios_vhost_file
   
# }}}

def get_lpar_vios1_slot_file(): # {{{
    """Returns the path of the lpar_vios1_slots file"""
    vios_dir=get_vios_processing_dir()
    lpar_vios1_slots_file=vios_dir+"/lpar_vios1_slots"
    return lpar_vios1_slots_file
   
# }}}
def get_lpar_vios2_slot_file(): # {{{
    """Returns the path of the lpar_vios1_slots file"""
    vios_dir=get_vios_processing_dir()
    lpar_vios2_slots_file=vios_dir+"/lpar_vios2_slots"
    return lpar_vios2_slots_file
   
# }}}


# HMC -> VIOS
def get_vio_a_hostname(verbose=False,silent=False): # {{{
    """Returns the hostname of the vios_A -> str:"""

    l_ms = args.destination_managed_system.lower()
    vios_a_hostname = l_ms+"vp1en0"

    if verbose >= 1 and not silent:
       amd.ok_msg("   >> VIOS_A hostname is: ", vios_a_hostname)


    return vios_a_hostname
# }}}
def get_vio_b_hostname(verbose=False,silent=False): # {{{
    """Returns the hostname of the vios_A -> str:"""

    l_ms = args.destination_managed_system.lower()
    vios_a_hostname = l_ms+"vp2en0"

    if verbose >= 1 and not silent:
       amd.ok_msg("   >> VIOS_B hostname is: ", vios_a_hostname)


    return vios_a_hostname
# }}}
def get_vios_id(hmc, ms, vios_name, verbose=False, silent=False, quit=False, do_prereq=False ): # {{{
    """Determines the  VIOS ID available on the MS -> int: lpar_id
    hmc:    Target HMC name
    ms:     Target Managed System
    vios_name: The name of the lpar: e.g. s134en0
    do_prereq: Check if HMC is accesible, if MS exists"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])
      

    if do_prereq:
        # Checking if the target MS exists/is defined in the NIM server
        is_target_ms(verbose=args.verbose, quit=True)

        # Checking if hmc is accessible
        is_hmc_accesible(args.hmc,
                user="hscroot",
                verbose=args.verbose,
                silent=True,
                quit=True)

    # lssyscfg -r lpar -m S04 --filter "vios_names=s04vp1en0" -F "lpar_id"

    user = "hscroot"
    opt1 = "lssyscfg -r lpar -m "
    opt2 = " --filter \"lpar_names={}\"".format(vios_name)
    opt3 = "-F \"lpar_id\""
    unix_cmd=("ssh "\
            "{}"\
            "@{} "\
            "{}"\
            "{}"\
            "{}"\
            " {}"\
            ).format(user,hmc, opt1, ms, opt2, opt3)
    
    if verbose >= 2 and not silent:
       amd.info_msg("  unix_cmd is: ", unix_cmd)

    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
        # Unix_cmd has failed
    if rc!=0:
       if quit:
           amd.err_msg("Unable to determine the  VIOS ID",
                   exit_code=23)
       else:
           return False
    
        # Unix_cmd executed successfully
    elif rc==0:
       id_list=[]
       for line in p.stdout:
           id_list.append(line[0].strip())


    vios_id = int(id_list[0])
    if not  isinstance(vios_id, int):
       amd.err_msg("Unable to determine the VIOS ID", exit_code=23)
    else:
      if verbose and not silent:
         amd.ok_msg("   >> The  VIOS ID of:",
                 vios_name,
                 "is:",
                 vios_id)
    return vios_id

#  }}}
def is_ssh_accesible(host, user="root", verbose=False, silent=False, quit=False ): # {{{
    """Checking if a host is accessible over ssh"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    # Starting the process 
    if verbose and not silent:
        amd.ok_msg("   >> Checking if:", host, ": is accessible over ssh")
    
    unix_cmd=("ssh "\
            " {}@"\
            "{}"\
            " exit"\
            ).format(user, host)
    
    if verbose >= 2 and not silent:
       amd.info_msg("  unix_cmd is: ", unix_cmd)

    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
        # Unix_cmd has failed
    if rc!=0:
       if quit:
           amd.err_msg("   >> Host:",host,"cannot be reached over ssh", exit_code=20)
       else:
           return False
    
        # Unix_cmd executed successfully
    elif rc==0:
       if verbose and not silent:
         amd.ok_msg("   >> Host:",host,"is reachable over ssh")
       return True


# }}}
def get_eth_slot_ids(hmc, ms, verbose=False, silent=False, quit=False, do_prereq=False): # {{{
    """Determines the eth slot ids -> list: eth_slot_ids
    hmc:    Target HMC name
    ms:     Target Managed System
    do_prereq: Check if HMC is accessible, if MS exists"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])
      

    if do_prereq:
        # Checking if the target MS exists/is defined in the NIM server
        is_target_ms(verbose=args.verbose, quit=True)

        # Checking if hmc is accessible
        is_hmc_accesible(args.hmc,
                user="hscroot",
                verbose=args.verbose,
                silent=True,
                quit=True)


    # Starting the process 
    if verbose and not silent:
        amd.ok_msg("   >> Retrieving the eth slots IDs:")

    # unix_cmd: ssh hscroot@hmc lssyscfg -r lpar -m ms -F "lpar_id, name"

    user = "hscroot"
    opt1 = "lshwres -r virtualio --rsubtype eth -m "
    opt2 = "--level lpar -F slot_num"
    unix_cmd=("ssh "\
            "{}"\
            "@{} "\
            "{}"\
            "{}"\
            " {}"\
            ).format(user,hmc, opt1, ms, opt2)
    
    eth_slot_ids_list=[]
    non_uniq_list=[]

    if verbose >= 2 and not silent:
       amd.info_msg("  unix_cmd is: ", unix_cmd)

    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    lpar_id = False    
        # Unix_cmd has failed
    if rc!=0:
       if quit:
           amd.err_msg("Unable to determine the eth SLOT IDs",
                   exit_code=23)
       else:
           return False
    
        # Unix_cmd executed successfully
    elif rc==0:
        for line in p.stdout:
           non_uniq_list.append(line.strip())

        eth_slot_ids_list = list(set(non_uniq_list))
        eth_slot_ids_list =  [ int(x) for x in eth_slot_ids_list ]
        eth_slot_ids_list.sort()
        if verbose >= 2 and not silent:
           amd.info_msg("   >> eth IDs", eth_slot_ids_list )

    if verbose  and not silent:
        amd.ok_msg("   >> Retrieved the eth slots IDs:")

    return eth_slot_ids_list
# }}}
def get_scsi_slot_ids(hmc, ms, verbose=False, silent=False, quit=False, do_prereq=False): # {{{
    """Determines the scsi slot ids -> list: scsi_slot_ids
    hmc:    Target HMC name
    ms:     Target Managed System
    do_prereq: Check if HMC is accessible, if MS exists"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])
      

    if do_prereq:
        # Checking if the target MS exists/is defined in the NIM server
        is_target_ms(verbose=args.verbose, quit=True)

        # Checking if hmc is accessible
        is_hmc_accesible(args.hmc,
                user="hscroot",
                verbose=args.verbose,
                silent=True,
                quit=True)


    # Starting the process 
    if verbose and not silent:
        amd.ok_msg("   >> Retrieving the scsi slots IDs:")

    # unix_cmd: ssh hscroot@hmc lssyscfg -r lpar -m ms -F "lpar_id, name"

    user = "hscroot"
    opt1 = "lshwres -r virtualio --rsubtype scsi -m "
    opt2 = "--level lpar -F slot_num"
    unix_cmd=("ssh "\
            "{}"\
            "@{} "\
            "{}"\
            "{}"\
            " {}"\
            ).format(user,hmc, opt1, ms, opt2)
    
    scsi_slot_ids_list=[]
    non_uniq_list=[]

    if verbose >= 2 and not silent:
       amd.info_msg("  unix_cmd is: ", unix_cmd)

    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    lpar_id = False    
        # Unix_cmd has failed
    if rc!=0:
       if quit:
           amd.err_msg("Unable to determine the scsi SLOT IDs",
                   exit_code=23)
       else:
           return False
    
        # Unix_cmd executed successfully
    elif rc==0:
        for line in p.stdout:
            if "No results were found" in line:
                # No results means that this is the first lpar. 
                # I'm adding 9 into this list so that the mapping can begin from 10
                non_uniq_list.append(9)
            else:
               non_uniq_list.append(line.strip())

        scsi_slot_ids_list = list(set(non_uniq_list))
        scsi_slot_ids_list =  [ int(x) for x in scsi_slot_ids_list ]
        scsi_slot_ids_list.sort()
        if verbose >= 2 and not silent:
           amd.info_msg("   >> SCSI IDs", scsi_slot_ids_list )

    if verbose and not silent:
        amd.ok_msg("   >> Retrieved the scsi slots IDs:")

    return scsi_slot_ids_list
# }}}
def get_fc_slot_ids(hmc, ms, verbose=False, silent=False, quit=False, do_prereq=False): # {{{
    """Determines the FC slot ids -> list: fc_slot_ids
    hmc:    Target HMC name
    ms:     Target Managed System
    do_prereq: Check if HMC is accessible, if MS exists"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])
      

    if do_prereq:
        # Checking if the target MS exists/is defined in the NIM server
        is_target_ms(verbose=args.verbose, quit=True)

        # Checking if hmc is accessible
        is_hmc_accesible(args.hmc,
                user="hscroot",
                verbose=args.verbose,
                silent=True,
                quit=True)


    # Starting the process 
    if verbose and not silent:
        amd.ok_msg("   >> Retrieving the FC slots IDs:")

    # unix_cmd: ssh hscroot@hmc lssyscfg -r lpar -m ms -F "lpar_id, name"

    user = "hscroot"
    opt1 = "lshwres -r virtualio --rsubtype fc -m "
    opt2 = "--level lpar -F slot_num"
    unix_cmd=("ssh "\
            "{}"\
            "@{} "\
            "{}"\
            "{}"\
            " {}"\
            ).format(user,hmc, opt1, ms, opt2)
    
    fc_slot_ids_list=[]
    non_uniq_list=[]

    if verbose >= 2 and not silent:
       amd.info_msg("  unix_cmd is: ", unix_cmd)

    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
    lpar_id = False    
        # Unix_cmd has failed
    if rc!=0:
       if quit:
           amd.err_msg("Unable to determine the scsi SLOT IDs",
                   exit_code=23)
       else:
           return False
    
        # Unix_cmd executed successfully
    elif rc==0:
        for line in p.stdout:
            if "No results were found" in line:
                # No results means that this is the first lpar. 
                # I'm adding 9 into this list so that the mapping can begin from 10
                non_uniq_list.append(9)
            else:
               non_uniq_list.append(line.strip())

        fc_slot_ids_list = list(set(non_uniq_list))
        fc_slot_ids_list =  [ int(x) for x in fc_slot_ids_list ]
        fc_slot_ids_list.sort()
        if verbose >= 2 and not silent:
           amd.info_msg("   >> The FC  IDs", fc_slot_ids_list )

    if verbose and not silent:
        amd.ok_msg("   >> Retrieved the FC slots IDs:")

    return fc_slot_ids_list
# }}}
def get_next_slot_id(eth_list, scsi_list, fc_list, verbose=False, silent=False, quit=False, do_prereq=False): # {{{
    """Determines the last slot id -> int: last_slot_id
    hmc:    Target HMC name
    ms:     Target Managed System
    do_prereq: Check if HMC is accessible, if MS exists"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])
      

    if do_prereq:
        # Checking if the target MS exists/is defined in the NIM server
        is_target_ms(verbose=args.verbose, quit=True)

        # Checking if hmc is accessible
        is_hmc_accesible(args.hmc,
                user="hscroot",
                verbose=args.verbose,
                silent=True,
                quit=True)

    all_slot_ids_list=[]

    all_slot_ids_list += eth_list
    all_slot_ids_list += scsi_list
    all_slot_ids_list += fc_list

    all_slot_ids_list =  [ int(x) for x in all_slot_ids_list ]
    all_slot_ids_list.sort(reverse=True)
    next_slot_id =  all_slot_ids_list[0]+1



    # Starting the process 
    if verbose and not silent:
        amd.ok_msg("   >> Determining the next available slot ID:")


    if verbose and not silent:
        amd.ok_msg("   >> Next available slot ID:", next_slot_id)


    vio_a=get_vio_a_hostname(silent=True)
    vio_b=get_vio_b_hostname(silent=True)
    root_vg_slot_id = next_slot_id
    datavg1_slot_id = next_slot_id+1
    datavg2_slot_id = next_slot_id+2

    if verbose and not silent:
        amd.info2_msg("   Slot allocation to be used:")
        amd.info2_msg("   VSCSI:rootvg", vio_a, ",", vio_b ,
                "SLOT:",next_slot_id, "--->",args.source_lpar,"SLOTS: 5,6")

        amd.info2_msg("   FC:datavg1", vio_a, ",", vio_b ,
                "SLOT:",datavg1_slot_id, "--->",args.source_lpar,"SLOTS: 7,9")

        amd.info2_msg("   FC:datavg2", vio_a, ",", vio_b ,
                "SLOT:",datavg2_slot_id, "--->",args.source_lpar,"SLOTS: 8,10")


    # Writing slots to files# {{{
        # Writing VIOS slots to file
    vios_slot_file=get_vios_slot_file()
    with open(vios_slot_file,'w') as f:
       # Append with a new line
       f.write("rootvg "+str(next_slot_id)+ "\n")
       f.write("datavg1 "+str(datavg1_slot_id)+ "\n")
       f.write("datavg2 "+str(datavg2_slot_id) + "\n")
    f.close()


        # Writing LPAR to VIOS1 slots to file
    lpar_vios1_slots_file=get_lpar_vios1_slot_file()
    with open(lpar_vios1_slots_file,'w') as f:
       # Append with a new line
       f.write("rootvg "+ str(root_vg_slot_a)+"\n")
       f.write("datavg1 "+ str(data_vg1_slot_a)+"\n")
       f.write("datavg2 "+str(data_vg2_slot_a)+"\n")
    f.close()


        # Writing LPAR to VIOS2 slots to file
    lpar_vios2_slots_file=get_lpar_vios2_slot_file()
    with open(lpar_vios2_slots_file,'w') as f:
       # Append with a new line
       f.write("rootvg "+ str(root_vg_slot_b)+"\n")
       f.write("datavg1 "+ str(data_vg1_slot_b)+"\n")
       f.write("datavg2 "+str(data_vg2_slot_b)+"\n")
    f.close()


# }}}


    return next_slot_id
# }}}
def compile_lpar_profile_string(hmc, ms, next_slot_id, next_lpar_id, verbose=False, silent=False, quit=False, do_prereq=False): # {{{
    """Compiling the Profile String -> str: string
    hmc:    Target HMC name
    ms:     Target Managed System
    do_prereq: Check if HMC is accessible, if MS exists"""
# V2 {{{
    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])
      # }}}
# Do prereq if necessarily# {{{
    if do_prereq:
        # Checking if the target MS exists/is defined in the NIM server
        is_target_ms(verbose=args.verbose, quit=True)

        # Checking if hmc is accessible
        is_hmc_accesible(args.hmc,
                user="hscroot",
                verbose=args.verbose,
                silent=True,
                quit=True)
# }}}
# V1 {{{
    # Starting the process 
    if verbose and not silent:
        amd.ok_msg("   >> Compiling the LPAR profile string:")
# }}}
# Variable collection	# {{{
    vios_a_hostname=get_vio_a_hostname(silent=True)
    vios_b_hostname=get_vio_b_hostname(silent=True)


    vios_a_id=get_vios_id(args.hmc,
       args.destination_managed_system,
       get_vio_a_hostname(silent=True),
       verbose=args.verbose,
       silent=True,
       quit=True) 

    vios_b_id=get_vios_id(args.hmc,
       args.destination_managed_system,
       get_vio_b_hostname(silent=True),
       verbose=args.verbose,
       silent=True,
       quit=True) 

    node_conf_dic= get_node_conf_options_dic(get_node_conf_path(),
              silent=True, quit=True)

#     print node_conf_dic

    node_wwws_dic= get_wwns_conf_options_dic(get_wwns_conf_path(),
              silent=True, quit=True)

#     print node_wwws_dic

    # LPAR SLOTS as of 01-06-2018
    eth_slot_a=2
    eth_slot_b=3
    eth_slot_c=4

    root_vg_slot_a=5
    root_vg_slot_b=6

    data_vg1_slot_a=7
    data_vg1_slot_b=9

    data_vg2_slot_a=8
    data_vg2_slot_b=10

# }}}
# Copmpiling  the profile string -> profile_string # {{{
    profile_string=""
    #--- The default options for building the partition
    profile_string +="profile_name=default,"
    profile_string +="name={},".format(args.source_lpar)
    profile_string +="lpar_id={},".format(next_lpar_id)
    profile_string +="lpar_env=aixlinux,"
    profile_string +="all_resources=0,"
    profile_string +="allow_perf_collection=1,"
    profile_string +="min_mem={},".format(node_conf_dic['LPAR_MEM_MIN'])
    profile_string +="desired_mem={},".format(node_conf_dic['LPAR_MEM_DES'])
    profile_string +="max_mem={},".format(node_conf_dic['LPAR_MEM_MAX'])
    profile_string +="min_num_huge_pages=0,"
    profile_string +="desired_num_huge_pages=0,"
    profile_string +="max_num_huge_pages=0,"
    profile_string +="mem_mode=ded,"
    profile_string +="proc_mode=shared,"
    profile_string +="min_proc_units={},".\
          format(node_conf_dic['LPAR_PROC_UNITS_MIN'])
    profile_string +="desired_proc_units={},".\
          format(node_conf_dic['LPAR_PROC_UNITS_DES'])
    profile_string +="max_proc_units={},".\
          format(node_conf_dic['LPAR_PROC_UNITS_MAX'])
    profile_string +="min_procs={},".\
          format(node_conf_dic['LPAR_PROC_MIN'])
    profile_string +="desired_procs={},".\
          format(node_conf_dic['LPAR_PROC_DES'])
    profile_string +="max_procs={},".\
          format(node_conf_dic['LPAR_PROC_MAX'])
    profile_string +="sharing_mode={},".\
          format(node_conf_dic['LPAR_SHARING_MODE'])
    profile_string +="uncap_weight=128,"
    profile_string +="shared_proc_pool_id=1,"
    profile_string +="io_slots=none,"
    profile_string +="lpar_io_pool_ids=none,"
    profile_string +="max_virtual_slots=3250,"

    # VSCSI
    profile_string +="\\\\\\\"virtual_scsi_adapters="
    profile_string +="{}/client/{}/{}/{}/0,".\
    format(root_vg_slot_a,vios_a_id, vios_a_hostname, next_slot_id)
    profile_string +="{}/client/{}/{}/{}/0\\\\\\\",".\
    format(root_vg_slot_b, vios_b_id, vios_b_hostname, next_slot_id)

   # ETH
    profile_string +="\\\\\\\"virtual_eth_adapters="
    profile_string +="{}/0/{}//0/0/ETHERNET0,".\
    format(eth_slot_a, node_conf_dic['VLANA'])
    profile_string +="{}/0/{}//0/0/ETHERNET0,".\
    format(eth_slot_b, node_conf_dic['VLANB'])
    profile_string +="{}/0/{}//0/0/ETHERNET0".\
    format(eth_slot_c, node_conf_dic['VLANC'])
    profile_string +="\\\\\\\","

    profile_string +="hca_adapters=none,"
    profile_string +="boot_mode=norm,"
    profile_string +="conn_monitoring=0,"
    profile_string +="auto_start=0,"
    profile_string +="power_ctrl_lpar_ids=none,"
    profile_string +="work_group_id=none,"

    # AME FACTOR    
    ###########################
    profile_string +="mem_expansion={},".\
          format(node_conf_dic['LPAR_AME_FACTOR'])
    ###########################

    profile_string +="lhea_logical_ports=none,"
    profile_string +="lhea_capabilities=none,"
    profile_string +="lpar_proc_compat_mode=default,"
      #  FC/WWN
    profile_string +="\\\\\\\"virtual_fc_adapters="
    profile_string +="\\\\\\\"\\\\\\\"{}/client/{}/{}/{}/{}/0\\\\\\\"\\\\\\\",".\
    format(data_vg1_slot_a,vios_a_id, vios_a_hostname, next_slot_id+1, node_wwws_dic['WWN2'])
    profile_string +="\\\\\\\"\\\\\\\"{}/client/{}/{}/{}/{}/0\\\\\\\"\\\\\\\",".\
    format(data_vg1_slot_b,vios_b_id, vios_b_hostname, next_slot_id+1, node_wwws_dic['WWN3'])

    profile_string +="\\\\\\\"\\\\\\\"{}/client/{}/{}/{}/{}/0\\\\\\\"\\\\\\\",".\
    format(data_vg2_slot_a,vios_a_id, vios_a_hostname, next_slot_id+2, node_wwws_dic['WWN6'])
    profile_string +="\\\\\\\"\\\\\\\"{}/client/{}/{}/{}/{}/0\\\\\\\"\\\\\\\"".\
    format(data_vg2_slot_b,vios_b_id, vios_b_hostname, next_slot_id+2, node_wwws_dic['WWN7'])
    profile_string +="\\\\\\\""

    amd.ok_msg("   >> The profile string is ready:")

# V2 {{{
    if verbose >=2  and not silent:
        amd.ok_msg("   >> lpar profile string:", profile_string)
# }}}

# }}}
    return profile_string

# }}}
def create_target_lpar(hmc, ms, next_slot_id, next_lpar_id, verbose=False, silent=False, quit=False, do_prereq=False): # {{{
    """Creating the target LPAR or partition
    hmc:    Target HMC name
    ms:     Target Managed System
    do_prereq: Check if HMC is accessible, if MS exists"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    profile_string=compile_lpar_profile_string(args.hmc,
        args.destination_managed_system,
        next_slot_id,
        next_lpar_id,
        verbose=verbose,
        quit=True)

    print ""
    print profile_string
    print ""

    amd.ok_msg("   >> Creating partition:",args.source_lpar,
            "on:", args.destination_managed_system)

    user = "hscroot"
    opt1 = "mksyscfg -r lpar -m "
    unix_cmd=("ssh "\
            "{}"\
            "@{} "\
            "{}"\
            "{}"\
            " -i \" {} \""\
            ).format(user,hmc, opt1, ms, profile_string)
    

    if verbose >= 2 and not silent:
       amd.info_msg("  unix_cmd is: ", unix_cmd)

    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
        # Unix_cmd has failed
    if rc!=0:
        if verbose >= 2 and not silent:
            for line in p.stdout:
                print line.strip()

        if quit:
           amd.err_msg("Unable to create the LPAR/partition",
                   exit_code=25)
        else:
           return False
    
        # Unix_cmd executed successfully
    elif rc==0:
        if verbose >= 2 and not silent:
            for line in p.stdout:
                print line.strip()

        if verbose and not silent:
            amd.ok_msg("   >> The partition has been created:")

        return True

# }}}


# VIOS VIOS VIOS 
   # LU, LOGICAL UNIT rootvg
def get_rootvg_lu_name(lpar_name): # {{{
    """Returns the name of the Logical Unit used by rootvg : str 
    e.g. s370_rvg
    return str: 
    """
    rootvg_lu_name = lpar_name[0:4]+"_rvg"
    return rootvg_lu_name

   
# }}}
def is_rootvg_lu(vios, lpar_name, verbose=False, silent=False, quit=True, do_prereq=False): # {{{
    """Check if the Logical Unit exists
    vios: vios hostname
    lpar_name : the name of the lpar
    $cmd="ssh padmin\@$VIO_A ioscli lu -list |grep $LU";
    do_prereq: Check if HMC is accessible, if MS exists"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    is_rootvg_lu=False
    rootvg_lu_name=get_rootvg_lu_name(lpar_name)

    user = "padmin"
    opt1 = " ioscli lu -list "

    unix_cmd=("ssh "\
            "{}"\
            "@{} "\
            "{}"\
            ).format(user,
                  vios,
                  opt1)
    
    if verbose >= 2 and not silent:
       amd.info_msg("  unix_cmd is: ", unix_cmd)

    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
        # Unix_cmd has failed
    if rc!=0:
        if verbose >= 2 and not silent:
            for line in p.stdout:
                print line.strip()

        if quit:
            amd.err_msg("Unable to determine if ", rootvg_lu_name, "exists:",
                   exit_code=27)
        else:
           return False
    
        # Unix_cmd executed successfully

    elif rc==0:
       for line in p.stdout:
           if rootvg_lu_name in line:
               is_rootvg_lu = True
               break

    if is_rootvg_lu:
       if verbose and not silent:
           amd.ok_msg("   >> Logical Unit servicing the rootvg exists:", 
             rootvg_lu_name)
  
    return is_rootvg_lu
    

# }}}
def mk_rootvg_lu(vios, lpar_name, verbose=False, silent=False, quit=True, do_prereq=False): # {{{
    """Create the rotovg Logical Unit
    vios: vios hostname
    lpar_name : the name of the lpar
    cmdd="ssh padmin\@$VIO_A \"ioscli mkbdsp -clustername SSPFFM01 -sp SSPFFM01 100G -bd $LU \"   " ;
    do_prereq: Check if HMC is accessible, if MS exists"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    rootvg_lu_name=get_rootvg_lu_name(lpar_name)

    user = "padmin"
    opt1 = " ioscli mkbdsp -clustername SSPFFM01 -sp SSPFFM01 122880M -bd {} "\
            .format(rootvg_lu_name)

    unix_cmd=("ssh "\
            "{}"\
            "@{} "\
            "{}"\
            ).format(user,
                  vios,
                  opt1)
    
    if verbose >= 2 and not silent:
       amd.info_msg("  unix_cmd is: ", unix_cmd)

    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
        # Unix_cmd has failed
    if rc!=0:
        if verbose >= 2 and not silent:
            for line in p.stdout:
                print line.strip()

        if quit:
           amd.err_msg("Unable to create", rootvg_lu_name,
                   exit_code=27)
        else:
           return False
    
        # Unix_cmd executed successfully
    elif rc==0:
       if verbose and not silent:
          amd.ok_msg("   >> Successfully created the Logical Unit:", 
             rootvg_lu_name)
       return True

# }}}
   # UPDATE VIOS_PROFILE
def update_vios_scsi_profile(hmc, ms, lpar_vsci_slot_id, lpar_id, vios_id, vios_slot_id,  verbose=False, silent=False, quit=False, do_prereq=False): # {{{
    """Updating the VIOSs profiles to integrate the SCSI slots
    hmc:    Target HMC name
    ms:     Target Managed System
    lpar_vsci_slot_id: The slot id of the lpar : 5 by default
    lpar_id : The lpar_id of the lpar. determined by get_next_lpar_id
    vios_id : The ID of the VIOS usually eigher 1 or 2
    vios_slot_id: The slot id of the vios. Usually this is equal to nex_slot  id
    do_prereq: Check if HMC is accessible, if MS exists"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


# Compiling  the profile string -> profile_string # {{{
    profile_string=""

# Example commands# {{{
#  cmd: chsyscfg -r prof -m S02 -i \'name=default_profile,lpar_id=1,\"virtual_scsi_adapters+=28/server/8/s372en0/5/0\"\'
#  virtual_scsi_adapters=<slot_num>/<adapter_type>/[<remote_lpar_id>]/[<remote_lpar_name>]/[<remote_slot_num>]/<is_required>,.""
# my $cmd=" ssh hscroot\@$HMC chsyscfg -m $BLECH -r prof -i \\'name=default_profile,lpar_id=$VIO_ID,\\\"virtual_scsi_adapters+=$ADAPTERSTRING\\\"\\' --force";
# }}}

    profile_string +="name=default_profile,"
    profile_string +="lpar_id={},".format(vios_id)
    


#   profile_string +="{vios_slot_id}/server/{lpar_id}/{lpar_name}/{lpar_slot_nr}/0,".\

    profile_string +="\\\\\\\"virtual_scsi_adapters+="
    profile_string +="{}/server/{}/{}/{}/0".\
    format(vios_slot_id, lpar_id, args.source_lpar, lpar_vsci_slot_id)
    profile_string +="\\\\\\\""

    if verbose  and not silent:
       amd.ok_msg("   >> VIOS:",vios_id, "virtual_scsi_adapters profile string is ready:")


# V2 {{{
    if verbose >=2  and not silent:
       amd.ok_msg("   >> VIOS:  SCSI profile string:", profile_string)
# }}}

# }}}

    user = "hscroot"
    opt1 = "chsyscfg -r prof -m "
    unix_cmd=("ssh "\
            "{}"\
            "@{} "\
            "{}"\
            "{}"\
            " -i \\\\\"{} --force\\\\\"" \
            ).format(user,hmc, opt1, ms, profile_string)
    

    if verbose >= 2 and not silent:
       amd.info_msg("  unix_cmd is: ", unix_cmd)

    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
        # Unix_cmd has failed
    if rc!=0:
        if verbose >= 2 and not silent:
            for line in p.stdout:
                print line.strip()

        if quit:
           amd.err_msg("Unable to update the VIOS profile",
                   exit_code=27)
        else:
           return False
    
        # Unix_cmd executed successfully
    elif rc==0:
        if verbose >= 2 and not silent:
            for line in p.stdout:
                print line.strip()

        if verbose and not silent:
           amd.ok_msg("   >> SCSI profile successfully updated for VIOS:", vios_id)

        return True

# }}}
def update_vios_FC_profile(hmc, ms, lpar_slot_id_1, lpar_slot_id_2, lpar_id, vios_id, next_slot_id,  verbose=False, silent=False, quit=False, do_prereq=False): # {{{
    """Updating the VIOSs profiles to integrate the FC slots
    hmc:    Target HMC name
    ms:     Target Managed System
    data_vg1_slot_a : Lpar slot id : 
    lpar_slot_id_1 : Lpar slot id : usually 7 or 9
    lpar_slot_id_2 : Lpar slot id : usually 8 or 10
    lpar_vsci_slot_id: The slot id of the lpar : 5 by default
    lpar_id : The lpar_id of the lpar. determined by get_next_lpar_id
    vios_id : The ID of the VIOS usually eigher 1 or 2
    next_slot_id: VIOS slot id based on the previously determined next_slot_id value
    do_prereq: Check if HMC is accessible, if MS exists"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


# Compiling  the profile string -> profile_string # {{{
    #  ssh hscroot@hmc11en0 chsyscfg -m I23 -r prof -i \'name=default_profile,lpar_id=1,\"virtual_fc_adapters=100/server/100//100//1,300/server/100//300//1\"\'
    
# virtual-slot-number/client-or-server/ 
# [remote-lpar-ID]/[remote-lpar-name]/ 
# remote-slot-number/[wwpns]/is-required



    vios_slot_datavg1=next_slot_id+1
    vios_slot_datavg2=next_slot_id+2

    profile_string=""

# Example commands# {{{
#  cmd: chsyscfg -r prof -m S02 -i \'name=default_profile,lpar_id=1,\"virtual_scsi_adapters+=28/server/8/s372en0/5/0\"\'
#  virtual_scsi_adapters=<slot_num>/<adapter_type>/[<remote_lpar_id>]/[<remote_lpar_name>]/[<remote_slot_num>]/<is_required>,.""
# my $cmd=" ssh hscroot\@$HMC chsyscfg -m $BLECH -r prof -i \\'name=default_profile,lpar_id=$VIO_ID,\\\"virtual_scsi_adapters+=$ADAPTERSTRING\\\"\\' --force";
# }}}

    profile_string +="name=default_profile,"
    profile_string +="lpar_id={},".format(vios_id)
    


# \"virtual_fc_adapters=100/server/100//100//1,300/server/100//300//1\"\'
# \"virtual_fc_adapters=13/server/4/s370en0/7//0,14/server/4/s370en0/8//0\"\'

    profile_string +="\\\\\\\"virtual_fc_adapters+="
    profile_string +="{}/server/{}/{}/{}//0,".\
    format(vios_slot_datavg1, lpar_id, args.source_lpar, lpar_slot_id_1)
    profile_string +="{}/server/{}/{}/{}//0".\
    format(vios_slot_datavg2, lpar_id, args.source_lpar, lpar_slot_id_2)
    profile_string +="\\\\\\\""

    if verbose  and not silent:
       amd.ok_msg("   >> VIOS:",vios_id, "virtual_FC_adapters profile string is ready:")


# V2 {{{
    if verbose >=2  and not silent:
       amd.ok_msg("   >> VIOS:  FC profile string:", profile_string)
# }}}

# }}}

    user = "hscroot"
    opt1 = "chsyscfg -r prof -m "
    unix_cmd=("ssh "\
            "{}"\
            "@{} "\
            "{}"\
            "{}"\
            " -i \\\\\"{} --force\\\\\"" \
            ).format(user,hmc, opt1, ms, profile_string)
    

    if verbose >= 2 and not silent:
       amd.info_msg("  unix_cmd is: ", unix_cmd)

    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
        # Unix_cmd has failed
    if rc!=0:
        if verbose >= 2 and not silent:
            for line in p.stdout:
                print line.strip()

        if quit:
           amd.err_msg("Unable to update the VIOS profile",
                   exit_code=29)
        else:
           return False
    
        # Unix_cmd executed successfully
    elif rc==0:
        if verbose >= 2 and not silent:
            for line in p.stdout:
                print line.strip()

        if verbose and not silent:
           amd.ok_msg("   >> SCSI profile successfully updated for VIOS:", vios_id)

        return True

# }}}
   # DLPAR
def dlpar_scsi_slot_mapping(hmc, ms, lpar_vsci_slot_id, lpar_id, vios_id, vios_slot_id,  verbose=False, silent=False, quit=False, do_prereq=False): # {{{
    """Performing dlpar for scsi
    hmc:    Target HMC name
    ms:     Target Managed System
    lpar_vsci_slot_id: The slot id of the lpar : 5 by default
    lpar_id : The lpar_id of the lpar. determined by get_next_lpar_id
    vios_id : The ID of the VIOS usually eigher 1 or 2
    vios_slot_id: The slot id of the vios. Usually this is equal to nex_slot  id
    do_prereq: Check if HMC is accessible, if MS exists"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    user = "hscroot"
    opt1 = "chhwres -r virtualio --rsubtype scsi"
    unix_cmd=("ssh "\
            "{}"\
            "@{} "\
            "{}"\
            " -m {}"\
            " -o a"\
            " --id {}"\
            " -s {}"\
            " -a remote_slot_num={},"\
            " remote_lpar_id={},"\
            " adapter_type=server"\
            " "
            ).format(user,
                  hmc,
                  opt1,
                  ms,
                  vios_id,
                  vios_slot_id,
                  lpar_vsci_slot_id,
                  lpar_id)
    

    if verbose >= 2 and not silent:
       amd.info_msg("  unix_cmd is: ", unix_cmd)

    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
        # Unix_cmd has failed
    if rc!=0:
        if verbose >= 2 and not silent:
            for line in p.stdout:
                print line.strip()

        if quit:
           amd.err_msg("Unable to perform the scsi mappings",
                   exit_code=27)
        else:
           return False
    
        # Unix_cmd executed successfully
    elif rc==0:
        if verbose >= 2 and not silent:
            for line in p.stdout:
                print line.strip()

        if verbose and not silent:
           amd.ok_msg("   >> SCSI mappings are in place for VIOS:", vios_id,": ",
                 vios_slot_id, "-->", lpar_vsci_slot_id)
        return True

# }}}
def dlpar_FC_slot_mapping(hmc, ms, lpar_fc_slot_id, lpar_id, vios_id, vios_slot_id,  verbose=False, silent=False, quit=False, do_prereq=False): # {{{
    """performing dlpar for FC
    hmc:    Target HMC name
    ms:     Target Managed System
    lpar_fc_slot_id: The slot id of the lpar : 5 by default
    lpar_id : The lpar_id of the lpar. determined by get_next_lpar_id
    vios_id : The ID of the VIOS usually either 1 or 2
    vios_slot_id: The slot id of the vios. Usually this is equal to nex_slot  id
    do_prereq: Check if HMC is accessible, if MS exists"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    user = "hscroot"
    opt1 = "chhwres -r virtualio --rsubtype fc"
    unix_cmd=("ssh "\
            "{}"\
            "@{} "\
            "{}"\
            " -m {}"\
            " -o a"\
            " --id {}"\
            " -s {}"\
            " -a remote_slot_num={},"\
            " remote_lpar_id={},"\
            " adapter_type=server"\
            " "
            ).format(user,
                  hmc,
                  opt1,
                  ms,
                  vios_id,
                  vios_slot_id,
                  lpar_fc_slot_id,
                  lpar_id)
    

    if verbose >= 2 and not silent:
       amd.info_msg("  unix_cmd is: ", unix_cmd)

    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
        # Unix_cmd has failed
    if rc!=0:
        if verbose >= 2 and not silent:
            for line in p.stdout:
                print line.strip()

        if quit:
           amd.err_msg("Unable to perform the FC mappings",
                   exit_code=27)
        else:
           return False
    
        # Unix_cmd executed successfully
    elif rc==0:
        if verbose >= 2 and not silent:
            for line in p.stdout:
                print line.strip()

        if verbose and not silent:
           amd.ok_msg("   >> FC mappings are in place for VIOS:", vios_id,": ",
                 vios_slot_id, "-->", lpar_fc_slot_id)

        return True

# }}}
   # REDISCOVER DEVICES
def do_FC_cfgdev(vios,  verbose=False, silent=False, quit=False, do_prereq=False): # {{{
    """Performing cfgdev for FC
    vios:    The name of the vios
    do_prereq: Check if HMC is accessible, if MS exists"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    user = "padmin"
    opt1 = " ioscli cfgdev -dev vio0"
    unix_cmd=("ssh "\
            "{}"\
            "@{} "\
            "{}"\
            ).format(user,
                  vios,
                  opt1)
    
    if verbose >= 2 and not silent:
       amd.info_msg("  unix_cmd is: ", unix_cmd)

    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
        # Unix_cmd has failed
    if rc!=0:
        if verbose >= 2 and not silent:
            for line in p.stdout:
                print line.strip()

        if quit:
           amd.err_msg("Unable to run cfgdev",
                   exit_code=27)
        else:
           return False
    
        # Unix_cmd executed successfully
    elif rc==0:
        if verbose >= 2 and not silent:
            for line in p.stdout:
                print line.strip()

        if verbose and not silent:
            amd.ok_msg("   >> Virtual adapters are in place for:", vios)
        return True

# }}}
   # SLOT PROCESSING
def get_slot_id_from_file(slot_file, slot_type,  verbose=False, silent=False, quit=True, do_prereq=False): # {{{
    """Retrieving the slot id from file
    file: the file where the slots assignements are keept
        get_vios_slot_file(), get_lpar_vios1_slot_file(), get_lpar_vios2_slot_file()
    slot_type: rootvg, datavg1, datavg2
    do_prereq: Check if HMC is accessible, if MS exists"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    is_slot=False
    with open(slot_file,'r') as f:
       # Read/print file line by line: 
       for line in f:
           if slot_type in line:
               is_slot=line.split()[1]
               break
    f.close()

    if quit:
        if not is_slot:
            amd.err_msg("Unable to retrieve slot id:",
                    slot_type,
                    "for:",
                    slot_file,
                    exit_code=31)
 
    return is_slot

# }}}
def get_vfchost_based_on_slot(vios, slot_nr, verbose=False, silent=False, quit=True, do_prereq=False): # {{{
    """Determines the vFChost name based on the slot nr.  --> str: vhostN|vfchostN
    slot_nr:    The number of the vios slot
            get_slot_id_from_file()
    $cmd="ssh padmin\@$VIO_B \"ioscli lsmap -all -npiv|grep -w C$_|grep vfchost|awk '{print \\\$1}'\"";
    do_prereq: Check if HMC is accessible, if MS exists"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    user = "padmin"
    opt1 = " ioscli lsmap -all -npiv|grep -w C{}".format(slot_nr)
    unix_cmd=("ssh "\
            "{}"\
            "@{} "\
            "{}"\
            ).format(user,
                  vios,
                  opt1)
    
    if verbose >= 2 and not silent:
       amd.info_msg("  unix_cmd is: ", unix_cmd)

    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
        # Unix_cmd has failed
    if rc!=0:
        if verbose >= 2 and not silent:
            for line in p.stdout:
                print line.strip()

        if quit:
           amd.err_msg("Unable to identify the vfchost number.",
                   exit_code=27)
        else:
           return False
    
        # Unix_cmd executed successfully

    elif rc==0:
        for line in p.stdout:
            if slot_nr in line:
               return  line.split()[0].strip()
            else:
                amd.err_msg("Unable to retrieve the vfchost nr.", exit_code=31)

        if verbose and not silent:
            amd.ok_msg("   >> vfchost successfully retrieved")

# }}}
def get_vhost_based_on_slot(vios, slot_nr, verbose=False, silent=False, quit=True, do_prereq=False): # {{{
    """Determines the vhost name based on the slot nr.  --> str: vhostN|vfchostN
    slot_nr:    The number of the vios slot
            get_slot_id_from_file()
    $cmd="ssh padmin\@$VIO_B \"ioscli lsmap -all -npiv|grep -w C$_|grep vfchost|awk '{print \\\$1}'\"";
    do_prereq: Check if HMC is accessible, if MS exists"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    user = "padmin"
    opt1 = " ioscli lsmap -all |grep -w C{}".format(slot_nr)
    unix_cmd=("ssh "\
            "{}"\
            "@{} "\
            "{}"\
            ).format(user,
                  vios,
                  opt1)
    
    if verbose >= 2 and not silent:
       amd.info_msg("  unix_cmd is: ", unix_cmd)

    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
        # Unix_cmd has failed
    if rc!=0:
        if verbose >= 2 and not silent:
            for line in p.stdout:
                print line.strip()

        if quit:
           amd.err_msg("Unable to identify the vhost number.",
                   exit_code=27)
        else:
           return False
    
        # Unix_cmd executed successfully

    elif rc==0:
        for line in p.stdout:
            if slot_nr in line:
               return  line.split()[0].strip()
            else:
                amd.err_msg("Unable to retrieve the vhost nr.", exit_code=31)

        if verbose and not silent:
            amd.ok_msg("   >> vhost successfully retrieved")

# }}}
   # POPULATE VIOS FILES    
def populate_vios_vhost_vfchost_files(vios, vios_slot_file, verbose=False, silent=False, quit=True, do_prereq=False): # {{{
    """Populates the vios_host_file for  the rotovg  slot_nr found in vios_slots file
    e.g 
    rootvg vhostn 
    vios: vios_hostname
    vios_slots_file: filepath: retrieved by: get_vios_slot_file()
    do_prereq: Check if HMC is accessible, if MS exists"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    vios_vfchost_file=get_vios_processing_dir()+"vfchost_"+str(vios)
    vios_vhost_file=get_vios_processing_dir()+"vhost_"+str(vios)

    vios_vfchost_slots_dic={}
    vios_vhost_slots_dic={}

    with open(vios_slot_file) as f:
        for line in f:
               # DATAVG
            if "rootvg" not in line:
               (key, val) = line.split()
               vios_vfchost_slots_dic[key] = val
            else:
                # ROOTVG
               (key, val) = line.split()
               vios_vhost_slots_dic[key] = val
    f.close()

        
              # DATAVG
    with open(vios_vfchost_file,'w') as f:
        for key,value in vios_vfchost_slots_dic.items():
           f.write(str(key) +" "+ get_vfchost_based_on_slot(vios, value, verbose=verbose) + "\n")
    #      print key,value
    #      print get_vfchost_based_on_slot(vios, value, verbose=verbose)

    f.close()

    
    with open(vios_vhost_file,'w') as f:
        for key,value in vios_vhost_slots_dic.items():
           f.write(str(key) +" "+ get_vhost_based_on_slot(vios, value, verbose=verbose) + "\n")
    #      print key,value
    #      print get_vfchost_based_on_slot(vios, value, verbose=verbose)

    f.close()


    if verbose and not silent:
       amd.ok_msg("   >> File is in place:", vios_vfchost_file)
       amd.ok_msg("   >> File is in place:", vios_vhost_file)

# }}}
def populate_vios_fcs_files(vios, verbose=False, silent=False, quit=True, do_prereq=False): # {{{
    """Populates the vios_fcs_file 
    e.g 
    datavg1  fcs5
    datavg2  fcs7
    vios: vios_hostname
    do_prereq: Check if HMC is accessible, if MS exists"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    vios_fcs_file=get_vios_fcs_file(vios)   
              # DATAVG
    with open(vios_fcs_file,'w') as f:
           f.write("datavg1 " + datavg1_fcs + "\n")
           f.write("datavg2 " + datavg2_fcs + "\n")
    f.close()

    


    if verbose and not silent:
       amd.ok_msg("   >> File is in place:", vios_fcs_file)

# }}}
   # PHYSICAL TO VIRTUAL FC MAPPINGS
# get_fcs_from_file
def get_fcs_from_file(vios, datavg_type, verbose=False, silent=False, quit=True, do_prereq=False): # {{{
    """Retrieving the fcs from file based on the datavg_type
    file: the file where the datavg_type to fcs mapping is kept
        get_vios_slot_file(), get_lpar_vios1_slot_file(), get_lpar_vios2_slot_file()
    datavg_type:  datavg1, datavg2
    do_prereq: Check if HMC is accessible, if MS exists"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    local_file = get_vios_fcs_file(vios)

    is_fcs=False
    with open(local_file,'r') as f:
       # Read/print file line by line: 
       for line in f:
           if datavg_type in line:
               is_fcs=line.split()[1]
               break
    f.close()

    if quit:
        if not is_fcs:
            amd.err_msg("Unable to retrieve fcs:", datavg_type,
               "from", local_file, 
               exit_code=31)
 
    return is_fcs

# }}}
# get_vfchost_from_file
def get_vfchost_from_file(vios, datavg_type, verbose=False, silent=False, quit=True, do_prereq=False): # {{{
    """Retrieving the vfchost from file based on the datavg_type
    file: the file where the datavg_type to fcs mapping is kept
    datavg_type:  datavg1, datavg2
    do_prereq: Check if HMC is accessible, if MS exists"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    local_file = get_vios_vfchost_file(vios)

    is_vfchost=False
    with open(local_file,'r') as f:
       # Read/print file line by line: 
       for line in f:
           if datavg_type in line:
               is_vfchost=line.split()[1]
               break
    f.close()

    if quit:
        if not is_vfchost:
            amd.err_msg("Unable to retrieve vfchost:", datavg_type,
               "from", local_file, 
               exit_code=31)
 
    return is_vfchost

# }}}
# Map vfchost to physical 
def do_physical_to_virtual_vfc_mappings(vios, datavg_type, verbose=False, silent=False, quit=True, do_prereq=False): # {{{
    """Do a physical to virtual mapping for FC
    vios: vios hostname
    datavg_type:  datavg1, datavg2
      based on datavg_type -> vfchost and fcs will be extracted
    $cmd="ssh padmin\@$VIO_B \"ioscli vfcmap -vadapter vfchostN -fcp fcsM";
    do_prereq: Check if HMC is accessible, if MS exists"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    vfchost = get_vfchost_from_file(vios, datavg_type)
    fcs = get_fcs_from_file(vios, datavg_type)

    user = "padmin"
    opt1 = " ioscli vfcmap -vadapter {} -fcp {}".format(vfchost, fcs)
    unix_cmd=("ssh "\
            "{}"\
            "@{} "\
            "{}"\
            ).format(user,
                  vios,
                  opt1)
    
    if verbose >= 2 and not silent:
       amd.info_msg("  unix_cmd is: ", unix_cmd)

    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
        # Unix_cmd has failed
    if rc!=0:
        if verbose >= 2 and not silent:
            for line in p.stdout:
                print line.strip()

        if quit:
           amd.err_msg("Unable to map physical to virtual FC adaters.",
                   exit_code=27)
        else:
           return False
    
        # Unix_cmd executed successfully
    elif rc==0:
       if verbose and not silent:
          amd.ok_msg("   >> Successfully mapped:", 
             datavg_type, "-->", vios, "-->", vfchost,"-->",fcs)
       return True

# }}}

   # PHYSICAL TO VIRTUAL LU  MAPPINGS
# get_vhost_from_file
def get_vhost_from_file(vios, verbose=False, silent=False, quit=True, do_prereq=False): # {{{
    """Retrieving the vhost from file: str --> vhost
    vios: the vios hostname
    do_prereq: Check if HMC is accessible, if MS exists"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    local_file = get_vios_vhost_file(vios)

    is_vhost = False
    with open(local_file,'r') as f:
       # Read/print file line by line: 
       for line in f:
           if "rootvg" in line:
               is_vhost=line.split()[1]
               break
    f.close()

    if quit:
        if not is_vhost:
            amd.err_msg("Unable to retrieve vhost:" "from", local_file, 
               exit_code=31)
 
    return is_vhost

# }}}
# Map vfchost to physical 
def do_vhost_to_lu_mapping(vios, lpar_name, verbose=False, silent=False, quit=True, do_prereq=False): # {{{
    """Map vhost to Logical unit
    vios: vios hostname
     mkbdsp -clustername SSPFFM01 -sp SSPFFM01 -vadapter vhost2 
     -bd s370_rvg -tn vtscsi_s370en0
    do_prereq: Check if HMC is accessible, if MS exists"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    vhost = get_vhost_from_file(vios)
    lu = get_rootvg_lu_name(lpar_name)
    vtscsi_name = "vtscsi_"+str(lpar_name).strip()

    user = "padmin"
    opt1 = "ioscli mkbdsp -clustername SSPFFM01 -sp SSPFFM01 -vadapter {} -bd {} -tn {}".format(vhost, lu, vtscsi_name)
    unix_cmd=("ssh "\
            "{}"\
            "@{} "\
            "{}"\
            ).format(user,
                  vios,
                  opt1)
    
    if verbose >= 2 and not silent:
       amd.info_msg("  unix_cmd is: ", unix_cmd)

    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
        # Unix_cmd has failed
    if rc!=0:
        if verbose >= 2 and not silent:
            for line in p.stdout:
                print line.strip()

        if quit:
            amd.err_msg("Unable to map LU:", lu, "to vhost:",vhost, exit_code=27)
        else:
           return False
    
        # Unix_cmd executed successfully
    elif rc==0:
       if verbose and not silent:
          amd.ok_msg("   >> Successfully mapped:", 
             "rootvg", "-->", vios, "-->", vhost,"-->",lu)
       return True

#}}}


# LPAR
   # ACTIVATE SMS MODE
def get_lpar_state(hmc, ms, lpar_name, verbose=False, silent=False, quit=False, do_prereq=False ): # {{{
    """Determines the  lpar state -> str: lpar_state
    hmc:    Target HMC name
    ms:     Target Managed System
    lpar:   The name of the lpar: e.g. s134en0
    do_prereq: Check if HMC is accesible, if MS exists"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    is_lpar=is_lpar_in_hmc(args.hmc,
            args.destination_managed_system,
            args.source_lpar,
            quit=False)

    if  is_lpar:

    # ssh hscroot@lxsrvhmc0001 lssyscfg -m S04 -r lpar --filter "lpar_names=s370en0" -F state

        user = "hscroot"
        opt1 = "lssyscfg -r lpar -m "
        opt2 = " --filter \"lpar_names={}\"".format(lpar_name)
        opt3 = "-F \"state\""
        unix_cmd=("ssh "\
                "{}"\
                "@{} "\
                "{}"\
                "{}"\
                "{}"\
                " {}"\
                ).format(user,hmc, opt1, ms, opt2, opt3)
        
        if verbose >= 2 and not silent:
           amd.info_msg("  unix_cmd is: ", unix_cmd)

        p = subprocess.Popen(unix_cmd,\
                shell=True, stdout=subprocess.PIPE,\
                stderr=subprocess.STDOUT)
        rc = p.wait()
        
            # Unix_cmd has failed
        if rc!=0:
           if quit:
               amd.err_msg("Unable to determine the LPAR STATE",
                       exit_code=23)
           else:
               return False
        
            # Unix_cmd executed successfully
        elif rc==0:
           line = p.stdout.readlines()[0].strip()
           if verbose and not silent:
                  amd.ok_msg("   >> The  state of the lpar is::", line)

           return line

#  }}}
def do_lpar_activate_ok_prompt(hmc, ms, lpar_name, verbose=False, silent=False, quit=False, ): # {{{
    """Activating the lpar into Open Firwmare prompt

    hmc:    Target HMC name
    ms:     Target Managed System 
    lpar:   the lpar name"""

    

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    if verbose and not silent:
        amd.ok_msg("Starting lpar activation ")
      
    lpar_state=get_lpar_state(args.hmc,
            args.destination_managed_system,
            args.source_lpar, 
            verbose=False,
            silent=True,
            quit=True)

    if "Not Activated" in lpar_state:
        user = "hscroot"
        opt1 = "chsysstate -r lpar -m "
        opt2 = " -f default -o on -n {} -b of".format(lpar_name)
        unix_cmd=("ssh "\
                "{}"\
                "@{} "\
                "{}"\
                "{}"\
                " {}"\
                ).format(user,hmc, opt1, ms, opt2)
        
        if verbose >= 2 and not silent:
           amd.info_msg("  unix_cmd is: ", unix_cmd)

        p = subprocess.Popen(unix_cmd,\
                shell=True, stdout=subprocess.PIPE,\
                stderr=subprocess.STDOUT)
        rc = p.wait()
        
            # Unix_cmd has failed
        if rc!=0:
           if quit:
               amd.err_msg("Unable activate the lpar into OK prompt",
                       exit_code=23)
           else:
               return False
        
            # Unix_cmd executed successfully
        elif rc==0:
           if verbose and not silent:
               amd.ok_msg("   >> Lpar mode:  OK prompt")



    else:
        if verbose and not silent:
            amd.ok_msg("   >> Lpar already in state:", lpar_state)



    if verbose and not silent:
        amd.ok_msg("End of: LPAR ACTIVATION")



# }}}
def do_lpar_deactivate(hmc, ms, lpar_name, verbose=False, silent=False, quit=False, ): # {{{
    """Deactivating the lpar into Not Activated

    hmc:    Target HMC name
    ms:     Target Managed System 
    lpar:   the lpar name"""

    

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])


    if verbose and not silent:
        amd.ok_msg("Starting lpar deactivation ")
      
    lpar_state=get_lpar_state(args.hmc,
            args.destination_managed_system,
            args.source_lpar, 
            verbose=False,
            silent=True,
            quit=True)

    if "Not Activated" not in lpar_state:
    # ssh hscroot@lxsrvhmc0001 chsysstate -m S04 -r lpar  -o shutdown -n s370en0 --immed

        user = "hscroot"
        opt1 = "chsysstate -r lpar -m "
        if args.FORCE:
            opt2 = "  -o shutdown -n {} --immed".format(lpar_name)
        else:
            opt2 = "  -o shutdown -n {} ".format(lpar_name)
        unix_cmd=("ssh "\
                "{}"\
                "@{} "\
                "{}"\
                "{}"\
                " {}"\
                ).format(user,hmc, opt1, ms, opt2)
        
        if verbose >= 2 and not silent:
           amd.info_msg("  unix_cmd is: ", unix_cmd)

        p = subprocess.Popen(unix_cmd,\
                shell=True, stdout=subprocess.PIPE,\
                stderr=subprocess.STDOUT)
        rc = p.wait()
        
            # Unix_cmd has failed
        if rc!=0:
           if quit:
               amd.err_msg("Unable deactivate the lpar",
                       exit_code=23)
           else:
               return False
        
            # Unix_cmd executed successfully
        elif rc==0:
           if verbose and not silent:
               amd.ok_msg("   >> Lpar mode: Not Activated")



    else:
        if verbose and not silent:
            amd.ok_msg("   >> Lpar already in state:", lpar_state)



    if verbose and not silent:
        amd.ok_msg("End of: LPAR DEACTIVATION \n")



# }}}
    # GET MAC
def get_lpar_mac(hmc, ms, lpar_name, verbose=False, silent=False, quit=False, ): # {{{
    """Retrieving the LPAR mac address

    hmc:    Target HMC name
    ms:     Target Managed System 
    lpar_name:   the lpar name"""

    

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    local_mac=False

    if verbose and not silent:
        amd.ok_msg("Retrieving the MAC address of the LPAR")
      
    lpar_state=get_lpar_state(args.hmc,
            args.destination_managed_system,
            args.source_lpar, 
            verbose=False,
            silent=True,
            quit=True)

    if "Not Activated" in lpar_state:

            do_lpar_activate_ok_prompt(args.hmc,
            args.destination_managed_system,
            args.source_lpar, 
            verbose=args.verbose,
            quit=True)

# ssh hscroot@lxsrvhmc0001 lshwres -r virtualio --rsubtype eth -m S04 --level lpar  --filter "lpar_names=s370en0,slots=2" -F mac_addr


    user = "hscroot"
    opt1 = "lshwres -r virtualio --rsubtype eth --level lpar -m "
    opt2 = " --filter \"lpar_names={},slots=2\" -F mac_addr".format(lpar_name)
    unix_cmd=("ssh "\
            "{}"\
            "@{} "\
            "{}"\
            "{}"\
            " {}"\
            ).format(user,hmc, opt1, ms, opt2)
    
    if verbose >= 2 and not silent:
       amd.info_msg("  unix_cmd is: ", unix_cmd)

    p = subprocess.Popen(unix_cmd,\
            shell=True, stdout=subprocess.PIPE,\
            stderr=subprocess.STDOUT)
    rc = p.wait()
    
        # Unix_cmd has failed
    if rc!=0:
       if quit:
           amd.err_msg("Unable retrieve the MAC address",
                   exit_code=23)
       else:
           return False
    
        # Unix_cmd executed successfully
    elif rc==0:
        output_list=p.stdout.readlines()
        local_mac=output_list[0].strip()
        if verbose and not silent:
           amd.ok_msg("   >> Mac address is:", local_mac)





    return local_mac



# }}}


    
# STAGE_FUNCTIONS

# Q-1 Collect Node Info
def do_all_collect_info(source_csm, verbose=False, silent=False, quit=False, ): # {{{
    """Collecting NODE info

    source_csm: Source CSM
    ms:     Target Managed System """
    

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])
      
    if verbose and not silent:
        amd.stage_msg("Starting the SOURCE CSM/LPAR checks")
    is_source_csm_accesible(source_csm, user="root",
       verbose=verbose, silent=True, quit=True)
    
    is_source_lpar_dsh_accesible(args.source_lpar, verbose=verbose, quit=True)



    # Starting  NIM RESOURCE DEFINITION
    if verbose and not silent:
        amd.info_cyan_msg("Starting nim operations: define resources ")


# ---------------TEST 
    amd.ok_msg("Starting NIM test section")
    is_nim_client(args.source_lpar, verbose=verbose, quit=False, silent=False)

# ---------------end_testTEST 


# }}}



# Q_1 INFRA PREREQ
def do_infra_prereq(hmc, ms, verbose=False, silent=False, quit=False, ): # {{{
    """Performing a complete infrastructure prerequisites checks
    hmc:    Target HMC name
    ms:     Target Managed System """

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])
      


    # Starting  HMC/MS
    if verbose and not silent:
        amd.stage_msg("Starting the HMC/MS prerequisites checks")

    is_hmc_accesible(args.hmc, user="hscroot",
       verbose=args.verbose, silent=True, quit=True)

    get_target_ms_serial(verbose=args.verbose, quit=True)

    # Starting VIOS checking
    if verbose and not silent:
        amd.stage_msg("Starting the VIOS prerequisites checks")
    get_vio_a_hostname(verbose=args.verbose)
    get_vio_b_hostname(verbose=args.verbose)
    if verbose and not silent:
        amd.ok_msg("   >> Retrieving VIOS ID:")
    get_vios_id(args.hmc,
       args.destination_managed_system,
       get_vio_a_hostname(silent=True),
       verbose=args.verbose,
       quit=True) 

    get_vios_id(args.hmc,
       args.destination_managed_system,
       get_vio_b_hostname(silent=True),
       verbose=args.verbose,
       quit=True) 

    # check if vioss are  accessible over  ssh
    is_ssh_accesible(get_vio_a_hostname(silent=True),
       user="padmin",
       verbose=args.verbose,
       quit=True)

    is_ssh_accesible(get_vio_b_hostname(silent=True),
       user="padmin",
       verbose=args.verbose,
       quit=True)


    # Starting NODE checking
    if verbose and not silent:
        amd.stage_msg("Checking if the client is registered in /etc/hosts")

    if not is_node_in_host_conf(args.source_lpar):
        amd.err_msg(args.source_lpar, " is not listed in /etc/hosts")
        amd.err_msg("Add the client specific entry and retry",exit_code=1)
    else:
        if args.verbose:
            amd.ok_msg("   >> Client is registered in /etc/hsts")


    if verbose and not silent:
        amd.stage_msg("Starting the node_conf prerequisites checks")

    is_node_conf_file(get_node_conf_path(),
            verbose=args.verbose,
            quit=True)
    is_valid_node_conf_file(get_node_conf_path(),
            verbose=args.verbose,
            quit=True)

    # Starting WWNs checking
    if verbose and not silent:
        amd.stage_msg("Starting the wwns_conf prerequisites checks")

    is_valid_wwns_conf_file(get_node_conf_path(),
            verbose=args.verbose,
            quit=True)

    # Starting node_ini_checks
    if verbose and not silent:
        amd.stage_msg("Starting the live data  prerequisites checks")
    ini_path = get_node_ini_path()
    is_node_ini_file(ini_path, verbose=verbose, quit=True)


    # Starting firstboot checking
    if verbose and not silent:
        amd.stage_msg("Starting the firstboot prerequisites checks")
    fb_path=get_node_firstboot_path()

    if is_node_firstboot_file(fb_path, verbose=args.verbose, quit=False):
        amd.info_msg("The firstboot file will be overwritten")
    else:
        amd.info_msg("The firstboot file will be generated")



    if verbose and not silent:
        amd.ok_msg("End of: infrastructure prerequisites\n")
# }}}

# Q_2 PREMIGRATION
def do_all_premigration(verbose=False):# {{{
    """Performs all the premigration activities: 
    
    - It generates the /csmimages/node_firstboot_lpar.sh file
    - It updates the vlan values for SAP in:
            /csmimages/node_conf_lpar file
    - It updates the AME values in:
            /csmimages/node_conf_lpar file
    

    :fb_file:   The first boot file to be generated: 
    :ini_file:  The node_ini_lpar file that stores the live config data
    :node_conf_file:  The node_conf_file to be updated
    :verbose:   Show what is going on
    """
    fb_file = get_node_firstboot_path()
    ini_file = get_node_ini_path()
    node_conf_file = get_node_conf_path()

    am_premig.main(fb_file, ini_file, node_conf_file,verbose=verbose)
# }}}
def do_generate_fb(verbose=False):# {{{
    """Generates on the first_boot
    
    - It generates the /csmimages/node_firstboot_lpar.sh file
    

    :fb_file:   The first boot file to be generated: 
    :ini_file:  The node_ini_lpar file that stores the live config data
    :verbose:   Show what is going on
    """
    fb_file = get_node_firstboot_path()
    ini_file = get_node_ini_path()

    am_premig.gen_fb(fb_file, ini_file, verbose=verbose)
# }}}

# Q3_Q4 HMC/VIOS
def do_hmc_vios_target_lpar_operations(hmc, ms, verbose=False, silent=False, quit=False, ): # {{{
    """Performing hmc operations  related to the target lpar:

    hmc:    Target HMC name
    ms:     Target Managed System """
    

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])
      

    # Starting  HMC/MS
    if verbose and not silent:
        amd.info_cyan_msg("Starting the HMC lpar operations ")

   # Variable collections
    is_lpar=is_lpar_in_hmc(args.hmc,
            args.destination_managed_system,
            args.source_lpar,
            verbose=args.verbose,
            quit=False)

    vios_a_id=get_vios_id(args.hmc,
       args.destination_managed_system,
       get_vio_a_hostname(silent=True),
       verbose=args.verbose,
       silent=True,
       quit=True) 

    vios_b_id=get_vios_id(args.hmc,
       args.destination_managed_system,
       get_vio_b_hostname(silent=True),
       verbose=args.verbose,
       silent=True,
       quit=True) 

    vios_a_hostname=get_vio_a_hostname(silent=True)
    vios_b_hostname=get_vio_b_hostname(silent=True)

    mk_vios_processing_dir(verbose=verbose, quit=True)


    # TESTING with Existing LPAR

    # END OF TESTING with Existing LPAR


    if not is_lpar:

        # Identifying the next available LPAR ID
        if verbose and not silent:
            amd.info_cyan_msg("Identifying the next available LPAR ID")
        next_lpar_id=get_next_lpar_id(args.hmc,
           args.destination_managed_system,
           verbose=args.verbose,
           quit=True) 

        # Identifying three contiguous slots starting from the first one available
        if verbose and not silent:
            amd.info_cyan_msg("Identifying three contiguous slots starting from the first one available")

        eth_slot_id_list=get_eth_slot_ids(args.hmc,
           args.destination_managed_system,
           verbose=args.verbose,
           quit=True) 

        scsi_slot_ids_list=get_scsi_slot_ids(args.hmc,
           args.destination_managed_system,
           verbose=args.verbose,
           quit=True) 




        fc_slot_ids_list=get_fc_slot_ids(args.hmc,
           args.destination_managed_system,
           verbose=args.verbose,
           quit=True) 



        next_slot_id=get_next_slot_id(eth_slot_id_list, scsi_slot_ids_list,
            fc_slot_ids_list,verbose=args.verbose, quit=True) 


        # Creating the Logical Unit to be used as a rootvg substorage system
        if verbose and not silent:
            amd.info_cyan_msg("Creating the rootvg Logical Unit")
            
            if not is_rootvg_lu(vios_a_hostname,args.source_lpar,verbose=verbose):
                mk_rootvg_lu(vios_a_hostname,args.source_lpar,verbose=verbose )



        # Creating the lpar 
        if verbose and not silent:
            amd.info_cyan_msg("Creating the lpar")
        create_target_lpar(args.hmc,
            args.destination_managed_system,
            next_slot_id,
                next_lpar_id,
                verbose=verbose,
                quit=True)

#        amd.ok_msg("==== DEBUG EXITING ======")
#        sys.exit(0)


        # Updating the VIOS virtual_scsi  profile
        if verbose and not silent:
            amd.info_cyan_msg("Updating the VIOSs profiles to include virtual_scsi mappings")




            # Updating the VIOS_A virtual_scsi  profile
        update_vios_scsi_profile(hmc,
              ms,
              root_vg_slot_a,
              next_lpar_id,
              vios_a_id,
              next_slot_id,
              verbose=verbose,
              quit=True)

            # Updating the VIOS_A virtual_scsi  profile
        update_vios_scsi_profile(hmc,
              ms,
              root_vg_slot_b,
              next_lpar_id,
              vios_b_id,
              next_slot_id,
              verbose=verbose,
              quit=True)


        # Updating the VIOS virtual_FC  profile
        if verbose and not silent:
            amd.info_cyan_msg("Updating the VIOSs profiles to include virtual_FC mappings")

            # Updating the VIOS_A virtual_scsi  profile
        update_vios_FC_profile(hmc,
              ms,
              data_vg1_slot_a,
              data_vg2_slot_a,
              next_lpar_id,
              vios_a_id,
              next_slot_id,
              verbose=verbose,
              quit=True)


            # Updating the VIOS_B virtual_scsi  profile
        update_vios_FC_profile(hmc,
              ms,
              data_vg1_slot_b,
              data_vg2_slot_b,
              next_lpar_id,
              vios_b_id,
              next_slot_id,
              verbose=verbose,
              quit=True)




        #  DLPAR
        # Performing VIOS mapping for vscsi
        if verbose and not silent:
            amd.info_cyan_msg("Performing VIOS slot mapping for vscsi (VIOS --> LPAR)")

         #  VSCSI mappings VIOS_A
        dlpar_scsi_slot_mapping(hmc,
              ms,
              root_vg_slot_a,
              next_lpar_id,
              vios_a_id,
              next_slot_id,
              verbose=verbose,
              quit=True)


         #  VSCSI mappings VIOS_A
        dlpar_scsi_slot_mapping(hmc,
              ms,
              root_vg_slot_b,
              next_lpar_id,
              vios_b_id,
              next_slot_id,
              verbose=verbose,
              quit=True)





        # Performing VIOS mapping for FC/NPIV 
        if verbose and not silent:
            amd.info_cyan_msg("Performing VIOS slot mapping for FC (VIOS --> LPAR)")

         #  VSCSI mappings VIOS_A
        dlpar_FC_slot_mapping(hmc,
              ms,
              data_vg1_slot_a,
              next_lpar_id,
              vios_a_id,
              next_slot_id + 1,
              verbose=verbose,
              quit=True)


        dlpar_FC_slot_mapping(hmc,
              ms,
              data_vg2_slot_a,
              next_lpar_id,
              vios_a_id,
              next_slot_id + 2,
              verbose=verbose,
              quit=True)


         #  VSCSI mappings VIOS_B
        dlpar_FC_slot_mapping(hmc,
              ms,
              data_vg1_slot_b,
              next_lpar_id,
              vios_b_id,
              next_slot_id + 1,
              verbose=verbose,
              quit=True)


        dlpar_FC_slot_mapping(hmc,
              ms,
              data_vg2_slot_b,
              next_lpar_id,
              vios_b_id,
              next_slot_id + 2,
              verbose=verbose,
              quit=True)


        # CFGDEV
        if verbose and not silent:
            amd.info_cyan_msg("Detecting the new virtual adapters")
        do_FC_cfgdev(get_vio_a_hostname(), verbose=verbose, quit=True)
        do_FC_cfgdev(get_vio_b_hostname(), verbose=verbose, quit=True)


        # Populating vios_host file
        if verbose and not silent:
            amd.info_cyan_msg("Populating the vfchost, fcs and vhost  files")
        for vios in [vios_a_hostname, vios_b_hostname]:
            populate_vios_vhost_vfchost_files(vios,
                    get_vios_slot_file(),
                    verbose=verbose)

            # Populating FCS  file # These are the Physical ports
            populate_vios_fcs_files(vios,verbose=verbose)


        # Performing VIOS Physical to Virtual
        if verbose and not silent:
            amd.info_cyan_msg("Performing VIOS Physical to Virtual mappings")
        for vios in [vios_a_hostname, vios_b_hostname]:
           for datavg_type in ["datavg1", "datavg2"]:
              do_physical_to_virtual_vfc_mappings(vios,
                    datavg_type,
                    verbose=verbose)


        # Performing VIOS LU to vhost mapping
        if verbose and not silent:
            amd.info_cyan_msg("Performing VIOS Logical Unit to vhost mappings")
        for vios in [vios_a_hostname, vios_b_hostname]:
            do_vhost_to_lu_mapping(vios, args.source_lpar, verbose=verbose)


    if verbose and not silent:
        amd.ok_msg("End of: HMC/VIOS Operations \n")



# }}}

# Q4 LPAR_ACTIVATE_OK
# ACTIVATE LPAR INTO OK PROMPT
# EXTRACT MAC ADDRESS
def do_lpar_all_activation_operations(hmc, ms, lpar_name, verbose=False, silent=False, quit=False, ): # {{{
    """Performing Lpar Activation and mac retrieval

    hmc:    Target HMC name
    ms:     Target Managed System 
    lpar_name The name of the lpar e.g. s370en0"""

    

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    #

    do_lpar_activate_ok_prompt(args.hmc,
            args.destination_managed_system,
            args.source_lpar, 
            verbose=args.verbose,
            quit=True)





# }}}

# Q-4 LPAR_SHUTDOWN
# DEACTIVATE LPAR INTO OK PROMPT
def do_lpar_all_deactivation_operations(hmc, ms, lpar_name, verbose=False, silent=False, quit=False, ): # {{{
    """Performing Lpar Activation and mac retrieval

    hmc:    Target HMC name
    ms:     Target Managed System 
    lpar_name The name of the lpar e.g. s370en0"""

    

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    #

    do_lpar_deactivate(args.hmc,
            args.destination_managed_system,
            args.source_lpar, 
            verbose=args.verbose,
            quit=True)





# }}}


# Q_5 NIM_DEFINITION
def do_all_NIM_define_operations(hmc, ms, verbose=args.verbose, silent=False, quit=False, ): # {{{
    """Performing all NIM operations

    hmc:    Target HMC name
    ms:     Target Managed System """
    

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])
      

    # Starting  NIM RESOURCE DEFINITION
    if verbose and not silent:
        amd.info_cyan_msg("Starting nim operations: define resources ")


# ---------------TEST 
    amd.ok_msg("Starting NIM test section")
    is_nim_client(args.source_lpar, verbose=verbose, quit=False, silent=False)

# ---------------end_testTEST 



    amd.ok_msg("Checking the master")
    am_i_nim_master(verbose=args.verbose, quit=True)
    amd.ok_msg("Checking if NIM processing dir exists")
    mk_nim_processing_dir(verbose=args.verbose, quit=True)


    amd.ok_msg("Defining the bosinst.data resource")
    nim_define_bosinst_data_res(verbose=args.verbose, quit=True)



    amd.ok_msg("Defining the image.data resource")
    nim_define_image_data_res(verbose=args.verbose, quit=True)

    amd.ok_msg("Defining the first boot source")
    nim_define_fb_script_res(verbose=args.verbose, quit=True)

    amd.ok_msg("Checking the resolv_conf resource")
    is_nim_resolvconf(verbose=args.verbose, quit=True)

    amd.ok_msg("Defining the mksysb resource")
    nim_define_mksysb_res(verbose=args.verbose, quit=True)

    amd.ok_msg("Defining the spot resource")
    nim_define_spot_res(verbose=args.verbose, quit=True)


    amd.ok_msg("Identifying the network")
    all_nim_networks=get_nim_all_networks(verbose=args.verbose, quit=True)
    local_network=get_nim_network(all_nim_networks,
            args.destination_managed_system,
            verbose=args.verbose,
            quit=True)


    amd.ok_msg("Identifying the MAC Address")
    get_lpar_mac(args.hmc,
            args.destination_managed_system,
            args.source_lpar, 
            verbose=verbose,
            quit=True)

    amd.ok_msg("Defining the NIM Client")
    nim_define_client(args.source_lpar, 
            local_network,
            verbose=verbose,
            quit=True)

    if verbose and not silent:
        amd.ok_msg("End of: nim operations: define resources\n")


# }}}

# Q_-5 NIM_REMOVE_RESOURCE
def do_all_NIM_remove_operations(hmc, ms, verbose=False, silent=False, quit=False, force=False ): # {{{
    """Performing all NIM operations

    hmc:    Target HMC name
    ms:     Target Managed System """

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])

    if force:
        amd.ok_msg("Resetting the nim client")
        nim_reset_client(args.source_lpar,
            verbose=verbose, quit=True, force=force)

    # Starting  
    if verbose and not silent:
        amd.info_cyan_msg("Starting nim operations: remove resources ")


    amd.ok_msg("Checking the master")
    am_i_nim_master(verbose=args.verbose, quit=True)
    amd.ok_msg("Checking if NIM processing dir exists")
    mk_nim_processing_dir(verbose=args.verbose, quit=True)



    amd.ok_msg("Removing the bosinst.data if it is defined")
    nim_remove_bosinst_data_res(verbose=args.verbose)

    amd.ok_msg("Removing the image.data if it is defined")
    nim_remove_image_data_res(verbose=args.verbose)

    amd.ok_msg("Removing the spot if it is defined")
    nim_remove_spot_res(verbose=args.verbose)

    amd.ok_msg("Removing the mksysb if it is defined")
    nim_remove_mksysb_res(verbose=args.verbose)

    amd.ok_msg("Removing the fb_script if it is defined")
    nim_remove_fb_script_res(verbose=args.verbose)

    amd.ok_msg("Removing the nim client")
    nim_remove_client(args.source_lpar,
            verbose=verbose, quit=True)


    if verbose and not silent:
        amd.ok_msg("End of: nim operations: remove resources\n")


# }}}


# Q_6 NIM_ALLOCATION
def do_all_NIM_allocate_operations(client_name,hmc, ms,  verbose=args.verbose, silent=False, quit=False, ): # {{{
    """Performing all NIM operations

    hmc:    Target HMC name
    ms:     Target Managed System """
    

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])
      

    # Starting  NIM ALLOCATION
    if verbose and not silent:
        amd.info_cyan_msg("Starting nim operations: resources allocation ")


    amd.ok_msg("Allocating the bosinst_data")
    nim_allocate_bosinst_data(client_name,verbose=args.verbose, quit=True)

    amd.ok_msg("Allocating the image_data")
    nim_allocate_image_data(client_name,verbose=verbose, quit=True)

    amd.ok_msg("Allocating the mksysb resource")
    nim_allocate_mksysb_res(client_name,verbose=verbose, quit=True)

    amd.ok_msg("Allocating the resolv_conf resource")
    nim_allocate_resolv_conf(client_name,resolv_conf_name,
        verbose=verbose, quit=True)

    amd.ok_msg("Allocating the first_boot script")
    nim_allocate_fb_script(client_name,verbose=verbose, quit=True)

    amd.ok_msg("Allocating the SPOT resource")
    nim_allocate_spot_client_specific(client_name,verbose=verbose, quit=True)

#    amd.ok_msg("Retrieving OSLEVEL from the mksysb")
#    get_oslevel_from_mksysbd(get_mksysb_path(), verbose=args.verbose)
#
#    amd.ok_msg("Retrieving the appropriate spot for the mksysb")
#    my_oslevel=get_oslevel_from_mksysbd(get_mksysb_path(), quit=True)
#    my_spot=get_nim_aix_spot_based_on_oslevel(my_oslevel,
#            verbose=args.verbose, quit=True)
#    nim_allocate_spot(client_name,my_spot,verbose=args.verbose, quit=True)
#    
    # Further investigation is needed
#    amd.ok_msg("Retrieving the appropriate lpp_source for the mksysb")
#    my_lpp=get_nim_aix_lpp_source_based_on_oslevel(my_oslevel,
#            verbose=args.verbose, quit=True)
#    nim_allocate_lpp_source(client_name,my_lpp,verbose=args.verbose, quit=True)


# ---------------TEST 
# ---------------end_testTEST 


    if verbose and not silent:
        amd.ok_msg("End of: nim :  resources allocation\n")


# }}}

# Q_-6 NIM_
def do_all_NIM_deallocate_operations(client_name,hmc, ms,  verbose=args.verbose, silent=False, quit=False, force=False): # {{{
    """Performing all NIM deallocation
    client_name: the name of the source lpar args.source_lpar
    hmc:    Target HMC name
    ms:     Target Managed System """
    

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])
      

    # Starting  NIM DEALLOCATION
    if verbose and not silent:
        amd.info_cyan_msg("Starting nim operations: resources deallocation ")

    if force:
        amd.ok_msg("Resetting the nim client")
        nim_reset_client(args.source_lpar,
            verbose=verbose, quit=True, force=force)

    amd.ok_msg("Deallocating the bosinst.data")
    nim_deallocate_bosinst_data(client_name,verbose=verbose, quit=True)

    amd.ok_msg("Deallocating the image_data")
    nim_deallocate_image_data(client_name,verbose=verbose, quit=True)

    amd.ok_msg("Deallocating the mksysb resource")
    nim_deallocate_mksysb_res(client_name,verbose=verbose, quit=True)


    amd.ok_msg("Deallocating the SPOT resource")
    nim_deallocate_spot_client_specific(client_name,verbose=verbose, quit=True)

    amd.ok_msg("Deallocating the resolv_conf resource")
    nim_deallocate_resolv_conf(client_name,resolv_conf_name,
        verbose=verbose, quit=True)

    amd.ok_msg("Deallocating the fb_script resource")
    nim_deallocate_fb_script(client_name,verbose=verbose, quit=True)

#    amd.ok_msg("Retrieving the appropriate spot for the mksysb")
#    my_oslevel=get_oslevel_from_mksysbd(get_mksysb_path(), quit=True)
#    my_spot=get_nim_aix_spot_based_on_oslevel(my_oslevel, verbose=args.verbose, quit=True)
#    nim_deallocate_spot(client_name,my_spot,verbose=args.verbose, quit=True)


#    amd.ok_msg("Deallocating the lpp_source")
#    my_lpp=get_nim_aix_lpp_source_based_on_oslevel(my_oslevel, quit=True)
#    nim_deallocate_lpp_source(client_name,my_lpp,verbose=args.verbose, quit=True)

    if verbose and not silent:
        amd.ok_msg("End of: nim :  resources allocation\n")


# }}}



#-------------------------- HERE ---------------
# Q_7 NIM_ALLOCATION
def do_all_NIM_bosinst(client_name,hmc, ms,  verbose=args.verbose, silent=False, quit=False,prereq=False,force=False ): # {{{
    """Performing  NIM bosinstallation operations

    hmc:    Target HMC name
    ms:     Target Managed System """
    



    if force:
        amd.ok_msg("Resetting the nim client")
        nim_reset_client(args.source_lpar,
            verbose=verbose, quit=True, force=force)


    if prereq:
        print "I'm doing the prereq"

        amd.info_cyan_msg("Stages 5 and 6 are prerequisites for this state")

        # STAGE 5
        do_all_NIM_define_operations(args.hmc, 
           args.destination_managed_system,
           verbose=args.verbose,
           quit=True)

        # STAGE_6
        do_all_NIM_allocate_operations(args.source_lpar,
           args.hmc, 
           args.destination_managed_system,
           verbose=args.verbose,
           quit=True)






    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])
      

    # Starting  NIM ALLOCATION
    if verbose and not silent:
       amd.info_cyan_msg("Starting bosinst operations:")
    current_state=get_nim_client_cstate(client_name,verbose=args.verbose, quit=True)

    if  "BOS installation has been enabled" not in current_state:
        amd.ok_msg("Initiating the nim restore operation")
        nim_do_initiate_restore(client_name,verbose=args.verbose, quit=True)
    else:
        amd.ok_msg("Client is already configured for BOS installation")



    amd.info_cyan_msg("Starting Unattended Migration/Installation:")
    amd.info_cyan_msg("Estimated installation/migration time, 50 minutes")
    amd.info_cyan_msg("Use the following command for status details:")
    print ("# lsnim -a Mstate -a Cstate -a Cstate_result -a info  {} \n")\
            .format(client_name)

    nim_do_unattended_install(args.hmc,
        args.destination_managed_system,
        args.source_lpar,
        verbose=args.verbose,
        quit=True)



    if verbose and not silent:
        amd.ok_msg("End of: bosinst : \n")


# }}}


# Q_77 MKSYSB
def do_mksysb_operations(hmc, ms, lpar_name, verbose=False, silent=False, quit=False, ): # {{{
    """This function bundles the STAGE 2 Functions
    Its purpose is to perorm mksysb operations

    hmc:    Target HMC name
    ms:     Target Managed System 
    lpar_name The name of the source lpar args.source_lpar"""

    if verbose >= 2:
       amd.debug_msg("Start of:#  ", inspect.stack()[0][3])
      
    
    amd.info_cyan_msg("Performing mksysb general prequisites checks")

    # check if mksysb exists: # {{{
    mksysb_path=get_mksysb_path()
    if is_mksysb(mksysb_path):
      amd.ok_msg("   >> The file", mksysb_path, "exists in the right place:")
    else:
      amd.err_msg("  >> The mksysb file", mksysb_path,
              "does not exist on the /csmimages",
              exit_code=1)
      
# }}}
    # checking if mksysb file is older than 3 days:# {{{
    if not args.mksysb_age:
       age=5
    else:
       age=args.mksysb_age

    if is_mksysb_new(mksysb_path, age=age):
        amd.ok_msg("   >> The mksysb is newer than:", age, "days")
    else:
        amd.info_msg("  The mksysb is older than:", age, "days")
        amd.info_msg("  Please use the -a switch to specify a different age or:")
        amd.info_msg("  Use the -1 stage to collect a newer mksysb.")
        amd.err_msg("  Invalid mksysb age:", exit_code=2)
  
  # }}}
  # checking if mksysb if valid# {{{
    is_mksysb_valid(mksysb_path, verbose=verbose, quit=True)
  # }}}
# checking if the rootvg of the mksysb if mirrored# {{{
    amd.info_cyan_msg("Checking if the rootvg of the mksysb is mirrored")
    if is_mksysb_rootvg_mirrored(mksysb_path,
            verbose=args.verbose,
            quit=True, silent=False):
        amd.info_msg("  For migration to SSP the rootvg will be unmirrored")
  # }}}
  # go to the mksysb processing image directory# {{{
    goto_mksysb_processing_dir(verbose=args.verbose)
  # }}}
    amd.info_cyan_msg("Processing the unattended installation files")
  # Extracting the bosinst.data form mksysb# {{{
    amd.ok_msg("   >> Extracting the bosinst.data for processing")
    extract_mksysb_bosinst_data(verbose=verbose, quit=True)
  # }}}
  # Extracting the image.data form mksysb# {{{
    amd.ok_msg("   >> Extracting the image.data for processing")
    extract_mksysb_image_data(verbose=verbose, quit=True)
  # }}}
  # UnMirroring the mksysb image.data data# {{{
    if is_mksysb_rootvg_mirrored(get_mksysb_path(),  silent=True):
       amd.ok_msg("  UnMirroring the rootvg in the image.data file")
       unmirror_mksysb_image_data(verbose=args.verbose, quit=True)
  # }}}
  # IS bosinst.data valid # {{{
    is_bosinst_data_valid(verbose=args.verbose, quit=True)
  # }}}
  # BOSINST.data configuration# {{{
    mk_boinst_data(verbose=args.verbose, quit=True)
  # }}}
    if verbose and not silent:
        amd.ok_msg("End of: mksysb operations\n")

#-------------------------- HERE ---------------#

#
#    # Starting  HMC/MS
#    if verbose and not silent:
#        amd.stage_msg("Starting the HMC/MS prerequisites checks")
#
#    is_hmc_accesible(args.hmc, user="hscroot",
#       verbose=args.verbose, silent=True, quit=True)
#
#    get_target_ms_serial(verbose=args.verbose, quit=True)
#
#    # Starting VIOS checking
#    if verbose and not silent:
#        amd.stage_msg("Starting the VIOS prerequisites checks")
#    get_vio_a_hostname(verbose=args.verbose)
#    get_vio_b_hostname(verbose=args.verbose)
#    if verbose and not silent:
#        amd.ok_msg("   >> Retrieving VIOS ID:")
#    get_vios_id(args.hmc,
#       args.destination_managed_system,
#       get_vio_a_hostname(silent=True),
#       verbose=args.verbose,
#       quit=True) 
#
#    get_vios_id(args.hmc,
#       args.destination_managed_system,
#       get_vio_b_hostname(silent=True),
#       verbose=args.verbose,
#       quit=True) 
#
#    # check if vioss are  accessible over  ssh
#    is_ssh_accesible(get_vio_a_hostname(silent=True),
#       user="padmin",
#       verbose=args.verbose,
#       quit=True)
#
#    is_ssh_accesible(get_vio_b_hostname(silent=True),
#       user="padmin",
#       verbose=args.verbose,
#       quit=True)
#
#
#    # Starting NODE checking
#    if verbose and not silent:
#        amd.stage_msg("Starting the node_conf prerequisites checks")
#
#    is_node_conf_file(get_node_conf_path(),
#            verbose=args.verbose,
#            quit=True)
#    is_valid_node_conf_file(get_node_conf_path(),
#            verbose=args.verbose,
#            quit=True)
#
#    # Starting WWNs checking
#    if verbose and not silent:
#        amd.stage_msg("Starting the wwns_conf prerequisites checks")
#
#    is_valid_wwns_conf_file(get_node_conf_path(),
#            verbose=args.verbose,
#            quit=True)
#
#    if verbose and not silent:
#         amd.ok_msg("End of infrastructure prerequisites\n\n")
# }}}


#       HERE IT GOES            ## {{{
# ------------------------------# 
# ------------------------------# 
amd.ok_msg("Here it goes:")
#### Actions# {{{
if (args.list or \
        args.longlist or \
        args.check or \
        args.test ) and (args.verbose):
    amd.ok_msg("Here is goes") 

# }}}
# TO REMOVE
if args.check:# {{{

    amd.ok_msg("Start of prerequisites checks:")
    if args.check == "mksysb":
      amd.ok_msg("Checking the mksysb of:"
              , args.source_lpar)
      # check if mksysb exists: # {{{
      mksysb_path=get_mksysb_path()
      if is_mksysb(mksysb_path):
        amd.ok_msg("  The file",
                mksysb_path,
                "exists in the right place:")
      else:
        amd.err_msg("  The mksysb file",
                mksysb_path,
                "does not exist on the /csmimages",
                exit_code=1)

      
# }}}
      # checking if mksysb file is older than 3 days:# {{{
      if not args.mksysb_age:
         age=3
      else:
         age=args.mksysb_age
  
      if is_mksysb_new(mksysb_path, age=age):
          amd.ok_msg("  The mksysb is newer than:",
          age,
          "days")
      else:
          amd.err_msg("  The mksysb is older than:",
                  age,
                  "days",
                  exit_code=2)
  
  # }}}
  # checking if mksysb if valid# {{{
      is_mksysb_valid(mksysb_path, verbose=args.verbose, quit=True)
  # }}}
  # checking if the rootvg of the mksysb if mirrored# {{{
      amd.ok_msg("  Checking if the rootvg of the mksysb is mirrored")
      if is_mksysb_rootvg_mirrored(mksysb_path,
              verbose=args.verbose,
              quit=True, silent=False):
          amd.info_msg("  For migration to SSP the rootvg will be unmirrored")
  # }}}
  # go to the mksysb processing image directory# {{{
      goto_mksysb_processing_dir(verbose=args.verbose)
  # }}}
  # Extracting the bosinst.data form mksysb# {{{
      amd.ok_msg("  Extracting the bosinst.data for processing")
      extract_mksysb_bosinst_data(verbose=args.verbose, quit=True)
  # }}}
  # Extracting the image.data form mksysb# {{{
      if is_mksysb_rootvg_mirrored(mksysb_path,  silent=True):
         amd.ok_msg("  Extracting the image.data for processing")
         extract_mksysb_image_data(verbose=args.verbose, quit=True)
  # }}}
  # UnMirroring the mksysb image.data data# {{{
      if is_mksysb_rootvg_mirrored(get_mksysb_path(),  silent=True):
         amd.ok_msg("  UnMirroring the rootvg in the image.data file")
         unmirror_mksysb_image_data(verbose=args.verbose, quit=True)
  # }}}
  # IS bosinst.data valid # {{{
      amd.ok_msg("  Checking the validity of the bosinst.data before processing it")
      is_bosinst_data_valid(verbose=args.verbose, quit=True)
  # }}}
  # BOSINST.data configuration# {{{
      amd.ok_msg("  Starting the bosinst.data configuration")
      mk_boinst_data(verbose=args.verbose, quit=True)
  # }}}


    if args.check == "nim":
      amd.ok_msg("Checking the master")
      am_i_nim_master(verbose=args.verbose, quit=True)

# }}}
if args.test:# {{{


    amd.ok_msg("Checking the master")
    am_i_nim_master(verbose=args.verbose, quit=True)
    amd.ok_msg("Checking if NIM processing dir exists")
    mk_nim_processing_dir(verbose=args.verbose, quit=True)

    amd.ok_msg("Removing the bosinst.data if it is defined")
    nim_remove_bosinst_data_res(verbose=args.verbose)

    amd.ok_msg("Defining the bosinst.data resource")
    nim_define_bosinst_data_res(verbose=args.verbose, quit=True)


    amd.ok_msg("Removing the image.data if it is defined")
    nim_remove_image_data_res(verbose=args.verbose)

    amd.ok_msg("Defining the image.data resource")
    nim_define_image_data_res(verbose=args.verbose, quit=True)


    amd.ok_msg("Removing the mksysb if it is defined")
    nim_remove_mksysb_res(verbose=args.verbose)

    amd.ok_msg("Defining the mksysb resource")
    nim_define_mksysb_res(verbose=args.verbose, quit=True)

    amd.ok_msg("Removing the fb_script if it is defined")
    nim_remove_fb_script_res(verbose=args.verbose)

    amd.ok_msg("Defining the first boot source")
    generate_fb_to_nim_res(verbose=args.verbose, quit=True)
    nim_define_fb_script_res(verbose=args.verbose, quit=True)

# }}}
if args.test2:# {{{

      # check if mksysb exists: # {{{
      mksysb_path=get_mksysb_path()
      if is_mksysb(mksysb_path):
        amd.ok_msg("  The file",
                mksysb_path,
                "exists in the right place:")
      else:
        amd.err_msg("  The mksysb file",
                mksysb_path,
                "does not exist on the /csmimages",
                exit_code=1)

      
# }}}
      # checking if mksysb file is older than 3 days:# {{{
      if not args.mksysb_age:
         age=5
      else:
         age=args.mksysb_age
  
      if is_mksysb_new(mksysb_path, age=age):
          amd.ok_msg("  The mksysb is newer than:",
          age,
          "days")
      else:
          amd.err_msg("  The mksysb is older than:",
                  age,
                  "days",
                  exit_code=2)
  
  # }}}
  # checking if mksysb if valid# {{{
      is_mksysb_valid(mksysb_path, verbose=args.verbose, quit=True)
  # }}}
  # checking if the rootvg of the mksysb if mirrored# {{{
      amd.ok_msg("  Checking if the rootvg of the mksysb is mirrored")
      if is_mksysb_rootvg_mirrored(mksysb_path,
              verbose=args.verbose,
              quit=True, silent=False):
          amd.info_msg("  For migration to SSP the rootvg will be unmirrored")
  # }}}
  # go to the mksysb processing image directory# {{{
      goto_mksysb_processing_dir(verbose=args.verbose)
  # }}}
  # Extracting the bosinst.data form mksysb# {{{
      amd.ok_msg("  Extracting the bosinst.data for processing")
      extract_mksysb_bosinst_data(verbose=args.verbose, quit=True)
  # }}}
  # Extracting the image.data form mksysb# {{{
      amd.ok_msg("  Extracting the image.data for processing")
      extract_mksysb_image_data(verbose=args.verbose, quit=True)
  # }}}
  # UnMirroring the mksysb image.data data# {{{
      if is_mksysb_rootvg_mirrored(get_mksysb_path(),  silent=True):
         amd.ok_msg("  UnMirroring the rootvg in the image.data file")
         unmirror_mksysb_image_data(verbose=args.verbose, quit=True)
  # }}}
  # IS bosinst.data valid # {{{
      amd.ok_msg("  Checking the validity of the bosinst.data before processing it")
      is_bosinst_data_valid(verbose=args.verbose, quit=True)
  # }}}
  # BOSINST.data configuration# {{{
      amd.ok_msg("  Starting the bosinst.data configuration")
      mk_boinst_data(verbose=args.verbose, quit=True)
  # }}}
    # NIM
      amd.ok_msg("Checking the master")
      am_i_nim_master(verbose=args.verbose, quit=True)

      amd.ok_msg("Checking if NIM processing dir exists")
      mk_nim_processing_dir(verbose=args.verbose, quit=True)
  
      amd.ok_msg("Removing the bosinst.data if it is defined")
      nim_remove_bosinst_data_res(verbose=args.verbose)
  
      amd.ok_msg("Defining the bosinst.data resource")
      nim_define_bosinst_data_res(verbose=args.verbose, quit=True)
  
  
      amd.ok_msg("Removing the image.data if it is defined")
      nim_remove_image_data_res(verbose=args.verbose)
  
      amd.ok_msg("Defining the image.data resource")
      nim_define_image_data_res(verbose=args.verbose, quit=True)
  
      amd.ok_msg("Removing the mksysb if it is defined")
      nim_remove_mksysb_res(verbose=args.verbose)
  
      amd.ok_msg("Defining the mksysb resource")
      nim_define_mksysb_res(verbose=args.verbose, quit=True)
  
      amd.ok_msg("Removing the fb_script if it is defined")
      nim_remove_fb_script_res(verbose=args.verbose)
  
      amd.ok_msg("Defining the first boot source")
      generate_fb_to_nim_res(verbose=args.verbose, quit=True)
      nim_define_fb_script_res(verbose=args.verbose, quit=True)


#       NODE# {{{
      # - Check if node_conf file exits
#       is_node_conf_file(get_node_conf_path(), verbose=args.verbose)


      is_node_conf_file(get_node_conf_path(),
              verbose=args.verbose,
              quit=True)



      if not args.verbose:
          amd.ok_msg("Performing node_conf validity check:")
          # - Check the validity of node_conf
#       is_valid_node_conf_file(get_node_conf_path(),
#               verbose=args.verbose,
#               quit=True)


      if not args.verbose:
          amd.ok_msg("Extracting LPAR options")
      get_node_conf_options_dic(get_node_conf_path(),
              verbose=args.verbose, quit=True)


      if not args.verbose:
          amd.ok_msg("Extracting LPAR options")
      get_node_conf_string(verbose=args.verbose, quit=True)





    
# }}}
#         WWW# {{{
      if not args.verbose:
          amd.ok_msg("Performing wwns_conf validity check:")

      is_valid_wwns_conf_file(get_node_conf_path(),
              verbose=args.verbose,
              quit=True)

      if not args.verbose:
          amd.ok_msg("Extracting the  WWNS")
      get_wwns_conf_options_dic(get_wwns_conf_path(),
                  verbose=args.verbose, quit=True)

# }}}
#       HMC# {{{

      if not args.verbose:
          amd.ok_msg("Checking the HMC connectivity ")
      is_hmc_accesible(args.hmc,user="hscroot",verbose=args.verbose, quit=True)

      if not args.verbose:
          amd.ok_msg("Determining the domain")
#       get_domain(verbose=args.verbose, quit=True)

      if not args.verbose:
          amd.ok_msg("Determining Destination MS serial number")
      get_target_ms_serial(verbose=args.verbose, quit=True)

      if not args.verbose:
          amd.ok_msg("Determining if the lpar is already NIM/BS configured")
      is_lpar_in_hmc(args.hmc,
              args.destination_managed_system,
              args.source_lpar,
              verbose=args.verbose,
              quit=True)


      if is_lpar_in_hmc(args.hmc,
              args.destination_managed_system,
              args.source_lpar,
              verbose=args.verbose,
              quit=False):

          if not args.verbose:
              amd.ok_msg("Determining the LPAR ID")
          get_lpar_id(args.hmc,
                  args.destination_managed_system,
                  args.source_lpar,
                  verbose=args.verbose, quit=True)


      if not args.verbose:
          amd.ok_msg("Determining the next available slot ID")
      get_next_lpar_id(args.hmc,
              args.destination_managed_system,
              verbose=args.verbose,
              quit=True)


 # }}}


# }}}


# ARGS.STAGE
if args.stage:
    # STAGE_11 : Do all# {{{
    if args.stage==11:
    #_l
        amd.info_msg("START OF STAGE NR. 1:  INFRASTRUCTURE PREREQUISITES")
        do_infra_prereq(args.hmc, 
           args.destination_managed_system,
           verbose=args.verbose, quit=True)

    #_2
        amd.info_msg("  START OF STAGE NR. 2:  MKSYSB OPERATIONS")
        do_mksysb_operations(args.hmc, 
           args.destination_managed_system,
           args.source_lpar,
           verbose=args.verbose,
           quit=True)

    #_3
        amd.info_msg("  START OF STAGE NR. 3 and 4:  HMC/VIOS OPERATIONS")
        do_hmc_vios_target_lpar_operations(args.hmc, 
           args.destination_managed_system,
           verbose=args.verbose, quit=True)

    #_4
        amd.info_msg("  START OF STAGE NR. 4:  LPAR ACTIVATION")
        do_lpar_all_activation_operations(args.hmc, 
           args.destination_managed_system,
           args.source_lpar,
           verbose=args.verbose, quit=True)
    #_5
        amd.info_msg("  START OF STAGE NR. 5:  NIM  OPERATIONS: DEFINE RESOURCES")
        do_all_NIM_define_operations(args.hmc, 
           args.destination_managed_system,
           verbose=args.verbose,
           quit=True)
    #_6
        amd.info_msg("  START OF STAGE NR. 6:  NIM  OPERATIONS: RESOURCES ALLOCATION")
        do_all_NIM_allocate_operations(args.source_lpar,
           args.hmc, 
           args.destination_managed_system,
           verbose=args.verbose,
           quit=True)

    #_7
        amd.info_msg("  START OF STAGE NR. 7: UNATTENDED INSTALLATION  ")
        do_all_NIM_bosinst(args.source_lpar,
           args.hmc, 
           args.destination_managed_system,
           prereq=True,
           force=args.FORCE,
           verbose=args.verbose,
           quit=True)
# }}}




#  Individual Stages


    # STAGE -1
    if args.stage==-1:
        if not args.SOURCE_CSM:
            amd.info_msg("Source CSM is missing")
            amd.info_msg("usage example: /opt/migratevm/migratevm.py  -q -1 -C aix00p04  -s s370en0 -D S04 -H lxsrvhmc0001")
            amd.err_msg("-C, --SOURCE_CSM is a required for this stage",exit_code=1)


        amd.info_msg("START OF STAGE NR. -1:  CONFIGURATION FILE COLLECTION")
        do_all_collect_info(args.SOURCE_CSM, verbose=args.verbose, quit=True)






    # STAGE1
    if args.stage==1:
        amd.info_msg("START OF STAGE NR. 1:  INFRASTRUCTURE PREREQUISITES")
        do_infra_prereq(args.hmc, 
           args.destination_managed_system,
           verbose=args.verbose, quit=True)

    # STAGE_2
    elif args.stage==2:
        # GENERATE FIRSTBOOT, UPDATE AME AND VLAN
        amd.info_msg("  START OF STAGE NR. 2:  PREMIGRATION OPERATIONS")
        amd.ok_msg("Generating node_firstboot, updating VLAN, VLANB and AME")
        do_all_premigration(verbose=args.verbose)

        # MKSYSB OPERATIONS
        do_mksysb_operations(args.hmc, 
           args.destination_managed_system,
           args.source_lpar,
           verbose=args.verbose,
           quit=True)




    # STAGE_3
    elif args.stage==3:
        #  CHECKING PARAMETERS# {{{
        # Checking parameters
        if not args.destination_managed_system:
         amd.err_msg("Missing mandatory argument for this stage:\n \
            -D DESTINATION_MANAGED_SYSTEM \n \
            e.g. migratevm.py -q 3 -s s248en0 -D S04 -H lxsrvhmc0001",
            exit_code=18)

        # Checking parameters
        if not args.hmc:
         amd.err_msg("Missing mandatory argument for this stage:\n \
            -H HMC \n \
            e.g. migratevm.py -q 3 -s s248en0 -D S04 -H lxsrvhmc0001",
            exit_code=18)
# }}}
        amd.ok_msg("Start of stage nr.:", args.stage,\
                ": Target hmc operations")

      # INFRA PREREQUISITES# {{{
        do_infra_prereq(args.hmc, 
           args.destination_managed_system,
           verbose=args.verbose, quit=True)
# }}}
      # Do HMC OPERATIONS# {{{
        do_hmc_vios_target_lpar_operations(args.hmc, 
           args.destination_managed_system,
           verbose=args.verbose, quit=True)
# }}}


    # STAGE_4
    elif args.stage==4:
        amd.info_msg("  START OF STAGE NR. 4:  LPAR ACTIVATION")
        do_lpar_all_activation_operations(args.hmc, 
           args.destination_managed_system,
           args.source_lpar,
           verbose=args.verbose)


    # STAGE_-4
    elif args.stage==-4:
        amd.info_msg("  START OF STAGE NR. -4:  LPAR DEACTIVATION")
        do_lpar_deactivate(args.hmc, 
           args.destination_managed_system,
           args.source_lpar,
           verbose=args.verbose)





    # STAGE_5
    elif args.stage==5:
        amd.info_msg("  START OF STAGE NR. 5:  NIM  OPERATIONS: DEFINE RESOURCES")
        do_all_NIM_define_operations(args.hmc, 
           args.destination_managed_system,
           verbose=args.verbose,
           quit=True)


    # STAGE_-5
    elif args.stage==-5:
        amd.info_msg("  START OF STAGE NR. -5:  NIM  OPERATIONS: REMOVE RESOURCES")
        do_all_NIM_remove_operations(args.hmc, 
           args.destination_managed_system,
           verbose=args.verbose,
           force=args.FORCE, 
           quit=True)



    # STAGE_6
    elif args.stage==6:
        amd.info_msg("  START OF STAGE NR. 6:  NIM  OPERATIONS: RESOURCES ALLOCATION")
        do_all_NIM_allocate_operations(args.source_lpar,
           args.hmc, 
           args.destination_managed_system,
           verbose=args.verbose,
           quit=True)


    # STAGE_-6
    elif args.stage==-6:
        amd.info_msg("  START OF STAGE NR. 6:  NIM  OPERATIONS: RESOURCES DEALLOCATION")
        do_all_NIM_deallocate_operations(args.source_lpar,
           args.hmc, 
           args.destination_managed_system,
           verbose=args.verbose,
           force=args.FORCE,
           quit=True)

    # STAGE_7
    elif args.stage==7:


        amd.ok_msg("Generating node_firstboot")
        do_generate_fb(verbose=args.verbose)


        amd.info_msg("  START OF STAGE NR. 2:  MKSYSB OPERATIONS")
        do_mksysb_operations(args.hmc, 
           args.destination_managed_system,
           args.source_lpar,
           verbose=args.verbose,
           quit=True)

        amd.info_msg("  START OF STAGE NR. 7: UNATTENDED INSTALLATION  ")
        do_all_NIM_bosinst(args.source_lpar,
           args.hmc, 
           args.destination_managed_system,
           prereq=True,
           force=args.FORCE,
           verbose=args.verbose,
           quit=True)


    elif args.stage==8:
        amd.info_msg("  START DEV_TEST  ")

        lpar_id = get_lpar_id(args.hmc,
                  args.destination_managed_system,
                  args.source_lpar,
                  verbose=True,
                  quit=True)


#        amd.ok_msg("Defining the spot resource")
#        nim_define_spot_res(verbose=args.verbose, quit=True)
#        amd.ok_msg("Removing the spot resource")
#        nim_remove_spot_res(verbose=args.verbose)
#


    # DEV:TEST
    # STAGE_12
    elif args.stage==12:
        nim_define_spot_res()
        amd.info_msg("  START OF STAGE NR. 12: DEV_TEST  ")

        amd.ok_msg("Defining the spot resource")
        nim_define_spot_res(verbose=args.verbose, quit=True)
        amd.ok_msg("Removing the spot resource")
        nim_remove_spot_res(verbose=args.verbose)



    # STAGE_77
    elif args.stage==77:
        amd.info_msg("  START OF STAGE NR. 77:  MKSYSB OPERATIONS")
        do_mksysb_operations(args.hmc, 
           args.destination_managed_system,
           args.source_lpar,
           verbose=args.verbose,
           quit=True)






# }}}

















