#!/usr/bin/env python
# vim:filetype=python
import zc.zk
import sys
import k.config
import pettingzoo.utils
from optparse import OptionParser

def create_node(zkconfig, text, path):
	if not path[0] == '/':
		path = "/" + path
	conn = pettingzoo.utils.connect_to_zk(
		pettingzoo.utils.get_server_list(zkconfig))
	conn.create_recursive(path, "", acl=zc.zk.OPEN_ACL_UNSAFE)
	conn.set(path, text)

def option_parser():
	usage = '\n'.join([
		"usage: %prog [options] [path]", "  Creates a znode on zookeeper."])
	parser = OptionParser(usage=usage)
	parser.add_option(
		"-i", "--input", dest="input", action="store_true", default=False,
		help="Store input from stdin in the znode")
	parser.add_option(
		"-s", "--server", dest="server",
		help="directly set zookeeper server to connect to arg")
	parser.add_option(
		"-z", "--zkconfig", dest="zkconfig",
		help="zookeeper config file: defaults to localhost:2181")
	parser.add_option(
		"-d", "--debug", dest="debug", default=False, action="store_true",
		help="turn on debugging")
	parser.add_option(
		"-l", "--lconfig", dest="lconfig",
		help="python logger config file: defaults to None (stderr)")
	return parser

def main():
	(options, args) = option_parser().parse_args()
	if options.debug:
		pettingzoo.utils.configure_logger()
	if options.lconfig:
		pettingzoo.utils.configure_logger(
			config_file=os.path.abspath(os.path.expanduser(options.lconfig)))
	if not options.zkconfig:
		k.config.KnewtonConfig()._add_config({
				'header': {'service_class': 'zookeeper'},
				'host': 'localhost', 'port': 2181},
			'zookeeper/default')
		options.zkconfig = 'zookeeper/default'
	if options.server:
		host, port = options.server.split(':')
		k.config.KnewtonConfig()._add_config({
				'header': {'service_class': 'zookeeper'},
				'host': host, 'port': int(port)},
			'zookeeper/cli')
		options.zkconfig = 'zookeeper/cli'
	zkconfig = k.config.KnewtonConfig().fetch_config(options.zkconfig)
	text = ""
	if options.input == True:
		text = ''.join(sys.stdin.readlines())
	create_node(zkconfig, text, '/'.join(args))

if __name__ == "__main__":
	main()
