#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import requests
import sys
import socket
import subprocess
import csv
import json
reload(sys)
sys.setdefaultencoding('utf8')

CMDB_URL = "http://api-gw.service.ucloud.cn/cmdb"
# cmdb 公用只读帐号 cmdb.guest
API_KEY = {"api-key":"ebd9f8ee5a7b402389e43234499d46be"}

BASE_DIR = os.path.dirname(os.path.realpath(__file__))


def get_info_cmdb(item_type, info, env_flag):
    cmdb_result = None
    if item_type == 'Server':
        offline_file = os.path.join(BASE_DIR,'cmdb/','server.csv')
        if env_flag == 'offline':
            if os.path.isfile(offline_file):
                with open(offline_file) as f:
                    server = csv.DictReader(f)
                    for row in server:
                        if row['SN'] == info:
                            cmdb_result = row
        else:
            params = {"category": "Server", "q": "SN=={sn}".format(sn=info),
                      "fields": "(Usage,SecUsage,IDC,IP,BondIP,IPMI,AssetNo,SN,Manufacture,ManufactureType,MachineType,Owner,OperationalStatus)"}
            r = requests.get(CMDB_URL+'/v2/ci/search', headers=API_KEY, params=params, timeout=5)
            if r.status_code != 200:
                print("request cmdb failed , code is not 200")
                print(params)
                print(r.text)
                sys.exit(1)
            cmdb_result = r.json()['data'][0]
        if not cmdb_result:
            print("search cmdb failed")
            sys.exit(1)

        info = {}
        info['Usage'] = cmdb_result['Usage']
        info['SecUsage'] = cmdb_result['SecUsage']
        info['IDC'] = cmdb_result['IDC']
        info['IP'] = cmdb_result['IP']
        info['BondIP'] = cmdb_result['BondIP']
        info['IPMI'] = cmdb_result.get('IPMI','')
        info['AN'] = cmdb_result.get('AssetNo','')
        info['SN'] = cmdb_result['SN']
        info['Manufacture'] = cmdb_result['Manufacture']
        info['ManufactureType'] = cmdb_result['ManufactureType']
        info['MachineType'] = cmdb_result['MachineType']
        info['OperationalStatus'] = cmdb_result.get('OperationalStatus','')
        info['Owner'] = cmdb_result.get('Owner','').replace(u"\u3000","")
        return info
    elif item_type == 'VMServer':
        offline_file = os.path.join(BASE_DIR,'cmdb/','vmserver.csv')
        if env_flag == 'offline':
            if os.path.isfile(offline_file):
                with open(offline_file) as f:
                    server = csv.DictReader(f)
                    for row in server:
                        if row['IP'] == info:
                            cmdb_result = row
        else:
            params = {"category": "VMServer", "q": "IP=={ip}".format(ip=info),
                      "fields": "(Usage,SecUsage,IP,IDC,Owner,OperationalStatus)"}
            r = requests.get(CMDB_URL+'/v2/ci/search', headers=API_KEY, params=params)
            if r.status_code != 200:
                print("request cmdb failed , code is not 200")
                print(params)
                print(r.text)
                sys.exit(1)
            cmdb_result = r.json()['data'][0]
        if not cmdb_result:
            print("search cmdb failed")
            sys.exit(1)

        info = {}
        info['Usage'] = cmdb_result['Usage']
        info['SecUsage'] = cmdb_result['SecUsage']
        info['IP'] = cmdb_result['IP']
        info['IDC'] = cmdb_result['IDC']
        info['OperationalStatus'] = cmdb_result['OperationalStatus']
        info['Owner'] = cmdb_result.get('Owner','').replace(u"\u3000","")
        return info
    else:
        print("Unknon VMFLAG")
        sys.exit(1)


# get raid model
def get_info_raid(info, env_flag):
    offline_file = os.path.join(BASE_DIR,'cmdb/','cmdb_raid-info.json')
    raid_conf = None
    if env_flag == 'offline':
        if os.path.isfile(offline_file):
            with open(offline_file) as f:
                cmdb_result = json.loads(f.read())
            raid_conf = []
            for n,i in enumerate(cmdb_result['data']):
                if i['machine_type'] == info['MachineType']:
                    raid_conf.append(i)
    else:
        params = {'machine_type': info['MachineType']}
        r = requests.get(CMDB_URL+'/v2/machine-types/raid-info', headers=API_KEY, params=params)

        if r.status_code != 200:
            print("request raid failed , code is not 200")
            print(r.text)
            sys.exit(1)

        raid_conf = r.json()['data']
    if not raid_conf:
        print("search raid-info failed")
        sys.exit(1)

    tmp0 = {}
    tmp1 = {}
    tmp2 = {}
    tmp3 = {}
    # 之前的逻辑存在错误，导致部分机器 physical/053-check-datadisk-count.sh 脚本出现 交付检测失败的情况,即物理机磁盘数是正确而检测结果错误。如： 2102311GWE10H1000089 udb mysql S8-U1-V3
    # tmp0 一二级业务都相同 > tmp1 一级业务相同 二级业务 * > tmp2 一级业务 *  > 不存在
    for i in raid_conf:
        if i['usage'] == info['Usage']:
            if i['secusage'] == info['SecUsage']:
                tmp0['raid_info'] = i['raid_info']
                tmp0['memory'] = i['memory']
                return tmp0
            elif i['secusage'] == "*":
                tmp1['raid_info'] = i['raid_info']
                tmp1['memory'] = i['memory']
        elif i['usage'] == "*":
            tmp2['raid_info'] = i['raid_info']
            tmp2['memory'] = i['memory']
        else:
            tmp3['raid_info'] = ""
            tmp3['memory'] = ""

    if tmp1:
        return tmp1
    elif tmp2:
        return tmp2
    elif tmp3:
        return tmp3



