#! /usr/bin/env python3
# -*- coding: utf-8 -*-

# (c) 2013 Marcos Dione <mdione@grulic.org.ar>

# This file is part of ayrton.
#
# ayrton 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.
#
# ayrton 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 for more details.
#
# You should have received a copy of the GNU General Public License
# along with ayrton.  If not, see <http://www.gnu.org/licenses/>.

# cannot be simpler :)
import ayrton

# well, actually, it can :)
import argparse
import sys
import os.path

parser= argparse.ArgumentParser (prog=os.path.split (sys.argv[0])[-1], description='pythonic shell-like scripting language.')
script_group= parser.add_mutually_exclusive_group (required=True)
script_group.add_argument ('-c', '--script', help='source of the script to run.')
# script_group.add_argument ('file', required=False, help='file with the script to run.')
# beh: TypeError: 'required' is an invalid argument for positionals
# now I have to replace all the examples/scripts I developed to add the -f :(
script_group.add_argument ('-f', '--file', help='file with the script to run.')
parser.add_argument ('-V', '--version', action='version', version="%%(prog)s %s" % ayrton.__version__)
# parser.add_argument ('-x', '--trace', help='enable execution tracing.')
# parser.add_argument ('-p', '--capture', help="capture the comands' output à la sh.")
parser.add_argument ('args', nargs='*', help='arguments to be passed to the script.')

found= -1
ayrton_args= []
args= sys.argv[:]
for i, a in enumerate (args):
    if a in ('-c', '--script', '-f', '--file'):
        found= i+1

    if found==-1 or i<found:
        ayrton_args.append (a)
        sys.argv.pop (0)
    elif i==found:
        # this is the parameter which actually has to go to both
        ayrton_args.append (sys.argv[0])

# anything before found is arguments for ayrton itself
# anything else goes to the script

opts= parser.parse_args (ayrton_args)

ayrton.main (**vars (opts))
