#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
kread-ressource.py dumps a KDE configuration file. 
It is usefull for debugging KDE Kiosks settings,
where multiple config files are merged into the final configuration.  

The directory hierarchie for config files 
is based on the KDEDIRS environment variable
and can be made visible by  the command
kde4-config --path config

kreadconfig has a similiar purpose,
but is limited to a single value
"""

# $Id: kread-ressource.py 908 2010-07-01 15:23:15Z joergs $

import sys
import os
from PyKDE4.kdecore import ki18n, KAboutData, KCmdLineArgs, KCmdLineOptions, KConfig
from PyKDE4.kdeui import KApplication
 
#import pprint
#pp = pprint.PrettyPrinter(indent=4)

def getFullName( config ):
  """get the full name of a config group"""
  if config.name() == "<default>":
    return ""

  # check, if function config.parent is defined
  try: config.parent
  except AttributeError:
    # x doesn't exist, do something
    return "[" + config.name() + "]"
  else:
    # x exists, do something else
    parentsNames = getFullName( config.parent() )
    return  parentsNames + "[" + config.name() + "]"



def dumpGroup( config ):
  """print the entries of a config group"""

  # print secton name only if entries exists
  if config.entryMap():
    print getFullName( config )
    #print dir(config)
    #for i in config.entryMap():
    for i in config.keyList():
      immutaleString = ''
      if config.isEntryImmutable( i ):
        immutaleString = "[$i]"
      try:
        value = config.readEntry( i ).toUtf8()
        print "{0}{1}={2}".format( i, immutaleString, value )
      except AttributeError:
      # ignore when readEntry does not exist
        print i + " => readEntry not defined"
        #, i.count(), dir(i)
        pass
      except UnicodeEncodeError:
        print i + " => encoding error"
        pass
  print



def dumpSubGroups( config ):
  """print entries of the config group and all subgroups"""
  dumpGroup( config )
  #print dir( config )
  for i in config.groupList():
    configGroup=config.group(str(i))
    dumpSubGroups( configGroup )


appName     = "kread-resource.py"
catalog     = ""
programName = ki18n ("kread-resource.py")
version     = "$Rev: 908 $"
description = ki18n ("dump KDE resource/configuration files")
license     = KAboutData.License_GPL
copyright   = ki18n ("(c) 2010 Jörg Steffens")
text        = ki18n ("none")
homePage    = "www.dass-it.de"
bugEmail    = "rt@dass-it.de"
 
aboutData   = KAboutData (appName, catalog, programName, version, description,
                        license, copyright, text, homePage, bugEmail)

# command line argument handling
options = KCmdLineOptions()
options.add("type <kde-res-type>", ki18n("common types are: apps, config, xdgconf-autostart, xdgdata-apps. Default is"), "config")
options.add("types", ki18n("list all available types"))
options.add("+resourcename", ki18n("KDE ressource name (file name)"))

KCmdLineArgs.init(sys.argv, aboutData)
# Register the supported options
KCmdLineArgs.addCmdLineOptions( options )

app = KApplication()

args = KCmdLineArgs.parsedArgs();

if args.isSet("types"):
    os.system( "kde4-config --types" )
    exit()


# TODO: why is this not detected automatically?
if args.count() != 1:
  args.usage()

# TODO: check valid resource types (otherwise, this application starts a crash report
resourcetype = args.getOption("type");

configfilename = args.arg(0)
#print configfilename

#try:
config = KConfig(configfilename, KConfig.NoGlobals, resourcetype)
#except:
    #print "Unexpected error:", sys.exc_info()[0]
    #exit(1)


# only show the sub-groups.
# top-level entries will be in the section [MainWindow]
#dumpSubGroups( config )
for i in config.groupList():
  configGroup=config.group(str(i))
  dumpSubGroups( configGroup )
