#!/usr/bin/python

"""
Read a configuration file and save to a database
"""

import sys
from sqlmix import Db

db="config"

if __name__ == "__main__":
	try: from optparse import OptionParser
	except ImportError: from optik import OptionParser

	parser = OptionParser(conflict_handler="resolve")
	parser.add_option("-h","--help","-?", action="help", help="gibt diesen Hilfstext aus")
	parser.add_option("-f", "--file", dest="file", action="store", help="file to write")
	parser.add_option("-k", "--key", dest="key", action="store", help="database key")
	parser.add_option("-K", "--diff", dest="diff", action="store", help="key to generate a diff against")
	parser.add_option("-d", "--database", dest="database", action="store", help="database name")

	(opts, args) = parser.parse_args()
	if args:
		raise RuntimeError("No arguments accepted")

	if opts.database: db=opts.database
	db=Db(db)

	if opts.file: f=open(opts.file,"w")
	else: f=sys.stdout

	sub=opts.key
	if not sub: sub=""
	known={}
	subs = []
	while True:
		subs = [ sub ] + subs
		if not sub or opts.diff:
			break
		i=sub.rfind("/")
		if i>-1:
			sub=sub[:i]
		else:
			sub=""

	for sub in subs:
		for conf,val in db.DoSelect("select conf,val from kernelconfig where sub=${sub}", sub=sub, _empty=1):
			known[conf] = val

	if opts.diff:
		other = {}
		subs = []
		sub = opts.diff
		if sub == "-": sub = ""
		while True:
			subs = [ sub ] + subs
			if not sub or opts.diff:
				break
			i=sub.rfind("/")
			if i>-1:
				sub=sub[:i]
			else:
				sub=""

		for sub in subs:
			for conf,val in db.DoSelect("select conf,val from kernelconfig where sub=${sub}", sub=sub, _empty=1):
				other[conf] = val

		for conf,val in known.iteritems():
			oval = other.get(conf,None)
			if val is None:
				if oval is not None:
					print >>f, "# CONFIG_%s is not set" % (conf,)
			elif oval is None or val != oval:
				print >>f, "CONFIG_%s=%s" % (conf,val)

	else:
		for conf,val in known.iteritems():
			if val is None:
				print >>f, "# CONFIG_%s is not set" % (conf,)
			else:
				print >>f, "CONFIG_%s=%s" % (conf,val)
	db.commit()