def get_ip():
    try:
        s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        s.connect(('192.168.168.106',80))
        ip = s.getsockname()[0]
        s.close()
    except:
        args = "ip addr  |egrep 'eth0|eth2|net0|net2' |grep  -w inet  | grep -v 127.0.0.1 | awk '{print $2}' | cut -d '/'  -f 1"
        p = subprocess.Popen(args, shell=True, stdout=subprocess.PIPE)
        ip = list(p.communicate())[0].strip()
    return ip

def get_arch():
    args = "lscpu|grep 'Architecture:'|awk '{print $2}'"
    p = subprocess.Popen(args, shell=True, stdout=subprocess.PIPE)
    arch = list(p.communicate())[0].strip()
    return arch

def get_sn():
    arch = get_arch()
    if arch == 'aarch64':
        args = "cat /ucloud/exports.ini |grep UCLOUD_SN|awk -F '=' '{print $2}'"
    else:
        args = "dmidecode -s system-serial-number |grep -v ^#|sed 's/ //g'"
    p = subprocess.Popen(args, shell=True, stdout=subprocess.PIPE)
    sn = list(p.communicate())[0].strip()
    return sn


def main(item_type, env_flag):
    if item_type == 'Server':
        sn = get_sn()
        cmdb_info = get_info_cmdb(item_type, sn, env_flag)
        raid_info = get_info_raid(cmdb_info, env_flag)
        if not raid_info:
            print("get raid info failed ")
            sys.exit(1)

        memory = raid_info['memory'].replace('G', '')

        cmdbinfo = "Usage:" + cmdb_info['Usage'] + "\n" \
            + "SecUsage:" + cmdb_info['SecUsage'] + "\n" \
            + "IDC:" + cmdb_info['IDC'] + "\n" \
            + "HOSTIP:" + cmdb_info['IP'] + "\n" \
            + "BondIP:" + cmdb_info['BondIP'] + "\n" \
            + "IPMI:" + cmdb_info['IPMI'] + "\n" \
            + "AN:" + cmdb_info['AN'] + "\n" \
            + "SN:" + cmdb_info['SN'] + "\n" \
            + "Manufacture:" + cmdb_info['Manufacture'] + "\n" \
            + "ManufactureType:" + cmdb_info['ManufactureType'] + "\n" \
            + "MachineType:" + cmdb_info['MachineType'] + "\n" \
            + "Owner:" + cmdb_info['Owner'] + "\n" \
            + "OperationalStatus:" + \
            cmdb_info['OperationalStatus'] + "\n"
        # write info to cmdb.info
        raidinfo = "RaidInfo:" + raid_info['raid_info'] + "\n"
        meminfo = "Memory:" + memory + "\n"
        with open("/tmp/os_init/cmdb.info", "w") as fd:
            fd.write(cmdbinfo)
            fd.write(raidinfo)
            # write memory to cmdb.info
            fd.write(meminfo)
    elif item_type == 'VMServer':
        ip = get_ip()
        cmdb_info = get_info_cmdb(item_type, ip, env_flag)
        cmdbinfo = "Usage:" + cmdb_info['Usage'] + "\n" \
            + "SecUsage:" + cmdb_info['SecUsage'] + "\n" \
            + "HOSTIP:" + cmdb_info['IP'] + "\n" \
            + "IDC:" + cmdb_info['IDC'] + "\n" \
            + "Owner:" + cmdb_info['Owner'] + "\n" \
              + "OperationalStatus:" + \
            cmdb_info['OperationalStatus'] + "\n"
        with open("/tmp/os_init/cmdb.info", "w") as fd:
            fd.write(cmdbinfo)

if __name__ == '__main__':
    item_type = sys.argv[1]
    try:
        env_flag = sys.argv[2]
    except Exception as e:
        env_flag = 'pro'

    main(item_type, env_flag)
