#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
#  protocon
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions are
#  met:
#
#  * Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#  * Redistributions in binary form must reproduce the above
#    copyright notice, this list of conditions and the following disclaimer
#    in the documentation and/or other materials provided with the
#    distribution.
#  * Neither the name of the project nor the names of its
#    contributors may be used to endorse or promote products derived from
#    this software without specific prior written permission.
#
#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
#  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
#  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
#  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
#  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
#  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
#  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

import argparse
import functools
import os
import sys

import boltons.iterutils

get_path = functools.partial(os.path.join, os.path.abspath(os.path.dirname(__file__)))
sys.path.append(get_path('lib'))

import protocon

def main():
	plugins = protocon.PluginManager([os.path.join(os.path.expanduser('~'), '.config', 'protocon', 'plugins')])
	epilog = 'target_url examples:\n'
	for connection_driver in plugins.connection_drivers.values():
		for example in connection_driver.examples.values():
			epilog += "  {0}\n".format(example)

	parser = argparse.ArgumentParser(description='ProtoCon', conflict_handler='resolve', formatter_class=argparse.RawTextHelpFormatter)
	parser.add_argument('-q', '--quiet', action='store_true', default=False, help='initialize quiet to True')
	parser.add_argument('-v', '--version', action='version', version='%(prog)s Version: ' + protocon.__version__)
	parser.add_argument('target_url', help='the connection URL')
	parser.add_argument('scripts', metavar='script', nargs='*', help='the script to execute')
	parser.epilog = epilog
	arguments = parser.parse_args()

	try:
		engine = protocon.Engine.from_url(arguments.target_url)
	except protocon.ProtoconDriverError as error:
		protocon.print_error('Driver error: ' + error.message)
	else:
		engine.entry(arguments.scripts)
		engine.connection.close()
	return 0

if __name__ == '__main__':
	sys.exit(main())
