#!/usr/bin/python3
#
# A tool to manage a workspace of git repositories.
#
# Copyright (c) 2017-2018 Xevo Inc. All rights reserved.
#
# 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.
#

import argparse
import logging
import os
import sys

from wst import WSError
import wst.cmd
import wst.cmd.build
import wst.cmd.clean
import wst.cmd.config
import wst.cmd.default
import wst.cmd.env
import wst.cmd.init
import wst.cmd.list
import wst.cmd.remove
import wst.cmd.rename
from wst.conf import (
    find_root,
    get_default_ws_link,
    get_ws_dir
)

_LOG_FORMAT = '%(message)s'


# Keys that taint a build.
_TAINT_KEYS = {'type'}

# This dictionary gives the list of available subcmds. Each subcmd must supply
# a populate hook, which populates its arguments in the argument parser, and a
# do hook, which actually executes the subcmd given parsed arguments.
SUBCMDS = {
    'init': {
        'friendly': 'Initialize workspace with manifest',
        'args': wst.cmd.init.args,
        'handler': wst.cmd.init.handler
    },
    'list': {
        'friendly': 'List the available workspaces',
        'args': wst.cmd.list.args,
        'handler': wst.cmd.list.handler
    },
    'rename': {
        'friendly': 'Rename a workspace',
        'args': wst.cmd.rename.args,
        'handler': wst.cmd.rename.handler
    },
    'remove': {
        'friendly': 'Remove a workspace',
        'args': wst.cmd.remove.args,
        'handler': wst.cmd.remove.handler
    },
    'default': {
        'friendly': 'Set the default workspace',
        'args': wst.cmd.default.args,
        'handler': wst.cmd.default.handler
    },
    'config': {
        'friendly': 'Configure a workspace',
        'args': wst.cmd.config.args,
        'handler': wst.cmd.config.handler
    },
    'clean': {
        'friendly': 'Clean project or workspace',
        'args': wst.cmd.clean.args,
        'handler': wst.cmd.clean.handler
    },
    'build': {
        'friendly': 'Build project or workspace',
        'args': wst.cmd.build.args,
        'handler': wst.cmd.build.handler
    },
    'env': {
        'friendly': 'Run command in the workspace environment',
        'args': wst.cmd.env.args,
        'handler': wst.cmd.env.handler
    }
}


def parse_args():
    '''Parses the command-line arguments, returning the arguments, the argument
    parser, and the workspace directory to use.'''
    parser = argparse.ArgumentParser(description='Manage workspaces')
    parser.set_defaults(subcmd=None)
    parser.add_argument(
        '-r', '--root',
        action='store',
        required=False,
        help=('Root workspace directory (.ws) to act on. If not specified, '
              'will recursively try parent .ws directories.'))
    parser.add_argument(
        '-w', '--workspace',
        action='store',
        dest='ws',
        required=False,
        help='Name of the workspace inside the root on which to act')
    parser.add_argument(
        '-n', '--dry-run',
        action='store_true',
        default=False,
        required=False,
        help="Don't do anything; just print what would happen")
    parser.add_argument(
        '-d', '--debug',
        action='store_true',
        default=False,
        required=False,
        help='Debug output')
    parser.add_argument(
        '-v', '--verbose',
        action='store_true',
        default=False,
        required=False,
        help='Verbose output')

    subparsers = parser.add_subparsers(help='subcommands')
    for cmd, d in SUBCMDS.items():
        subparser = subparsers.add_parser(cmd, help=d['friendly'])
        d['args'](subparser)
        subparser.set_defaults(subcmd=cmd)

    args = parser.parse_args()

    if args.root is None:
        args.root = find_root()
        if args.root is None:
            if args.subcmd != 'init':
                raise WSError("can't find .ws directory; please run %s init"
                              % sys.argv[0])

    if args.subcmd not in ('init', 'default', 'list', 'rename', 'remove'):
        if args.ws is None:
            args.ws = get_default_ws_link(args.root)
        ws_dir = get_ws_dir(args.root, args.ws)
        if not os.path.exists(ws_dir):
            raise WSError('workspace %s at %s does not exist.'
                          % (args.ws, ws_dir))
        if not os.path.exists(ws_dir):
            raise WSError('workspace at %s is not a directory.' % ws_dir)
    else:
        if args.ws is not None:
            raise WSError('cannot specify a top-level workspace with the %s '
                          'subcmd' % args.subcmd)
        ws_dir = None

    if args.debug:
        level = logging.DEBUG
    elif args.verbose or args.dry_run:
        level = logging.INFO
    else:
        level = logging.WARNING

    # Must remove old handlers first.
    for handler in logging.root.handlers:
        logging.root.removeHandler(handler)
    logging.basicConfig(format=_LOG_FORMAT, level=level)

    if args.dry_run:
        wst.shell.set_dry_run()

    return args, parser, ws_dir


def main():
    '''Entrypoint.'''
    logging.basicConfig(format=_LOG_FORMAT, level=logging.WARNING)

    args, parser, ws_dir = parse_args()
    if args.subcmd is None:
        parser.print_help()
        return 1
    handler = SUBCMDS[args.subcmd]['handler']
    handler(ws_dir, args)


if __name__ == '__main__':
    try:
        status = main()
    except WSError as e:
        logging.error(e)
        status = 1
    sys.exit(status)
