#!/usr/bin/env python
_ = lambda x : x

try:
  from ConfigParser import ConfigParser
  from os import system
  import gobject
  import getpass
except ImportError, e:
  print "Import error in helper:", e
  sys.exit(1)

try:
  import gksu2 as gksu
except ImportError, e:
  pass
#   print '\n'
#   print e
#   print _('You will have to run the program as root in order to install/remove packages in a write-protected TeX tree\n')


def Write_ini(filename, config):
  """
  given a dictionary with key's 'section' and values that are dictionaries
  of the form 'option: value'
  write() generates a list of unique section names
  creates sections based that list
  use config.set to add entries to each section
  """
  cp = ConfigParser()
  sections = config.keys()
  map(cp.add_section, sections)
  for s,v in config.iteritems():
    for o,vv in v.iteritems():
      cp.set(s, o, vv)
  f=open(filename, "w")
  cp.write(f)
  f.close()

def Load_ini(file, config={}):
  """
  Returns a dictionary with keys of the form
  <section> and values that are dictionaries with keys opt and values 
  """
  config = config.copy()
  cp = ConfigParser()
  ff= cp.read(file)
  for sec in cp.sections():
    d={}
    for opt in cp.options(sec):
      d[opt] = cp.get(sec, opt).strip()

    # Copy keys to existing dictionary
    for k,v in d.iteritems():
      if not config.has_key(sec): # If it does not exist. Initialize it!
        config[sec]={}
      config[sec][k]=v
  return ff,config


def cli_ask_pass_func(context, prompt):
  try:
    return getpass.getpass("Enter Root password: ")
  except KeyboardInterrupt:
    err = gobject.GError("keyboard interrupt")
    err.code = gksu.ERROR_CANCELED
    err.domain = "libgksu"
    raise err

def run_comando(comando,ask_pass_func, permission=False):
  if permission == False:
    ctx = gksu.Context()
    ctx.set_command(comando)
  #   ctx.set_user(os.environ['USER'])
    try:
      gksu.su_full(ctx, ask_pass=ask_pass_func)
    except gobject.GError, error:
      if error.code == gksu.ERROR_CANCELED:
        print "Cancel:", error.message
      else:
        print "Error:", error.message
  else:
    system(comando)
  
