#!/usr/bin/python

"""
Propagate kernel config vars to the next level
"""

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("-k", "--key", dest="key", action="store", help="database key")
	#parser.add_option("-m", "--move", dest="move", action="store_true", help="move values instead")
	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 not opts.key:
		raise RuntimeError("Database key required")

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

	sub=opts.key
	i=sub.rfind("/")
	if i>-1:
		up=sub[:i]
	else:
		up=""
	
	cf={}
	for conf,val in db.DoSelect("select conf,val from kernelconfig where sub=${sub}", sub=sub, _empty=1):
		cf[conf] = val
	for conf,val in db.DoSelect("select conf,val from kernelconfig where sub=${up}", up=up, _empty=1):
		try: del cf[conf]
		except KeyError: pass

	i=0
	upd=0
	args={}
	for k,v in cf.iteritems():
		if i: s += ","
		else: s="insert into kernelconfig(conf,sub,val) values ";
		s += "(${key%d},${up},${val%d})" % (i,i)
		args["key"+str(i)] = k
		args["val"+str(i)] = v
		i+=1
		upd+=1

		if i >= 100:
			db.Do(s, up=up,**args)
			args={}
			i=0
	if i:
		db.Do(s, up=up,**args)
	print upd
	db.commit()

