#!/usr/bin/python3
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, division, unicode_literals
##
##  This file is part of etcTree, a dynamic and Pythonic view of
##  whatever information you tend to store in etcd.
##
##  etcTree is Copyright © 2015 by Matthias Urlichs <matthias@urlichs.de>,
##  it is licensed under the GPLv3. See the file `README.rst` for details,
##  including optimistic statements by the author.
##
##  This program is free software: you can redistribute it and/or modify
##  it under the terms of the GNU General Public License as published by
##  the Free Software Foundation, either version 3 of the License, or
##  (at your option) any later version.
##
##  This program is distributed in the hope that it will be useful,
##  but WITHOUT ANY WARRANTY; without even the implied warranty of
##  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##  GNU General Public License (included; see the file LICENSE)
##  for more details.
##
##  This header is auto-generated and may self-destruct at any time,
##  courtesy of "make update". The original is in ‘scripts/_boilerplate.py’.
##  Thus, do not remove the next line, or insert any blank lines above.
##
import logging
logger = logging.getLogger(__name__)
##BP

from aio_etcd.client import Client
from yaml import safe_load
from etcd_tree.util import to_etcd
import asyncio
import sys

from optparse import OptionParser
parser = OptionParser(conflict_handler="resolve")
parser.add_option("-h","--help","-?", action="help",
    help="print this help text")
parser.add_option("-s", "--server", dest="host", action="store",
    default="127.0.0.1", help="etcd server to connect to")
parser.add_option("-p", "--port", dest="port", action="store",
    default=None, type=int, help="User to connect as")
parser.add_option("-r", "--root", dest="root", action="store",
    default='/', help="Subtree to update")
parser.add_option("-d", "--delete", dest="delete", action="store_true",
    default=False, help="Remove other nodes")

(opts, args) = parser.parse_args()

if len(args)>1:
	print("I do not recognize non-option arguments.", file=sys.stderr)
	sys.exit(1)

kw = {'host':opts.host}
if opts.port:
	kw['port']=opts.port
et = Client(**kw)
if args and args[0] != "-":
	f = open(args[0])
else:
	f = sys.stdin
try:
	loop = asyncio.get_event_loop()
	loop.run_until_complete(to_etcd(et, opts.root, safe_load(stream=f), delete=opts.delete))
finally:
	if f is not sys.stdin: f.close()

