"""
Copyright 2014-2020 VMware, Inc.  All rights reserved. -- VMware Confidential

Dummy vmware-horizon-usb component.
"""

class VMwareHorizonUSB(Installer):
   def InitializeQuestions(self, old, new, upgrade):
      # Ask to install usb component or not
      defaultUsb = self.GetAnswer('usbEnable')
      if defaultUsb:
         qlevel = 'CUSTOM'
      else:
         qlevel = 'REGULAR'

      self.AddMultiChoiceQuestion(
         'YesNo',
         key='usbEnable',
         text='USB Redirection',
         required=True,
         default='yes',
         footer='The USB component enables USB device redirection from your '
                'local computer to the remote desktop.',
         level=qlevel)

   def InitializeInstall(self, old, new, upgrade):
      usbEnable = self.GetAnswer('usbEnable')
      if usbEnable == 'yes':
         self.AddTarget(
            'File',
            'lib/vmware/view/usb/libvmware-view-usbd.so',
            LIBDIR/'vmware/view/usb/libvmware-view-usbd.so')
         self.AddTarget(
            'File',
            'bin/vmware-usbarbitrator',
            LIBDIR/'vmware/view/usb/vmware-usbarbitrator')
         self.SetPermission(LIBDIR/'vmware/view/usb/*', BINARY)
         self.RegisterService(name='vmware-USBArbitrator',
                              src='init.d/vmware-USBArbitrator',
                              start=50, stop=8)
         self.AddTarget('File',
                        'lib/vmware/view/vdpService/*',
                        LIBDIR/'vmware/view/vdpService/')
         self.SetPermission(
            LIBDIR/'vmware/view/vdpService/libusbRedirectionClient.so', BINARY)
         self.AddTarget(
            'File',
            'bin/vmware-view-usbdloader',
            BINDIR/'vmware-view-usbdloader')
         self.SetPermission('/usr/bin/vmware-view-usbdloader', BINARY)
      if (CONFDIR/'abortInstall').exists():
         raise InstallError('View abort install')

   def PreUninstall(self, old, new, upgrade):
      # Stop the USB Arbitrator init script
      script = INITSCRIPTDIR/'vmware-USBArbitrator'
      if script.exists() and self.RunCommand(
         script, 'stop', ignoreErrors=True).retCode != 0:
         log.Warn(u'Unable to stop USB Arbitrator service.')

      inits = self.LoadInclude('initscript')
      inits.DeconfigureService('vmware-USBArbitrator')

   def PostUninstall(self, old, new, upgrade):
      orig = BINDIR/'vmware-usbarbitrator'
      backup = LIBDIR/'vmware/view/usb/vmware-usbarbitrator.old'
      try:
         orig.remove()
      except OSError:
         pass
      if backup.exists():
         backup.copyfile(str(orig))
         orig.chmod(0o0755)
         backup.remove()
      self.DelConfig('usbComponent')

   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):
      # If an arbitrator already exists and it's not a symlink, back
      # it up and create a symlink to our new ones.
      arb = BINDIR/'vmware-usbarbitrator'

      self.SetConfig('usbComponent', 'test')
      usbEnable = self.GetAnswer('usbEnable')
      if usbEnable == 'yes':
         self.AddScanFile(LIBDIR/'vmware/view/vdpService/libusbRedirectionClient.so')
         self.AddScanFile(LIBDIR/'vmware/view/usb/libvmware-view-usbd.so')
         self.AddScanFile(LIBDIR/'vmware/view/usb/vmware-usbarbitrator')
         self.AddScanFile(BINDIR/'vmware-view-usbdloader')

         if arb.exists():
            if not arb.islink():
               # Make the destination directory if it doesn't already exist
               dest = path(LIBDIR/'vmware/view/usb')
               if not dest.exists():
                  dest.makedirs()
               # Backup the program
               arb.copyfile(str(LIBDIR/'vmware/view/usb/vmware-usbarbitrator.old'))
               arb.remove()
            else:
               # Remove the old link
               arb.remove()

         # Now that our space in the BINDIR is clear, install the symlink.
         path(LIBDIR/'vmware/view/usb/vmware-usbarbitrator').symlink(str(arb))
         inits = self.LoadInclude('initscript')
         inits.ConfigureService(
            'vmware-USBArbitrator',
            'This services starts and stops the USB Arbitrator.',
            'localfs',
            'localfs',
            '',
            '',
            50,
            8)

         # Stop the USB Arbitrator init script
         script = INITSCRIPTDIR/'vmware-USBArbitrator'
         if script.exists() and self.RunCommand(
            script, 'stop', ignoreErrors=True).retCode != 0:
            log.Warn(
               u'Unable to stop current USB Arbitrator service.  Not fatal.')

         # Start the USB Arbitrator init script
         script = INITSCRIPTDIR/'vmware-USBArbitrator'
         if script.exists() and self.RunCommand(
            script, 'start', ignoreErrors=True).retCode != 0:
            log.Error(u'Unable to start USB Arbitrator service.')

   def PreExit(self, old, new, upgrade):
      # Stop the USB Arbitrator init script
      usbEnable = self.GetAnswer('usbEnable')
      if usbEnable == 'yes':
         script = INITSCRIPTDIR/'vmware-USBArbitrator'
         if script.exists() and self.RunCommand(
            script, 'stop', ignoreErrors=True).retCode != 0:
            log.Warn(u'Unable to stop USB Arbitrator service.')

         inits = self.LoadInclude('initscript')
         # Deconfigure the service twice to make sure that all the autostart
         # scripts are successfully removed
         inits.DeconfigureService('vmware-USBArbitrator')
         inits.DeconfigureService('vmware-USBArbitrator')
