import ctypes
import os
import subprocess


# provied the bat script between r''' <batScript> ''' for deleting different file if needed in the future
Batcontent = r'''
for /f %%a in ('dir /B /AD C:\Users') do (
    if exist "C:\Users\%%a\Desktop\Database 9-1-2010 PS.mdb" del /F /Q "C:\Users\%%a\Desktop\Database 9-1-2010 PS.mdb"
    if exist "C:\Users\%%a\Desktop\Database  9-1-2010 MGR Access.mdb" del /F /Q "C:\Users\%%a\Desktop\Database  9-1-2010 MGR Access.mdb"
    if exist "C:\Users\%%a\Desktop\Database 9-1-2010 PS.lnk" del /F /Q "C:\Users\%%a\Desktop\Database 9-1-2010 PS.lnk"
    if exist "C:\Users\%%a\Desktop\Database  9-1-2010 MGR Access.lnk" del /F /Q "C:\Users\%%a\Desktop\Database  9-1-2010 MGR Access.lnk"
)
'''


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 createBatFile(Batcontent):
    Folder = os.environ['programdata'] + r"\extraction_file"
    file_path = os.path.join(Folder, 'removePS.bat')
    with open(file_path, 'wb') as wr:
        wr.write(Batcontent)
    return file_path


BatPath = createBatFile(Batcontent)
if os.path.exists(BatPath):
    with disable_file_system_redirection():
        obj = subprocess.Popen(BatPath, shell=True, stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)
    out, err = obj.communicate()
    if out != "":
        print out
    else:
        print err
    os.remove(BatPath)
else:
    print 'Error creating .bat script file'