#!/usr/bin/python

# osh
# Copyright (C) 2005 Jack Orenstein <jao@geophile.com>
#
# 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 2 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 for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

import sys
import traceback

import osh.tpg
import osh.oshparser
import osh.oshobjects

args = sys.argv[1:]
if len(args) == 0:
    args.append('help')
verbosity = 0
if args[0].startswith('-v'):
    level = args[0][2:]
    if level:
        verbosity = int(level)
    else:
        verbosity = 1
    args = args[1:]
osh.oshobjects.verbosity = verbosity
# args = tweakCommandLine(args)
command_source = '#'.join(args)
if verbosity >= 1:
    print command_source
try:
    command = osh.oshparser.parse(command_source)
    command.execute()
except osh.oshobjects.ErrorHandlerException, e:
    print >>sys.stderr, e.reason
    sys.exit(1)


OSH_SYMBOLS = ['[', ']', '^', ',', ':', '@']

def isolateLeft(L, c):
    M = []
    for s in L:
        if s.startswith(c) and len(s) > len(c):
            M.append(c)
            M.append(s[1:])
        else:
            M.append(s)
    return M

def isolateRight(L, c):
    M = []
    for s in L:
        if s.endswith(c) and len(s) > len(c):
            M.append(s[:-1])
            M.append(c)
        else:
            M.append(s)
    return M

def isolate(L, c):
    return isolateRight(isolateLeft(L, c), c)

def fixEmptyListLiterals(L):
    if len(L) < 2:
        M = L
    else:
        L0 = L[0]
        L1 = L[1]
        if L0 == '[' and L1 == ']':
            M = ['[]'] + fixEmptyListLiterals(L[2:])
        else:
            M = [L0] + fixEmptyListLiterals(L[1:])
    return M

def tweakCommandLine(args):
    for symbol in OSH_SYMBOLS:
        args = isolate(args, symbol)
    # If '[]' was an input token, (or '[ ]', etc.), then we just broke
    # it apart into two tokens. Put them back together.
    args = fixEmptyListLiterals(args)
