url = r"https://statics.teams.cdn.office.net/production-teamsprovision/lkg/teamsbootstrapper.exe"

import subprocess
import os
import ctypes
import re
import ssl
import urllib2
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 call_command(command):
    with disable_file_system_redirection():
        process=subprocess.Popen(command, stdin=subprocess.PIPE,stdout=subprocess.PIPE, shell=True)
    stdout,stderr = process.communicate()
    ret = process.returncode
    return ret,stdout,stderr

def uninstall(command, success_msg, error_msg):
    returncode, output, error = call_command(command)
    if returncode == 0:
        print(output)
        print(success_msg)
    else:
        if error:
            print(error)
            print(error_msg)
        else:
            print("Something went wrong. Return code: %s"%(returncode))
            print(error_msg)

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:
        return 'Please Check URL or Download Path!'

def check_and_uninstall():
    with disable_file_system_redirection():
        userout = os.popen('query user').read()
        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"]
    try:
        try:
            curusername = re.findall(r"(.*)\s+\S+\s+\S+\s+Active",userout)[0].strip()
        except:
            raise Exception("no user seems to be logged in on this system")
        curcheck = list(filter(lambda x: x.lower()==curusername.lower(),fil_users))
        if curcheck:
                sid = os.popen("wmic useraccount where name=\"%s\" get sid"%(curusername)).read().splitlines()[1].strip()
                query = os.popen("REG QUERY HKEY_USERS\\%s\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\"%(sid)).read()
                for rk in query.splitlines():
                    displayname = os.popen('REG QUERY "%s" /v DisplayName'%(rk)).read()
                    if "Microsoft Teams classic" in displayname:
                        TeamsPath =  r"C:\Users\%s\AppData\Local\Microsoft\Teams"%(curusername)
                        CachePath = r"C:\Users\%s\AppData"%(curusername)
                        print("Microsoft Teams classic found for the user - %s, uninstalling...."%(curusername))
                        uninstallstringQuery = os.popen('REG QUERY "%s" /v QuietUninstallString'%(rk)).read().split("REG_SZ")[-1].strip()
                        call_command('taskkill /IM "Teams.exe" /F')
                        success_message = "Successfully uninstalled Microsoft Teams classic for the user: %s"%(curusername)
                        error_message = "Failed to uninstall Microsoft Teams classic for the user: %s"%(curusername)
                        uninstall('%s'%(uninstallstringQuery), success_message, error_message)
                        print(call_command('reg delete "%s" /f'%(rk)))
                        try:
                            shutil.rmtree(r"%s\Local\Microsoft\Teams"%(CachePath), ignore_errors=True)
                            shutil.rmtree(r"%s\Local\Microsoft\TeamsPresenceAddin"%(CachePath), ignore_errors=True)
                            shutil.rmtree(r"%s\Roaming\Microsoft\Teams"%(CachePath), ignore_errors=True)
                            os.remove(r"C:\Users\%s\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Microsoft Teams classic.lnk"%(curusername))
                            os.remove(r"C:\Users\%s\Desktop\Microsoft Teams classic.lnk"%(curusername))
                        except Exception as delete_error:
                            print(delete_error) 
    except Exception as err:
        print(err)
    else:
        fil_users.remove(curcheck[0])
    for us in fil_users:
        if os.path.exists("C:\\Users\\%s\\ntuser.dat"%(us)):
            ret,out,err = call_command('reg load "HKU\\%s" "C:\\Users\\%s\\ntuser.dat"'%(us,us))
            if out:
                try:
                    query = os.popen("REG QUERY HKEY_USERS\\%s\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\"%(us)).read()
                    for rk in query.splitlines():
                        displayname = os.popen('REG QUERY "%s" /v DisplayName'%(rk)).read()
                        if "Microsoft Teams classic" in displayname:
                            TeamsPath =  r"C:\Users\%s\AppData\Local\Microsoft\Teams"%(us)
                            CachePath = r"C:\Users\%s\AppData"%(us)
                            print("Microsoft Teams classic found for the user - %s, uninstalling...."%(us))
                            uninstallstringQuery = os.popen('REG QUERY "%s" /v QuietUninstallString'%(rk)).read().split("REG_SZ")[-1].strip()
                            call_command('taskkill /IM "Teams.exe" /F')
                            success_message = "Successfully uninstalled Microsoft Teams classic for the user: %s"%(us)
                            error_message = "Failed to uninstall Microsoft Teams classic for the user: %s"%(us)
                            uninstall('%s'%(uninstallstringQuery), success_message, error_message)
                            print(call_command('reg delete "%s" /f'%(rk)))
                            try:
                                shutil.rmtree(r"%s\Local\Microsoft\Teams"%(CachePath), ignore_errors=True)
                                shutil.rmtree(r"%s\Local\Microsoft\TeamsPresenceAddin"%(CachePath), ignore_errors=True)
                                shutil.rmtree(r"%s\Roaming\Microsoft\Teams"%(CachePath), ignore_errors=True)
                                os.remove(r"C:\Users\%s\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Microsoft Teams classic.lnk"%(us))
                                os.remove(r"C:\Users\%s\Desktop\Microsoft Teams classic.lnk"%(us))
                            except Exception as delete_error:
                                print(delete_error)
                except Exception as err:
                    print(err)
                else:
                    unLoad = os.popen('reg unload "HKU\\%s"'%(us)).read()
            else:
                print(err)

def install_Teams_system_wide():
    Down_path=os.environ['TEMP']
    Name = url.split("/")[-1]
    DownTo = os.path.join(Down_path, Name)

    print(downloadFile(DownTo, url))

    success_message = "Successfully installed Microsoft Teams New"
    error_message = "Failed to install Microsoft Teams New"

    uninstall('"%s" -p'%(DownTo), success_message, error_message)

    os.remove(DownTo)

check_and_uninstall()

install_Teams_system_wide()