import platform
machineArch = platform.machine()

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

cpuinfo = process_util.executeCmd('kstat -m cpu_info')
cputype = None
for l in cpuinfo.split('\n'):
    if l and l.startswith('cpu_type'):
        cputype = ' '.join(l.split()[1:])
        break

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([platform.system(), platform.release()])

serverInfoV2 = None
def initServerV2():
    global serverInfoV2

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

    serverInfoV2 = {
        "hostname":process_util.executeCommandShellWithTimeout('''hostname'''),
        "model":process_util.executeCommandShellWithTimeout('''echo `prtconf -b |grep banner-name |cut -f2 -d:`'''),
        "hwSerial":process_util.executeCommandShellWithTimeout("""prtdiag -v | awk '/Chassis Serial/{getline; getline; print}'"""),
        "OSVersion":process_util.executeCommandShellWithTimeout('''echo `uname -o` `uname -v` `uname -p` \(`uname -s` `uname -r`\)'''),
        "OSType":process_util.executeCommandShellWithTimeout('''uname -s'''),
        "firmware":process_util.executeCommandShellWithTimeout("""prtdiag -v | awk '/FW Version/{getline; getline; getline; print }'"""),
        "nCores":process_util.executeCommandShellWithTimeout("""kstat -m cpu_info |grep core_id | awk '{ print $2 }' | sort -u | wc -l | tr -d ' '"""),
        "lCores":process_util.executeCommandShellWithTimeout("""kstat -m cpu_info |grep core_id | awk '{ print $2 }' | wc -l | tr -d ' '"""),
        "frequency":process_util.executeCommandShellWithTimeout("""kstat -m cpu_info | grep clock_MHz | head -1 | awk '{print $2}'"""),
        "cpuType": process_util.executeCommandShellWithTimeout("""prtdiag | awk '/Implementation/{getline; getline; print $4}'"""),
        "memTotal":  process_util.executeCommandShellWithTimeout("""prtconf | grep "^Memory size:" | awk '{print $3}'"""),
        "IP_all":  process_util.executeCommandShellWithTimeout("""ifconfig -a | grep -w inet | egrep -v "127.0.0.1|0.0.0.0" | awk '{print $2}' | cut -d'/' -f 1"""),
        "timezone":  process_util.executeCommandShellWithTimeout("""cat /etc/default/init | grep ^TZ | awk -F= '{print $2}'"""),    
        "bootTime": bootTime,
    }
    if serverInfoV2['model']:
        serverInfoV2['serverType'] = 'Physical'

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

    return serverInfoV2

