URL = "https://openhardwaremonitor.org/files/openhardwaremonitor-v0.8.0-beta.zip"

import os
src_path=os.environ['TEMP']

import zipfile
import ctypes
import sys
import platform
import _winreg
import ssl
import shutil
import subprocess
import time
ssl._create_default_https_context = ssl._create_unverified_context

class disable_file_system_redirection:
        _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
        _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection
        def __enter__(self):
            self.old_value = ctypes.c_long()
            self.success = self._disable(ctypes.byref(self.old_value))
        def __exit__(self, type, value, traceback):
            if self.success:
                self._revert(self.old_value)

def Download(src_path, URL):
    import urllib2
    fileName = 'openhardwaremonitor.zip'
    fp = os.path.join(src_path, fileName)
    request = urllib2.Request(URL, headers={'User-Agent' : "Magic Browser"})
    parsed = urllib2.urlopen(request)
    if os.path.exists(src_path):
        print "Path already exists"
    if not os.path.exists(src_path):
        os.makedirs(src_path)
        print "Path created"
    with open(fp, 'wb') as f:
        while True:
            chunk=parsed.read(100*1000*1000)
            if chunk:
                f.write(chunk)
            else:
                break
    print "The file downloaded successfully in specified path"
    return fp


file_zip=os.environ['PROGRAMDATA']
file_zip1=file_zip+r'\openhardwaremonitor'
file_path = file_zip1+r'\OpenHardwareMonitor\OpenHardwareMonitor.exe'

def filezip(zip_path,file_zip):
    with disable_file_system_redirection():
        with zipfile.ZipFile(zip_path,"r") as zip_ref:
            zip_ref.extractall(file_zip1)
            print 'file unzipped to ' +file_zip1

if not os.path.isfile(file_path):
    zip_path=Download(src_path, URL)
    filezip(zip_path,file_zip1)

if os.path.isfile(file_path):        
    with disable_file_system_redirection():
        os.startfile(file_path)
        
else:
    print '%s is not found.'%path


    
