#! /usr/bin/python
#
# copyright (c) 2006 Josselin Mouette <joss@debian.org>
# Licensed under the GNU Lesser General Public License, version 2.1
# See COPYING for details

from optparse import OptionParser
import sys,os,os.path,shutil,tempfile

parser = OptionParser(usage="usage: %prog --[un]register file1.schemas [file2.schemas [...]]")

parser.add_option("--register", action="store_true", dest="register",
                  help="register schemas to the GConf database",
		  default=None)
parser.add_option("--unregister", action="store_false", dest="register",
                  help="unregister schemas from the GConf database",
		  default=None)

(options, args) = parser.parse_args()

if options.register==None:
  parser.error("You need to specify --register or --unregister.")

schema_location="/usr/share/gconf/schemas"

schemas = [ ]
for schema in args:
  if not os.path.isabs(schema):
    schema=os.path.join(schema_location,schema)
  if os.path.isfile(schema):
    schemas.append(schema)
  else:
    sys.stderr.write('Warning: %s could not be found.\n'%schema)

if len(schemas)<1:
  parser.error("You need to give at least a file to (un)register.")

if os.geteuid():
  parser.error("You must be root to launch this program.")

tmp_home=tempfile.mkdtemp(prefix='gconf-')
env={'HOME': tmp_home,
     'GCONF_CONFIG_SOURCE': 'xml:readwrite:/var/lib/gconf/defaults'}
if options.register:
  arg='--makefile-install-rule'
else:
  arg='--makefile-uninstall-rule'

save_stdout=os.dup(1)
os.close(1)
res=os.spawnvpe(os.P_WAIT,'gconftool-2',['gconftool-2',arg]+schemas,env)
os.dup2(save_stdout,1)
os.close(save_stdout)

shutil.rmtree(tmp_home)

if(res):
  sys.exit(res)

if options.register:
  # tell running processes to re-read the GConf database
  import signal
  try:
    pids=os.popen('pidof gconfd-2').readlines()[0].split()
    for pid in pids:
      try:
        os.kill(int(pid),signal.SIGHUP)
      except OSError:
        pass
  except IndexError:
    pass
