

import os
import subprocess
import ctypes
import re
import ssl
import urllib

url_64 = "https://script-downloads.comodo.com/Libreoffice/LibreOffice_7.3.4_Win_x64.msi"
url_32 = "https://script-downloads.comodo.com/Libreoffice/LibreOffice_7.3.4_Win_x86.msi"
paths = "C:\\Libreoffice"
if os.path.exists(paths):
	pass 
else:
	os.makedirs(paths)

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():

	def system_architecture():
		cmd=subprocess.Popen("wmic os get osarchitecture",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
		result,error=cmd.communicate()
		if error:
			print(error)
		else:
			operating_system = result.split()
			return operating_system

	def download(url,path,file_name):
		print('Libreoffice msi File Downloading......')
		src_path = path+"\\"+file_name
		try:
			gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
			download = urllib.urlretrieve(url,src_path,context = gcontext)
			print('Libreoffice msi File downloaded')
			return "Success"
		except Exception as e:
			print e 

	def install(file):
		print("Libreoffice installing.....")
		command = 'msiexec /i '+'"'+file+'"'+' /quiet /qn'
		print command
		cmd = subprocess.Popen(command,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
		result,error=cmd.communicate()
		if error:
			print(error)
			print("Error Occured while installing the file.")
		else:
			print("Libreoffice Installed Successfully")
		

	op_system = system_architecture()
	if "64-bit" in op_system:
		file_download = download(url_64,paths,"Libreoffice_64.msi")
		if file_download == "Success":
			location = paths+'\\Libreoffice_64.msi'
			print location
			install(location)
		else:
			print("Error occured while downloading the file.")
	else:
		file_download = download(url_32,paths,"Libreoffice_32.msi")
		if file_download == "Success":
			location = paths+'\\Libreoffice_32.msi'
			install(location)
		else:
			print("Error occured while downloading the file.")
	
