# ./addons/eventscripts/corelib/es_install/es_install.py

import es
import esamlib
import installlib
import os.path
import StringIO
import time

import psyco
psyco.full()


installlib._executeAutoLoad()

###

class InstallLog(esamlib.DBGLog):
   logpath = es.getAddonPath('corelib/es_install') + '/es_install.log'

   def __init__(self, logpath=None):
      if not logpath is None:
         self.logpath = logpath

      self.lines  = []
      self.recent = []

      self._readLines()

   def _readLines(self):
      if not os.path.isfile(self.logpath): return

      logfile    = open(self.logpath)
      self.lines = logfile.readlines()
      logfile.close()

   def write(self, text, dbglvl=None):
      if not dbglvl is None:
         es.dbgmsg(dbglvl, text)
      
      self.lines.append(time.strftime('%x %X ] ') + text + '\n')
      self.recent.append(time.strftime('%X ] ') + text + '\n')

      logfile = open(self.logpath, 'w')
      logfile.writelines(self.lines)
      logfile.close()

   def echo(self, recent=True):
      for line in self.recent if recent else self.lines:
         es.dbgmsg(0, line[:~0])

log = InstallLog()

###

def _registerServerCommand(name, description):
   if not es.exists('command', 'es_' + name):
      es.regcmd('es_' + name, 'corelib/es_install/expand_cmd', description)

   if not es.exists('command', 'es_x' + name):
      es.regcmd('es_x' + name, 'corelib/es_install/' + name + '_cmd', description)


def expand_cmd():
   name = es.getargv(0)
   args = es.getargs()
   es.server.cmd('es ' + name[:3] + 'x' + name[3:] + ((' ' + args) if args else ''))


###


def install_cmd():
   """
   es_install <basename> [autoload]
   """
   argc = es.getargc()
   if argc in (2, 3):
      basename = es.getargv(1)
      autoload = (es.getargv(2) <> '0') if argc == 3 else False

      installer = installlib.getInstaller(basename)
      if installer is None:
         log.write('es_install: Unable to connect to ESAM -- please ensure you have an active internet connection')

      else:
         status = installer.install(autoload)
         if status == installer.STATUS_SUCCESSFUL:
            log.write('es_install: %s installed successfully' % basename, 0)
         elif status == installer.STATUS_NO_DOWNLOAD:
            log.write('es_install: Unable to download %s -- please ensure you have an active internet connection' % basename, 0)
         elif status == installer.STATUS_ALREADY_DONE:
            log.write('es_install: %s already installed' % basename, 0)
         elif status == installer.STATUS_NOT_APPROVED:
            log.write('es_install: %s not approved for install' % basename, 0)
         else:
            log.write('es_install: Unknown error (%s)' % status, 0)

   elif argc == 1:
      addonlist = installlib.infomanager.getInstalled()
      if addonlist:
         maxlength = max(map(len, addonlist))

         es.dbgmsg(0, ' %s   Autoloaded\n %s   ----------' % ('Basename'.ljust(maxlength), '--------'.ljust(maxlength)))
         for addon in addonlist:
            es.dbgmsg(0, ' %s   %s' % (addon.ljust(maxlength), installlib.getInstaller(addon, 1).isAutoLoaded()))

      else:
         es.dbgmsg(0, 'No installed addons')

   else:
      es.dbgmsg(0, 'Syntax: %s <basename> [autoload]' % es.getargv(0).lower())
_registerServerCommand('install', 'Installs approved addons from the ESAM')


def update_cmd():
   """
   es_update <basename> [force update]
   """
   argc = es.getargc()
   if argc in (2, 3):
      basename = es.getargv(1)
      force    = (es.getargv(2) <> '0') if argc == 3 else False

      installer = installlib.getInstaller(basename)
      if installer is None:
         log.write('es_install: Unable to connect to ESAM -- please ensure you have an active internet connection')

      else:
         status = installer.update(force)
         if status == installer.STATUS_SUCCESSFUL:
            log.write('es_update: %s updated successfully' % basename, 0)
         elif status == installer.STATUS_NO_DOWNLOAD:
            log.write('es_update: Unable to download %s -- please ensure you have an active internet connection' % basename, 0)
         elif status == installer.STATUS_NO_INSTALL_INFO:
            log.write('es_update: %s not installed' % basename, 0)
         elif status == installer.STATUS_ALREADY_DONE:
            log.write('es_update: %s already up to date' % basename, 0)
         elif status == installer.STATUS_NOT_APPROVED:
            log.write('es_update: %s not approved for install' % basename, 0)
         else:
            log.write('es_update: Unknown error (%s)' % status, 0)

   else:
      es.dbgmsg(0, 'Syntax: %s <basename> [force update]' % es.getargv(0).lower())
_registerServerCommand('update', 'Updates addons installed with es_install')


def uninstall_cmd():
   """
   es_uninstall <basename>
   """
   if es.getargc() == 2:
      basename = es.getargv(1)

      installer = installlib.getInstaller(basename, StringIO.StringIO())

      status = installer.uninstall()
      if status == installer.STATUS_SUCCESSFUL:
         log.write('es_uninstall: %s uninstalled successfully' % basename, 0)
      elif status == installer.STATUS_NO_INSTALL_INFO:
         log.write('es_uninstall: %s not installed' % basename, 0)
      else:
         log.write('es_uninstall: Unknown error (%s)' % status, 0)

   else:
      es.dbgmsg(0, 'Syntax: %s <basename>' % es.getargv(0).lower())
_registerServerCommand('uninstall', 'Uninstalls addons installed with es_install')


"""
] es_uninstall teamfog
es_uninstall: teamfog not installed

] es_install teamfog 1
es_install: teamfog installed successfully
] es_install teamfog
es_install: teamfog already installed

] es_update teamfog
es_update: teamfog already up to date
] es_update teamfog 1
es_update: teamfog updated successfully

] es_uninstall teamfog
es_uninstall: teamfog uninstalled successfully

] es_update teamfog
es_update: teamfog not installed
"""