import os
import csv
from subprocess import Popen, PIPE
import zipfile
import ssl
import urllib2
import ctypes
import shutil

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 ecmd(command):   
    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("something went wrong. returncode: %s"%(ret))

def downloadFile(DownTo, fromURL):
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'}
    context = ssl._create_unverified_context()
    request = urllib2.Request(fromURL, headers=headers)
    req = urllib2.urlopen(request,context=context)
    try:
        with open(DownTo, 'wb') as f:
            while True:
                chunk = req.read(100*1000*1000)
                if chunk:
                    f.write(chunk)
                else:
                    break
        if os.path.isfile(DownTo):
            return '{} - {}KB'.format(DownTo, os.path.getsize(DownTo)/1024)
		
    except:
        raise Exception('Please Check URL or Download Path!')

def Extract_zip_file(path,file_path_name):
    with zipfile.ZipFile(file_path_name, 'r') as zip_object:
        zip_object.extractall(path)

def EPCC_Path():
    with disable_file_system_redirection():
        arch= os.popen("wmic os get OSArchitecture").read()
        if '64' in arch:
            query = os.popen("REG QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\").read()
        else:
            query = os.popen("REG QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\").read()
            
        for i in query.splitlines():
            displayname = os.popen('REG QUERY "%s" /v DisplayName'%(i)).read()
            if "Endpoint Manager Communication Client" in displayname:
                install_location = os.popen('REG QUERY "%s" /v InstallLocation'%(i)).read().strip().split("REG_SZ")[-1].strip()
                return install_location
    
headers = [
"Dumpfile",
"Timestamp",
"Reason",
"Errorcode",
"Parameter1",
"Parameter2",
"Parameter3",
"Parameter4",
"CausedByDriver"
]

Down_path=os.environ['TEMP'] + r"\BlueScreenViewFiles"

if not os.path.exists(Down_path):
    os.makedirs(Down_path)

csv_file_name = "bluescreenview-export.csv"
blue_screen_view_zip = "bluescreenview.zip"
blue_screen_view_exe = "BlueScreenView.exe"
blue_screen_view_url = "https://script-downloads.itarian.com/bluescreenview.zip"
blue_screen_view_zip_path = Down_path + "\%s"%(blue_screen_view_zip)
blue_screen_view_exe_path = Down_path + "\%s"%(blue_screen_view_exe)
csv_path = Down_path + "\%s"%(csv_file_name)
new_csv_path = Down_path + r"\bluescreenview_report.csv"

def check_BSOD():
    if os.path.exists("C:\Windows\Minidump"):
        downloadFile(blue_screen_view_zip_path,blue_screen_view_url)
        Extract_zip_file(Down_path,blue_screen_view_zip_path)
        print(ecmd('"%s" /scomma "%s"'%(blue_screen_view_exe_path,csv_path)))
        if os.path.exists(csv_path):
            try:
                import texttable
            except:
                try:
                    texttable_url = "https://script-downloads.itarian.com/py2_modules/texttable.py"
                    path = EPCC_Path() + r"\Lib\site-packages\texttable.py"
                    downloadFile(path,texttable_url)
                    import texttable
                except Exception as e:
                    raise Exception(e)
            tableObj = texttable.Texttable(0)
            mini_dumps = []
            with open(csv_path, "r") as csv_file:
                reader = csv.DictReader(csv_file, fieldnames=headers)
                mini_dumps.append(["Timestamp","Dumpfile","Reason","Errorcode","CausedByDriver"])
                for row in reader:
                    mini_dump = [row['Timestamp'], row["Dumpfile"], row["Reason"], row["Errorcode"], row["CausedByDriver"]]
                    mini_dumps.append(mini_dump)
                tableObj.add_rows(mini_dumps)
                print(tableObj.draw())
            shutil.rmtree(Down_path,ignore_errors=True)
        else:
            print("couldn't get CSV file using BlueScreenView.exe")
    else:
        print("minidump is not found on this machine. it is created by windows when blue screen of death occurs")

check_BSOD()