#!/usr/bin/env python
#
# PATH command-line interface
# Copyright (c) 2003-04 Francis Rogers
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

from argparse import ArgumentParser
import sys
import os
from os.path import expanduser, join as ospj
from pathlang import Path

def path_main():
    """
    Command line interpreter for the PATH programming language.
    """
    p = ArgumentParser()
    p.add_argument('-d', '--debug', action='store_true', help='print debug messages to stderr')
    p.add_argument('-n', '--noplugins', action='store_true', help='disable all plugins')
    p.add_argument('-p', '--plugindir', action='append', help='load plugins from directory DIR instead')
    p.add_argument('file', nargs='+')
    args = p.parse_args()
    for f in args.file:
        prog = Path()
        prog.load_prog_file(f)
        if not args.noplugins:
            path_load_plugins(prog, args.plugindir)
        prog.verbose = args.debug
        try:
            prog.run()
        except KeyboardInterrupt:
            sys.exit()

def path_load_plugins(prog, plugin_dir_override):
    """
    Load plugins from plugin directories.

    :param prog: Path interpreter object
    :param plugin_dir_override: List of plugin directories, None or [] specifies to use defaults
    """
    plugindirs = ["/usr/lib/path", expanduser("~/.path")]

    if plugin_dir_override:
        expanded = [expanduser(path) for path in plugindirs]
        plugindirs = [d for d in expanded if os.access(d, os.F_OK)]
    for plugindir in plugindirs:
        if os.access(plugindir, os.F_OK):
            for plugin in os.listdir(plugindir):
                if plugin.endswith(".py"):
                    with open(ospj(plugindir, plugin)) as p:
                        exec(compile(p.read(), ospj(plugindir, plugin), 'exec'), {"glob_path": prog})

if __name__ == "__main__":
    path_main()
