#!/usr/bin/env python
# Python version of MPM (MikTeX Package Manager)
_ = lambda x : x
import sys

try:
  from gmpm.constants import TEMPLATE_FILE, APP_ICON,DATA_DIR, PREFIX
  from gmpm.pympm import MiKTeX_config, MiKTeX_Distrib
except ImportError, e:
  print 'file', __file__ , ': OWN MODULES FAILING',e
  sys.exit(1)

try:
  from optparse import OptionParser
  import os.path
except ImportError, e:
  print 'Standard modules missing', e
  sys.exit(1)


def main():
  # CONFIGURACION ############################################################

  version= "Python version of MiKTeX Package Manager  Version 0.2\n" 
  version+="Copyright (C) 2008 by Juan Fiol\n"
  version+="This is free software; see the source for copying conditions. "
  version+="There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n"
  version+="Intented funcionality similar to original: \n"
  version+="MPM (Copyright (C) 2005-2006 Christian Schenk.)"
  version+="In this version it relies on MPM for many tasks. That may change in the future, or not.\n"

  parser = OptionParser(version=version)

  parser.add_option("", "--quiet", action="store_false", dest="quiet", default=False
                    , help="Suppress all output (except errors).")

  parser.add_option("", "--verbose", action="store_true", dest="VERBOSE", default=False
                    , help="Suppress all output (except errors).")

  parser.add_option("-l", "--list", action="store_true"
                    , help="List the contents of the package database: for each package," +
                    " print the installation status, the number of files, the size, and the name.")

  parser.add_option("-i", "--list-installed", action="store_true"
                    , help="(NEW) List the packages that are installed, for each package" +
                    " print the installation status, the number of files, the size, and the name.")



  parser.add_option("-p", "--print-package-info" #, dest="PACK_Info" #, default="NOINFO"
                    , help="Print detailed information about the specified package PACK_Info.")


  parser.add_option("", "--update-db", action="store_true", default=False
                    , help="Synchronize the local package database with the package repository.")

  parser.add_option("--install-root"
                    , help="Use the specified directory as the installation destination.")

  parser.add_option("--repository"
                    , help="Use the specified location as the package repository."+
                    "  The location can be either a fully qualified path name (a local package"+
                    " repository) or an URL (a remote package repository).")

  parser.add_option("--proxy", "--all_proxy", "--ALL_PROXY"
                    , help="Use the specified proxy for every network connection.")


##########################################################################################
##########################################################################################
##########################################################################################
##################################### NEW OPTIONS  #######################################
  parser.add_option("", "--gui", action="store_true", default=False
                    , help="Show the GUI and ignore all other options")


  parser.add_option("-n", "--dry-run", action="store_true", default=False
                    , help="(NEW) Don't actually run any commands; just print them.")

  parser.add_option("-c", "--conf", dest='INIFILE'
                    , help="(NEW) Load configuration values from INIFILE.")
  parser.add_option("-g", "--save-config", action='store_true', default=False
                    , help="(NEW) If set, it does save the configuration file when parameters"+
                    " of the distribution change (for instance with --install-root)")

  parser.add_option("-s", "--search"
                    , help="(NEW) Searches for matches of the supplied string in the distribution.\n"+
                    "Searches in names and short descriptions.")
  parser.add_option("-S", "--searchdesc"
                    , help="(NEW) Similar to --search but also searches in packages' long description")
  parser.add_option("-H", "--help-package"
                    , help="(NEW) Open Help on package (using mthelp).")

  parser.add_option("", "--show-configuration","--info", action='store_true', default=False
                    , help="(NEW) Show values of parameters in present configuration.")

