import platform
machineArch = platform.machine()

import whatap.util.process_util as process_util
import psutil
import time

isIA = False
cpuinfo = None
cputype = None
cpu_core = psutil.cpu_count()
totalsize = psutil.virtual_memory().total


system_info = {}

def GetCPUNum():
    return cpu_core

def GetCPUType():
    return cputype

def GetMemorySize():
    return totalsize

def GetMachineArch():
    return machineArch

def GetOSRelease():
    return " ".join(["HPUX", platform.release()])




serverInfoV2 = None
_boot_epoch_ts = None


def _hpvminfo_text():
    return process_util.executeCommandShellWithTimeout(
        'command -v hpvminfo >/dev/null 2>&1 && hpvminfo 2>/dev/null'
    )


def _is_vpar():
    rc = process_util.executeCommandShellWithTimeout(
        'command -v vecheck >/dev/null 2>&1 && vecheck >/dev/null 2>&1; echo $?'
    )
    if rc == '0':
        return True

    out = process_util.executeCommandShellWithTimeout(
        'command -v vparstatus >/dev/null 2>&1 && '
        '{ vparstatus -P 2>/dev/null; vparstatus 2>/dev/null; }'
    )
    if not out:
        return False
    markers = (
        'Current Virtual Partition Version:',
        'Commands product information:',
        'Monitor product information:',
    )
    if any(m in out for m in markers):
        return True
    low = out.lower()
    return 'virtual partition' in low or 'vpar' in low


def _classify_server(hpvm_out):
    if hpvm_out and 'Running inside an HPVM guest' in hpvm_out:
        return 'Virtual', 'Integrity VM guest'
    if _is_vpar():
        return 'Virtual', 'vPar'
    if hpvm_out and 'Running on an HPVM host' in hpvm_out:
        return 'Virtual', 'Integrity VM host'
    return 'Physical', 'Bare metal / nPar'


def initServerV2():
    global serverInfoV2
    global isIA
    global _boot_epoch_ts

    archCheck = process_util.executeCommandShellWithTimeout('''uname -m | grep -i ia64 | wc -l''')
    if archCheck == '1':
        isIA = True

    osVerStr = process_util.executeCommandShellWithTimeout('''uname -r''')
    osVer = 0
    if osVerStr[0] == 'B':
        osVer = float(osVerStr[2:])
    else:
        osVer = float(osVerStr)

    bootEpoch = process_util.executeCommandShellWithTimeout(''' uptime | perl -ne \'/.*up (\d+) days, +(\d+):(\d+),.*/; $total=((($1*24+$2)*60+$3)*60); $now=time(); $now-=$total; print $now,"\n";\' ''')
    _boot_epoch_ts = float(bootEpoch)
    bootTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(_boot_epoch_ts))


    serverInfoV2 = {
        "hostname": process_util.executeCommandShellWithTimeout(''' hostname '''),
        "OSType": process_util.executeCommandShellWithTimeout(''' uname -s '''),
        "OSVersion": process_util.executeCommandShellWithTimeout('''echo `uname -s` `uname -m` `swlist -l bundle QPKBASE | grep QPKBASE | head -1 | awk '{print $2}'`'''),
        "hwSerial": process_util.executeCommandShellWithTimeout('''getconf MACHINE_SERIAL'''),
        "lCores": process_util.executeCommandShellWithTimeout(''' ioscan -kfnC processor | grep processor | wc -l '''),
        "cpuType": process_util.executeCommandShellWithTimeout(''' grep $(printf "0x%x" $(getconf _SC_CPU_VERSION)) /usr/include/sys/unistd.h | awk -F\'*\' \'{print $2}\' '''),
        "IP_all": process_util.executeCommandShellWithTimeout(''' netstat -in | egrep -v "^Name|127.0.0.1|0.0.0.0" | awk \'{print $4}\' '''),
        "timezone": process_util.executeCommandShellWithTimeout(''' cat /etc/TIMEZONE | grep ^TZ | awk -F= \'{print $2}\' '''),
        "bootTime": bootTime,
    }

    model = process_util.executeCmd('model').strip()
    serverInfoV2['model'] = model if model else "Unknown"

    server_type, server_type_detail = _classify_server(_hpvminfo_text())
    serverInfoV2['serverType'] = server_type
    serverInfoV2['serverTypeDetail'] = server_type_detail
    serverInfoV2['systemArchitecture'] = platform.machine()

    if isIA:
        serverInfoV2['firmware'] = process_util.executeCommandShellWithTimeout(''' /usr/contrib/bin/machinfo |grep "Firmware revision" | awk \'{print $NF}\' ''')
        serverInfoV2['memTotal'] = process_util.executeCommandShellWithTimeout(''' /usr/contrib/bin/machinfo | grep Memory | sed s/\' =\'/\':\'/g | awk \'{print $2}\' ''')
        if osVer > 11.30:
            serverInfoV2['nCores'] = process_util.executeCommandShellWithTimeout(''' /usr/contrib/bin/machinfo | grep cores | grep -v logical | awk \'{print $1}\' ''')
            serverInfoV2['frequency'] = process_util.executeCommandShellWithTimeout(''' echo `/usr/contrib/bin/machinfo |grep "GHz" |cut -f3 -d "(" | awk \'{print $1}\'`"*1000" | bc | awk -F. \'{print $1}\' ''')
        else:
            serverInfoV2['nCores'] = process_util.executeCommandShellWithTimeout(''' /usr/contrib/bin/machinfo | grep "Number of CPU" | awk \'{print $NF}\' ''') 
            serverInfoV2['frequency'] = process_util.executeCommandShellWithTimeout(''' /usr/contrib/bin/machinfo | grep "MHz" | awk \'{print $4}\' ''')
    else:
        serverInfoV2['firmware'] = process_util.executeCommandShellWithTimeout(''' grep "PDC Version" /var/tombstones/ts99 | head -1 | awk -F: \'{print $2}\' | sed s/-//g | sed s/\' \'//g ''')
        serverInfoV2['memTotal'] = process_util.executeCommandShellWithTimeout(''' swapinfo | grep ^memory | awk \'{print $2/1024}\' ''')
        serverInfoV2['nCores'] = process_util.executeCommandShellWithTimeout(''' ioscan -kfnC processor | grep processor |wc -l ''')
        serverInfoV2['frequency'] = process_util.executeCommandShellWithTimeout(''' echo itick_per_usec/D | adb /stand/vmunix /dev/kmem | tail -1 | awk \'{print $2}\' ''')

    if osVer > 11.30:
        serverInfoV2['x86Socket'] = process_util.executeCommandShellWithTimeout(''' machinfo | grep socket | grep -v per | awk \'{print $1}\' ''')

def GetServerInfoV2():
    global serverInfoV2
    if serverInfoV2 == None:
        initServerV2()

    if _boot_epoch_ts is not None:
        serverInfoV2['uptime'] = int((time.time() - _boot_epoch_ts) / 86400)

    return serverInfoV2


def GetNtpInfo():
    from whatap.osinfo.ntp_common import build_ntp_info
    daemon = ""
    in_use = False
    try:
        for d_name in ('xntpd', 'ntpd'):
            ps_out = process_util.executeCommandShellWithTimeout(
                'ps -ef 2>/dev/null | grep %s | grep -v grep | head -1' % d_name, timeout=5).strip()
            if ps_out:
                daemon = d_name
                in_use = True
                break
    except Exception:
        pass
    return build_ntp_info(daemon, in_use)
