####################################################################
# (C) Copyright 2015-2016 Hewlett Packard Enterprise Development LP.
# @(#) Serviceguard UPCC Package Configuration Script.
# @(#) Product Name                :  HP Serviceguard
# @(#) Product Version             :  A.12.10.00
# @(#) Patch Name                  :  
#
# *** Note: This file MUST NOT be edited. *****
#
# Any changes made to it will be overwritten when you upgrade to the
# next release of HP Serviceguard.
#
# Changing this file may lead to unrecoverable package startup
# and/or shutdown problems.
#
###################################################################

###########################
## Source utility functions.
############################
. /etc/cmcluster.conf
SG_UTILS=${SGCONF}/scripts/mscripts/utils.sh
if [[ -f ${SG_UTILS} ]]; then
    . ${SG_UTILS}
    if (( $? != 0 ))
    then
        echo "ERROR: Unable to source package utility functions file: ${SG_UTILS}"
        exit 1
    fi
else
    echo "ERROR: Unable to find package utility functions file: ${SG_UTILS}"
    exit 1
fi

####################################################################
## Source the VMFS utility functions:
####################################################################
VMFS_COMMON_UTIL=${SGCONF}/scripts/sg/vmfs_common_util.sh
if [[ -f ${VMFS_COMMON_UTIL} ]]; then
    . ${VMFS_COMMON_UTIL}
    if (( $? != 0 ))
    then
        echo "ERROR: Unable to source package vmfs utility functions file: ${VMFS_COMMON_UTIL}"
        exit 1
    fi
else
    echo "ERROR: Unable to find package vmfs utility functions file: ${VMFS_COMMON_UTIL}"
    exit 1
fi

usage()
{
  cat >&2 <<EOM
  Usage:
    cmvmdiskquery -h
    cmvmdiskquery -n <uuid> -n <uuid> ......
    cmvmdiskquery -c <cmviewcl_output_file> -F <input_file>
    |------------------------------------------------------------------------------------------------------|
    | -n <uuid>                  | -F and -n option are mutually exclusive                                 |
    |------------------------------------------------------------------------------------------------------|
    | -F <input_file>            | -F and -n option are mutually exclusive                                 |
    |                            | Input file can have the following                                       |
    |                            | UUID: UUID of the cluster node, if already with -n option skip it here  |
    |                            | VMDK: The VMFS vmdk file(with dir/file.vmdk)                            |
    |                            | DS:   The name of the datastore in which the VMFS vdmk file exists      |
    |                            | SLOT: The slot on which the VMFS vmdk file will be attached             |
    |------------------------------------------------------------------------------------------------------|
    | -c <cmviewcl_output_file>  | Optional Param; if executed from vmfs_module this can be passed         |
    |------------------------------------------------------------------------------------------------------|
    Example Input file 
    UUID:564dca9a-eecf-f398-c588-d55b153dbc0f
    UUID:564df66b-0acb-41de-47b9-208a8260fad9
    VMDK:cluster/kf4.vmdk
    DS:kf1_kf3shared10GB2
    SLOT:1:1
    VMDK:cluster/kf4_1.vmdk
    DS:kf1_kf3shared10GB2
    SLOT:1:2
    VMDK:cluster/kf4_2.vmdk
    DS:kf1_kf3shared10GB2
    SLOT:1:3
    VMDK:cluster/nissan4.vmdk
    DS:kf1_kf3shared10GB3
    SLOT:2:1
EOM
    cleanup_before_exit 1
}

print_usage_if_help_or_no_arg()
{
  if [ $# -eq 0 ]; then
    usage
  fi
  if [ $# -eq 1 ] && \
     [ "$1" = "-h" ]; then
    usage
  fi
  return 0
}

print_usage_if_help_or_no_arg $*
typeset -i X=0
typeset input_file=""
declare -a array_of_uuid
typeset -i type_n_option=0
typeset -i type_f_option=0
typeset -i type_c_option=0

while [[ $# -ge 1 ]]
do
    key="$1"

    case $key in
    -n)
        type_n_option=1
        array_of_uuid[$X]="$2"
        if [[ "X${array_of_uuid[$X]}" == "X" ]]; then
            echo "UUID is missing"
            usage
        fi
        shift
        (( X = X + 1 ))
    ;;
    -F)
        type_f_option=1
        input_file="$2"
        if [[ "X$input_file" == "X" ]]; then
            echo "The Input file is missing"
            usage
        fi
        if [ ! -f $input_file ]; then
            echo "The Input file $input_file does not exist"
            usage
        fi
        shift
    ;;
    -c)
        type_c_option=1
        cmviewcl_output="$2"
        if [[ "X$cmviewcl_output" == "X" ]]; then
            echo "The cmviewcl output file is missing"
            usage
        fi
        if [ ! -f $cmviewcl_output ]; then
            echo "The cmviewcl output file $cmviewcl_output does not exist"
            usage
        fi
        shift
    ;;
    *)
        echo "Unknown Option :: $key"
        usage
        exit 1
    ;;
    esac
    shift
done

if (( type_n_option != 0 )) && (( type_f_option != 0 )); then
    echo "The command options -f and -n are mutually exclusive"
    usage
fi

# Utility functions
function read_uuid_from_file
{
    UUID=`cat $input_file | grep "UUID" | awk -F: '/UUID:/ {print $2}'`
    echo "$UUID"
}

function read_disks_info_from_file
{
    _disk_file=$1
    # Whatever has come just put it in a file remember to delete as part
    # of clean up
    cat $input_file | grep -v "UUID" >> $_disk_file
}

#MAIN
typeset -i type_esx=1
typeset -i type_vcenter=2
typeset -i set_failure=0