time.sleep(30)
ps_content=r'''
$cputemp = get-wmiobject -namespace root\OpenHardwareMonitor -query 'select * from Sensor where Identifier ="/intelcpu/0/temperature/0"  ' 
echo "CPU Temp" 
if ($cputemp -eq $null){
echo 0}else{
echo $cputemp.value
}



$gputemp = get-wmiobject -namespace root\OpenHardwareMonitor -query 'select * from Sensor where Identifier ="/nvidiagpu/0/temperature/0"  ' 
echo "GPU Temperature"
if ($gputemp -eq $null){
echo 0}else{
echo $gputemp.value
}
$hddtemp = get-wmiobject -namespace root\OpenHardwareMonitor -query 'select * from Sensor where Identifier ="/hdd/0/temperature/0" ' 
echo "HDD Temp" 
if ($hddtemp -eq $null){
echo 0}else{
echo $hddtemp.value
}


$mottemp = get-wmiobject -namespace root\OpenHardwareMonitor -query 'select * from Sensor where Identifier in ('/lpc/ITE IT8620E/temperature/0', '/lpc/IT8628E/temperature/0', '/lpc/IT8655E/temperature/0', '/lpc/IT8665E/temperature/0', '/lpc/IT8686E/temperature/0', '/lpc/IT8688E/temperature/0', '/lpc/IT8705F/temperature/0', '/lpc/IT8712F/temperature/0', '/lpc/IT8716F/temperature/0', '/lpc/IT8718F/temperature/0', '/lpc/IT8720F/temperature/0', '/lpc/IT8721F/temperature/0', '/lpc/IT8726F/temperature/0', '/lpc/IT8728F/temperature/0', '/lpc/IT8771E/temperature/0', '/lpc/IT8772E/temperature/0', '/lpc/IT8792E/temperature/0', '/lpc/IT8795EFintek F71808E/temperature/0', '/lpc/F71858/temperature/0', '/lpc/F71862/temperature/0', '/lpc/F71868AD/temperature/0', '/lpc/F71869/temperature/0', '/lpc/F71869A/temperature/0', '/lpc/F71882/temperature/0', '/lpc/F71889ED/temperature/0', '/lpc/F71889AD/temperature/0', '/lpc/F71889FNuvoton NCT6102D/temperature/0', '/lpc/NCT6106D/temperature/0', '/lpc/NCT6771F/temperature/0', '/lpc/NCT6772F/temperature/0', '/lpc/NCT6775F/temperature/0', '/lpc/NCT6776F/temperature/0', '/lpc/NCT6779D/temperature/0', '/lpc/NCT6791D/temperature/0', '/lpc/NCT6792D/temperature/0', '/lpc/NCT6792D-A/temperature/0', '/lpc/NCT6793D/temperature/0', '/lpc/NCT6795D/temperature/0', '/lpc/NCT6796D/temperature/0', '/lpc/NCT6796D-R/temperature/0', '/lpc/NCT6797D/temperature/0', '/lpc/NCT6798DWinbond W83627DHG/temperature/0', '/lpc/ W83627DHG-P/temperature/0', '/lpc/W83627EHF/temperature/0', '/lpc/W83627HF/temperature/0', '/lpc/W83627THF/temperature/0', '/lpc/W83667HG/temperature/0', '/lpc/W83667HG-B/temperature/0', '/lpc/W83687THF/temperature/0')' 
echo "Motherboard Temp" 
if ($mottemp -eq $null){
echo 0}else{
echo $mottemp.value
}
wmic diskdrive get status
'''
# motherboards=['ITE IT8620E', 'IT8628E', 'IT8655E', 'IT8665E', 'IT8686E', 'IT8688E', 'IT8705F', 'IT8712F', 'IT8716F', 'IT8718F', 'IT8720F', 'IT8721F', 'IT8726F', 'IT8728F', 'IT8771E', 'IT8772E', 'IT8792E','IT8795E'
# 'Fintek F71808E', 'F71858', 'F71862', 'F71868AD', 'F71869', 'F71869A', 'F71882', 'F71889ED', 'F71889AD', 'F71889F'
# 'Nuvoton NCT6102D', 'NCT6106D', 'NCT6771F', 'NCT6772F', 'NCT6775F', 'NCT6776F', 'NCT6779D', 'NCT6791D', 'NCT6792D', 'NCT6792D-A', 'NCT6793D', 'NCT6795D', 'NCT6796D', 'NCT6796D-R', 'NCT6797D', 'NCT6798D'
# 'Winbond W83627DHG',' W83627DHG-P', 'W83627EHF', 'W83627HF', 'W83627THF', 'W83667HG', 'W83667HG-B', 'W83687THF']



def ecmd(command):
    import ctypes
    from subprocess import PIPE, Popen

    with disable_file_system_redirection():
        obj = Popen(command, shell = True, stdout = PIPE, stderr = PIPE)
    out, err = obj.communicate()
    ret=obj.returncode
    if ret==0:
        if out:
            return out.strip()
        else:
            return ret
    else:
        if err:
            return err.strip()
        else:
            return ret

file_name='powershell_file.ps1'
file_path=os.path.join(os.environ['TEMP'], file_name)
print file_path
with open(file_path, 'wb') as wr:
    wr.write(ps_content)



ecmd('powershell "Set-ExecutionPolicy RemoteSigned"')
output = ecmd('powershell "%s"'%file_path)
print output

os.remove(file_path)
        
os.system("TASKKILL /F /IM OpenHardwareMonitor.exe")

def alert(arg): 
    sys.stderr.write("%d%d%d" % (arg, arg, arg))

ls=str(output).split('\n')
if int(ls[1])>70:
    print("Cpu Temperature is higher",ls[1])
    alert(1)
elif int(ls[3])>70:
    print("Gpu Temperature is higher",ls[3])
    alert(1)
elif int(ls[5])>70:
    print("HardDisk Temperature is higher",ls[5])
    alert(1)
elif int(ls[7])>70:
    print("Motherboard Temperature is higher",ls[7])
    alert(1)
elif ls[9]!='OK':
    print("Harddisk status failed",ls[9])
    alert(1)
else:
	print("Hardware Temperature is low")
	alert(0)