import os
import ctypes
import shutil
import re
from subprocess import PIPE, Popen

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(self,command):
    with disable_file_system_redirection():
        obj = Popen(command, shell = True, stdout = PIPE, stderr = PIPE)
        out, err = obj.communicate()
        return out,err
        

BatchScript = r"""
@echo off

set "user="

for /f "skip=1 tokens=1,* delims=\" %%A in ('
    wmic computersystem get username ^|
    powershell -noprofile -command "$input.trim()"
') do set "user=%%~B"

echo %user%
"""
        
def uninstall():
    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 "WinMessenger 2.1" in displayname:
                print("WinMessenger 2.1 is found on this machine")
                print("removing WinMessenger.......")
                install_location = os.popen('REG QUERY "%s" /v InstallLocation'%(i)).read().strip().split()[-1].strip()
                shutil.rmtree(os.path.expandvars(install_location),ignore_errors=True)
                print(os.popen('REG DELETE "%s" /f'%(i)).read())
                batch_script_path = os.path.join(os.environ["TEMP"], "currentuser.bat")
                with open(batch_script_path, "w") as f:
                    f.write(BatchScript)
                curusername = os.popen(batch_script_path).read().strip()
                users=os.popen("wmic UserAccount get Name").read().strip().splitlines()
                fil_users=[i.strip() for i in users if i.strip()!="Administrator" and i.strip()!="DefaultAccount" and i.strip()!="Guest" and i.strip()!="WDAGUtilityAccount"]
                if os.path.exists("C:\Users\%s\AppData\Roaming\VyPRESS\WinMessenger"%(curusername)):
                    shutil.rmtree("C:\Users\%s\AppData\Roaming\VyPRESS"%(curusername),ignore_errors=True)
                    sid = os.popen("wmic useraccount where name=\"%s\" get sid"%(curusername)).read().splitlines()[1].strip()
                    print(os.popen('REG DELETE "HKEY_USERS\%s\Software\VyPRESS" /f'%(sid)).read())
                    os.remove(batch_script_path)
                else:
                    fil_users.remove(curusername)
                    os.remove(batch_script_path)
                    flag = 0
                    for user in fil_users:
                        if os.path.exists("C:\Users\%s\AppData\Roaming\VyPRESS\WinMessenger"%(user)):
                            shutil.rmtree("C:\Users\%s\AppData\Roaming\VyPRESS"%(user),ignore_errors=True)
                            if os.path.exists("C:\\Users\\%s\\ntuser.dat"%(user)):
                                out,err = ('reg load "HKU\\%s" "C:\\Users\\%s\\ntuser.dat"'%(user,user))
                                if out:
                                    try:
                                        print(ecmd('REG DELETE "HKEY_USERS\%s\Software\VyPRESS" /f'%(user)))
                                        flag = 1
                                    except Exception as err:
                                        print(err)
                                    else:
                                        unLoad = os.popen('reg unload "HKU\\%s"'%(user)).read()
                                        if flag:
                                            break
                                else:
                                    print(err)
                print("successfully removed WinMessenger 2.1")
                break
        else:
            print("WinMessenger 2.1 is not found on this machine")
uninstall()