##########################################################################################
##########################################################################################
##########################################################################################


  parser.add_option("", "--install"
                    , help="Install the specified package.")
  parser.add_option("", "--uninstall"
                    , help="Uninstall the specified package.")
  parser.add_option("", "--update" 
                    , help="Update the specified package, if an updated version is available in the package "+
                    "repository.  Install all updateable packages, if the package name is omitted.")
  parser.add_option("", "--update-some" 
                    , help="Update packages listed (line-by-line) in the specified file.")
  parser.add_option("", "--find-updates" 
                    , help="Test the package repository for updates, then print the list of updateable packages.")
  parser.add_option("", "--list-repositories", action="store_true", default=False
                    , help="Download the list of known package repository URLs from "+
                    "the MiKTeX project server, then print the list.")
  parser.add_option("", "--pick-repository-url", action="store_true", default=False
                    , help="Pick up a suitable URL from the package repository list and print it.")

  parser.add_option("", "--verify", default=None
                    , help="Verify the integrity of the specified package.")


  (op, args) = parser.parse_args()

  if op.gui or len(sys.argv) ==1:
    # If not options or option --gui. Call the GUI Fronted and discard all other options
    import gmpm.gui.guimpm

    gladefile= os.path.join(PREFIX,TEMPLATE_FILE)

    gmpm.gui.guimpm.run(gladefile)
    return


  c= MiKTeX_config()  # Create a configuration object with standard (hardcoded) values and ini file
  # Set install-root from command line
  if op.install_root:
    c.set_attribute('root', op.install_root)
    root= op.install_root
  else:
    root= c.get_attribute('root')

  # After reading all distribution parameters
  # We create the distribution with the final configuration
  dist= MiKTeX_Distrib( inifile= op.INIFILE , config=c )

  # Set environment variable ALL_PROXY. Note that no_proxy is not modified at all in this program
  if op.proxy:
    dist.set_onlyone_proxy(op.proxy)
  
  if op.list_repositories:
    dist.conf.update_repositories()
    for l in dist.conf.repositories:
      print l
    return

  if op.pick_repository_url:
    l= dist.conf.pick_repository_url()
    print l

  if op.repository:
    dist.set_repository(op.repository)

  c= dist.conf
  if op.save_config:
    c.save_MiKTeX_config(c.inifiles[-1])

  if op.show_configuration:
    print 2*'\n'
    print '************************************************************************'
    print '                        Current configuration                           '
    print '************************************************************************'
    print 'Root:',dist.conf.get_attribute('root')
    print 'Repository:',dist.conf.get_attribute('repository')
    print 'http_proxy:',dist.conf.get_attribute('http_proxy')
    print 'FTP_PROXY:',dist.conf.get_attribute('ftp_proxy')
    print 'ALL_PROXY:',dist.conf.get_attribute('all_proxy')
    print 'no_proxy:',dist.conf.get_attribute('no_proxy'), 2*'\n'


  if op.update_db:
    msg,status= dist.update_db()
    if status:
      print "Database updated"
    else:
      print "ERROR: Database not updated "
      print msg
    return


#######################################################################################
#######################################################################################
  if dist.dist == {}:
    print _('Current configuration not valid\nRun First with option: --update-db')
    sys.exit()

  # From here we need an installed valid distribution
  if not dist.valid:
    print dist.conf.get_attribute('config_dir'),_('or'), dist.conf.get_attribute('tpm_dir'), _('not available')
    print _('Not a valid distribution')
    sys.exit(1)

#######################################################################################
#######################################################################################

  if op.search:
    s= dist.search(op.search,0).list(verbose=op.VERBOSE)
    if s=="":
      print "No match found"
    else:
      print s.encode('utf-8')
    return

  if op.searchdesc:
    s= dist.search(op.searchdesc, 3).list(verbose=op.VERBOSE)
    if s=="":
      print "No match found"
    else:
      print s.encode('utf-8')
    return

  if op.list:
    s=unicode(dist.list(verbose=op.VERBOSE)).encode('utf-8')
    if list == "":
      print "The package database files have not been installed."
    else:
      print s
    return

  if op.list_installed:
    s=unicode(dist.list_installed(verbose=op.VERBOSE)).encode('utf-8')
    print s
    return

  if op.print_package_info:
    s= dist.get_info(op.print_package_info,verbose=op.VERBOSE)
    if s:
      print s.encode('utf-8')
    return

################################################################################
################################################################################
################################################################################
  # These are temporary. Until we implement a good way of calling mpm
################################################################################
################################################################################
################################################################################
  if op.dry_run:
    fake="echo " + dist.mpmcommand

  if op.VERBOSE:
    dist.mpmcommand+= ' --verbose'

  if op.quiet:
    dist.mpmcommand+= ' --quiet'

#   repository= c.get_attribute('repository')

  if op.verify:
    ret= dist.verify_package(op.verify)
    if ret:
      print 'pympm: Package '+ op.verify +' is correctly installed'
    else:
      print 'pympm: Package '+ op.verify +' needs to be reinstalled.'
    return

  if op.install:
    dist.install_package(op.install)
    return

  if op.uninstall:
    dist.uninstall_package(op.uninstall)
    return


  if op.update:
    dist.update_package(op.update)
    return

  if op.update_some:
    dist.update_some(op.update_some)
    return
    
  if op.help_package:
    dist.get_package_help(op.help_package)
    return


if __name__ == "__main__":
  main()


### Local Variables: 
### tab-width: 2
### END:
