import os
from subprocess import PIPE, Popen
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)
            
            
with disable_file_system_redirection():
    arch=os.popen("wmic os get OSArchitecture").read()

if '64' in arch:
    ArchType = '64'
else:
    ArchType = '32'

def ecmd(command):   
    from subprocess import Popen, PIPE
    import ctypes
    
    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
            
            
batchfile = """
if %s==64 GOTO 64bit else GOTO 32bit

:64bit
RD /S /Q "C:\Program Files (x86)\SnapComms"
reg delete "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\SnapComms App" /f
GOTO END

:32bit
RD /S /Q "C:\Program Files\SnapComms"
reg delete "HKEY_LOCAL_MACHINE\SOFTWARE\SnapComms App" /f
GOTO END

:END
"""%(ArchType)

def uninstall():
    print(ecmd('wmic product where "name like \'SnapComms%%\'" call uninstall /nointeractive'))
    batch_name = 'batch_file.bat'
    batch_path=os.path.join(os.environ['TEMP'], batch_name)
    with open(batch_path, 'wb') as wr:
        wr.write(batchfile)
    
    print(ecmd(batch_path))
    
    os.remove(batch_path)
    
    with disable_file_system_redirection():
        users=os.popen("net users").read().split()[5:-4]
    fil_users=[i.strip() for i in users if i.strip()!="Administrator" and i.strip()!="Guest"]
    for i in fil_users:
        LocalPath = "C:\\Users\\%s\\AppData\\Local\\SnapComms App"%(i)
        TempPath = "C:\\Users\\%s\\AppData\Local\Temp\SnapClient"%(i)
        if os.path.exists(LocalPath):
            shutil.rmtree(LocalPath)
        if os.path.exists(TempPath):
            shutil.rmtree(TempPath)

uninstall()