declare -a SG_NODE_UUID
declare -a SG_NODE_ESX_HOST
declare -a _uuid_list_per_host
declare -a _uuid_host
declare -a per_host_input_file
declare -a pid_list
declare -a pid_return_list
declare -a output_file_list
declare -a error_output_file_list

typeset script_name=${0##*/}
typeset vmfs_output=""
typeset vmfs_tmp_dir="/var/tmp"
typeset output_file=$vmfs_tmp_dir/$log_prefix"_output_file.$$"
typeset error_output_file=$vmfs_tmp_dir/$log_prefix"_error_output_file.$$"
typeset _f_input_file=$vmfs_tmp_dir/$log_prefix"_f_input_file.$$"

if (( $type_c_option == 0 )); then
    cache_cmviewcl_output_lx
fi

check_if_cluster_is_configured_with_esx_or_vcenter
cluster_type=$?

if (( $cluster_type == $type_esx )); then
    # Type Esx
    R=0
    if (( $type_n_option == 1 )); then
        for uuid in "${array_of_uuid[@]}"
        do
            SG_NODE_UUID[$R]=$uuid
            SG_NODE_ESX_HOST[$R]=`get_esx_host_name_from_uuid $uuid`
            if [[ "X${SG_NODE_ESX_HOST[$R]}" == "X" ]]; then
                echo "msgtype:ERROR|message=Missing UUID"
                cleanup_before_exit $FAILED_TO_POPULATE_OBJECT
            fi
            (( R = R + 1 ))
        done
    else
        uuid_list=`read_uuid_from_file`
        for uuid in $uuid_list
        do
            SG_NODE_UUID[$R]=$uuid
            SG_NODE_ESX_HOST[$R]=`get_esx_host_name_from_uuid $uuid`
            if [[ "X${SG_NODE_ESX_HOST[$R]}" == "X" ]]; then
                echo "msgtype:ERROR|message=Missing UUID"
                cleanup_before_exit $FAILED_TO_POPULATE_OBJECT
            fi
            (( R = R + 1 ))
        done
    fi
    # Create unique ESX host list from the available ESX hosts
    unique_esx_host_list=`echo "${SG_NODE_ESX_HOST[*]}" | tr ' ' '\n' | \
                          sort -u | tr '\n' ' ' | sed 's/^ *//g' | sed 's/ *$//g'`
    Y=0
    for host in $unique_esx_host_list
    do
        __uuid=""
        R=0
        while (($R < ${#SG_NODE_ESX_HOST[*]}))
        do
            if [[ $host = ${SG_NODE_ESX_HOST[$R]} ]]; then
                echo "UUID:${SG_NODE_UUID[$R]}" >> $_f_input_file$Y
            fi
            (( R = R + 1 ))
        done
        if (( $type_f_option == 1 ))
        then
            read_disks_info_from_file $_f_input_file$Y
        fi
        per_host_input_file[$Y]=$_f_input_file$Y
        _uuid_host[$Y]=$host # This will have the host for the above UUID list
        (( Y = Y + 1 ))
    done
else
    # Type vCenter
    Y=0
    _uuid_host[$Y]=`get_vcenter_name`
    if (( $type_n_option == 1 )); then
        for __uuid in "${array_of_uuid[@]}"
        do
            echo "UUID:$__uuid" >> $_f_input_file$Y
        done
    else
        uuid_list=`read_uuid_from_file`
        for __uuid in $uuid_list
        do
            echo "UUID:$__uuid" >> $_f_input_file$Y
        done
        read_disks_info_from_file $_f_input_file$Y
    fi
    per_host_input_file[$Y]=$_f_input_file$Y
fi

# Now we have the ESX-Host/vCenter and the respective UUID's
# Call the java utility now.

JAVA=`command -v java`
JAVA_TOOL=$SGSBIN/vmwutil
OP="query"

Y=0
# Need to still call this in background
while (($Y < ${#_uuid_host[*]}))
do
    (
    $JAVA -jar $JAVA_TOOL -o $OP -H ${_uuid_host[$Y]} -F ${per_host_input_file[$Y]} 1> $output_file$Y 2>$error_output_file$Y
    )&

    # store the name of the file in an array
    output_file_list[$Y]=$output_file$Y
    error_output_file_list[$Y]=$error_output_file$Y

    # store the background processes id in an array
    pid_list[$Y]="$!"
    (( Y = Y + 1 ))
done

# Check for errors
while (( Y > 0 ))
do
    pid=${pid_list[$Y-1]}
    wait $pid
    ret=$?
    if check_if_vm_object_error $ret; then
        set_failure=$ret
        cat ${output_file_list[$Y-1]}
    elif check_if_host_unreachable_error $ret; then
        set_failure=$ret
        cat ${output_file_list[$Y-1]}
    elif check_if_credential_xml_file_corrupted $ret; then
        set_failure=$ret
        cat ${output_file_list[$Y-1]}
    else
        # For other errors or success;
        # Let the caller decide what to do
        :
    fi
    pid_return_list[$Y-1]=$ret
    if [ -s ${error_output_file_list[$Y-1]} ]; then
        $LOGGER -t $script_name[$$] -f ${error_output_file_list[$Y-1]}
    fi
    (( Y = Y - 1 ))
done

# Collate the output if multiple esx hosts are configured:
if [[ $set_failure != 0 ]]; then
    cleanup_before_exit $set_failure
else
    Y=0
    ret=0

    while (($Y < ${#pid_list[*]}))
    do
        if (( ${pid_return_list[$Y]} != 0 )); then
            # This non zero value will be 3 or 4
            ret=${pid_return_list[$Y]}
        fi
        cat ${output_file_list[$Y]}
        (( Y = Y + 1 ))
    done

    # Exit
    cleanup_before_exit $ret
fi
