#!/bin/bash

SCRIPT_PATH=$(cd $(dirname $0);pwd)
INSTALL_ROOT="/opt/oss"

function checkUser()
{
    cur_user=`id -un`
    [[ ${cur_user} == "ossadm" ]] && return 0
    echo "The script must run with ossadm user."
    exit 1
}

function query_ip_type()
{
    local use_ipv6=$(python -c """
import json
import ipaddress
nodes_ip = []
with open('/opt/oss/manager/etc/sysconf/nodelists.json', 'r') as nodelist_f:
    f_json=json.load(nodelist_f)
    node_list = f_json.get('nodeList', {})
    node_list = sorted(node_list.items(), key=lambda item: int(item[0]))
    for index, node_info in node_list:
        if index == '0':
            for ip_item in node_info.get('IPAddresses', []):
                if 'maintenance' in ip_item.get('usage', []):
                    node_ip = ip_item['IP']
                    if ipaddress.ip_interface(node_ip).version == 4:
                        print('IPv4')
                    else:
                        print('IPv6')
""")
    echo "${use_ipv6}"
}

function queryParam()
{
    . "${INSTALL_ROOT}"/manager/bin/engr_profile.sh
    DATE="`date +%Y%m%d%H%M%S`"
    if [[ ! -d /tmp/upgrade_info_common${DATE} ]]
    then
        rm -rf /tmp/upgrade_info_common${DATE}
    fi
    mkdir -p /tmp/upgrade_info_common${DATE}
    if [[ ! -f "${INSTALL_ROOT}"/manager/tools/resmgr/queryproduct.sh ]]; then
        echo "no queryproduct.sh" >> /tmp/upgrade_info_common${DATE}/excute.log
        exit 2
    fi
    "${INSTALL_ROOT}"/manager/tools/resmgr/queryproduct.sh -pn all -output /tmp/upgrade_info_common${DATE}
    if [[ $? != 0 ]]
    then
        echo "queryproduct.sh failed" >> /tmp/upgrade_info_common${DATE}/excute.log
        exit 1
    fi

    product_name=$(ls /opt/oss/manager/var/tenants/ | grep -v manager | grep Insight)
    if [[ ! -f /tmp/upgrade_info_common${DATE}/product_${product_name}.json ]]; then
        echo "the product is not FabricInsight. skip this step" >> /tmp/upgrade_info_common${DATE}/excute.log
        exit 2
    fi

    os_type=$(cat /etc/os-release | grep '^NAME'|awk -F'=' '{print $2}')
    is_suse=$([ '"SLES"' == ${os_type} ] && echo 'true' || echo 'false')
    switch_kmc=$([ -f /opt/oss/manager/etc/cipher/cloudsop_cipher_mode.flag ] && echo 'true' || echo 'false')
    upgrade_ndp=$([ -d /opt/oss/${product_name}/apps/NdpNameNodeService ] && echo 'false' || echo 'true')
    use_ipv6=$(query_ip_type)
    tmpdir="/tmp/upgrade_info_common${DATE}"
    python -c """
import json
import os
import stat
FILE_FLAGS = os.O_RDWR | os.O_CREAT | os.O_TRUNC
FILE_MODES = stat.S_IWUSR | stat.S_IRUSR

product_name = '${product_name}'
product_json_file = '{0}/product_{1}.json'.format('${tmpdir}', product_name)
with open(product_json_file, 'r') as product_json:
    product_json_info = json.load(product_json)
if 'V100R021C00' in product_json_info['productext']['product_version']:
    is_r21c00 = 'true'
else:
    is_r21c00 = 'false'
server_info = {
    'product': product_name,
    'deployment_plan': product_json_info['productext']['featureGroup'],
    'sceneid': product_name,
    'is_nce_analyzer_add_pkg': {product_name: 'TRUE'},
    'show_switch_kmc': '${switch_kmc}',
    'is_suse': '${is_suse}',
    'is_r21c00': is_r21c00,
    'upgrade_ndp': '${upgrade_ndp}',
    'use_ipv6': '${use_ipv6}'
}
server_info_file = os.path.join('${SCRIPT_PATH}' ,'serverinfo{}.json'.format(product_name))
with os.fdopen(os.open(server_info_file, FILE_FLAGS, FILE_MODES), 'w') as server_info_json:
    json.dump(server_info, server_info_json, indent=2)
"""
    if [[ -f ${SCRIPT_PATH}/serverinfo${product_name}.json ]]
    then
        echo "generate serverinfo${product_name}.json success" >> /tmp/upgrade_info_common${DATE}/excute.log
        return 0
    fi
    echo "generate serverinfo${product_name}.json failed" >> /tmp/upgrade_info_common${DATE}/excute.log
    return 1
}

checkUser
queryParam
result=$?
if [[ ${result} -eq 0 ]]
then
    echo "paramcfgFabricInsight.sh script run successfully " >> /tmp/upgrade_info_common${DATE}/excute.log
    echo 0
elif [[ ${result} -eq 2 ]]
then
    echo "Not FabricInsight Scenario" >> /tmp/upgrade_info_common${DATE}/excute.log
    echo 2
else
    echo "paramcfgFabricInsight script run faied!" >> /tmp/upgrade_info_common${DATE}/excute.log
    echo 1
fi

exit ${result}
