"""
Copyright 2019-2022 VMware, Inc.  All rights reserved. -- VMware Confidential

Dummy vmware-horizon-url-redirection component.
"""

import json
import os
import os.path
import pwd

urlConfigFile = '/etc/vmware/broker-url-config'
urlFilterEntry = '/usr/share/applications/urlfilter.desktop'
urlExtensionChrome = 'data.json'
urlExtensionFirefox = 'url_redirection@vmware.com.json'
chromeExtensionPath = '.config/google-chrome/Default/Extensions/lfidjngibpklhhijphdmbmedchiiolgk'
chromeUrlWhitelistPath = '/etc/opt/chrome/policies/managed'
firefoxManagedStorage = '/usr/lib/mozilla/managed-storage'
firefoxManagedStorage64 = '/usr/lib64/mozilla/managed-storage'
firefoxHandlerFile = "handlers.json"

class VMwareHorizonUrlRedirection(Installer):
   def InitializeInstall(self, old, new, upgrade):
      self.AddTarget('File', 'bin/vmware-urlFilter', '/usr/lib/vmware/view/bin/vmware-urlFilter')
      self.AddTarget('File', 'bin/vmware-url-filter', BINDIR/'vmware-url-filter')
      self.AddTarget('File', 'lib/liburlFilterPlugin.so', LIBDIR/'vmware/liburlFilterPlugin.so')
      self.SetPermission('/usr/lib/vmware/view/bin/vmware-urlFilter', BINARY)
      self.SetPermission(BINDIR/'vmware-url-filter', BINARY)
      self.SetPermission(LIBDIR/'vmware/liburlFilterPlugin.so', BINARY)
      self.ConfigBrowser()
      self.CreateChromeUrlWhitelist()

      if (CONFDIR/'abortInstall').exists():
         raise InstallError('View abort install')

   def InitializeUninstall(self, old, new, upgrade):
      if (CONFDIR/'abortUninstall').exists():
         raise InstallError('View aborting uninstall')
      self.RunCommand('true', ignoreErrors=True)

   def PostInstall(self, old, new, upgrade):
      self.SetConfig('urlredirectionComponent', 'test')

   def PostUninstall(self, old, new, upgrade):
      self.DelConfig('urlredirectionComponent')
      self.RemoveUrlConfig()

   # Config Browser scheme/whitelist for URL redirection
   def ConfigBrowser(self):
      userProfiles = pwd.getpwall()
      for profile in userProfiles:
         user = profile[0]
         uid = profile[3]
         # Only handle for normal user (uid > 1000)
         if uid < 1000:
            continue
         homedir = os.path.expanduser('~' + user)
         firefoxConfigDir = os.path.join(homedir, '.mozilla/firefox')
         if os.path.exists(firefoxConfigDir):
            self.SetFirefoxHandlers(firefoxConfigDir)

   def CreateChromeUrlWhitelist(self):
      if not os.path.exists(chromeUrlWhitelistPath):
         os.makedirs(chromeUrlWhitelistPath, 0o755);

      chromeUrlWhitelistConfig = os.path.join(chromeUrlWhitelistPath,
                                              'vmware-urlWhitelist.json')
      urlWhiteList = {"URLWhitelist": ["vmware-view:*"]}
      with open(chromeUrlWhitelistConfig, "w+") as f:
         json.dump(urlWhiteList, f)

      f.close()
      os.chmod(chromeUrlWhitelistConfig, 0o744)

   # Remove url config files for filter app and firefox extension
   def RemoveUrlConfig(self):
      if os.path.exists(urlConfigFile):
         os.remove(urlConfigFile);
      if os.path.exists(urlFilterEntry):
         os.remove(urlFilterEntry);

      # Remove chrome url white list config
      chromeUrlWhitelistConfig = os.path.join(chromeUrlWhitelistPath,
                                              'vmware-urlWhitelist.json')
      if os.path.exists(chromeUrlWhitelistConfig):
         os.remove(chromeUrlWhitelistConfig)

      # Remove firefox url config
      firefoxExtensionConfig = os.path.join(firefoxManagedStorage,
                                            urlExtensionFirefox)
      firefoxExtensionConfig64 = os.path.join(firefoxManagedStorage64,
                                            urlExtensionFirefox)
      if os.path.exists(firefoxExtensionConfig):
         os.remove(firefoxExtensionConfig)
      if os.path.exists(firefoxExtensionConfig64):
         os.remove(firefoxExtensionConfig64)

      # Remove url config for each user
      result  = self.RunCommand('ls', '/home', ignoreErrors=True)
      output = result[1]
      users = output.split('\n')
      for user in users:
         # Remove firefox url config file
         firefoxConfig = os.path.join('/home',
                                      user,
                                      '.mozilla/managed-storage',
                                      urlExtensionFirefox)
         if os.path.exists(firefoxConfig):
            os.remove(firefoxConfig)

         # Remove chrome url config files
         chromeConfigPath = os.path.join('/home',
                                         user,
                                         chromeExtensionPath)
         if os.path.exists(chromeConfigPath):
            for version in os.listdir(chromeConfigPath):
               chromeConfig = os.path.join(chromeConfigPath,
                                           version,
                                           urlExtensionChrome)
               if os.path.exists(chromeConfig):
                  os.remove(chromeConfig)

   # Set Firefox handler for vmware-view://
   def SetFirefoxHandlers(self, firefoxConfigDir):
      searchpath = os.path.expanduser(firefoxConfigDir)
      for root, dirs, files in os.walk(searchpath):
         result = []
         if firefoxHandlerFile in files:
            result.append(os.path.join(root, firefoxHandlerFile))

         if not len(result) > 0:
            continue

         handlerFilePath = result[0]
         try:
            with open(handlerFilePath) as fin:
               data = json.load(fin)

            # Set Firefox to use system default handler for vmware-view://
            schemes = data.get('schemes')
            if schemes is not None:
               client_config = dict()
               # Set handler action as use system default (By Firefox spec: useSystemDefault = 4)
               client_config['action']=4
               schemes['vmware-view']=client_config
               with open(handlerFilePath,'w') as fout:
                  json.dump(data, fout)
               break
         except ValueError:
            continue
