#!/usr/bin/env python2.7

import sys
import os

_APP_PATH = \
    os.path.join(os.path.dirname(__file__), '..', '..', '..')

sys.path.insert(0, os.path.abspath(_APP_PATH))

import logging
import argparse

import pm.config.log
import pm.manifest
import pm.utility

_LOGGER = logging.getLogger(__name__)

def _parse_args():
    description = "Write file-manifest for the contents of the given path."
    parser = argparse.ArgumentParser(description=description)
    parser.add_argument(
        'root_path',
        help='Root path')

    parser.add_argument(
        '-f', '--force',
        action='store_true',
        help="Force the replacement of an existing manifest")

    parser.add_argument(
        '-mf', '--manifest-filename',
        help='Manifest filename')

    parser.add_argument(
        '-e', '--exclude-rel-path',
        metavar='REL-PATH',
        action='append',
        default=[],
        dest='excluded_rel_paths',
        help="Ignore the contents of this child path")

    parser.add_argument(
        '-ef', '--exclude-rel-filepath',
        metavar='REL-FILEPATH',
        action='append',
        default=[],
        dest='excluded_rel_filepaths',
        help="Ignore this filepath")

    parser.add_argument(
        '-i', '--include-rel-path',
        metavar='REL-PATH',
        action='append',
        default=[],
        dest='included_rel_paths',
        help="Constraint the matched files to one or more directories")

    parser.add_argument(
        '-j', '--json',
        action='store_true',
        help="Print result in JSON")

    args = parser.parse_args()

    return args

def _main():
    args = _parse_args()

    root_path = args.root_path
    manifest_filename = args.manifest_filename
    excluded_rel_paths = args.excluded_rel_paths
    excluded_rel_filepaths = args.excluded_rel_filepaths
    included_rel_paths = args.included_rel_paths
    do_force = args.force
    do_print_json = args.json

    m = pm.manifest.Manifest(
            root_path, 
            manifest_filename=manifest_filename, 
            excluded_rel_paths=excluded_rel_paths,
            excluded_rel_filepaths=excluded_rel_filepaths,
            included_rel_paths=included_rel_paths)

    manifest_filepath = m.write_manifest(force=do_force)

    if do_print_json is True:
        result = {
            'manifest_filepath': manifest_filepath,
        }

        print(pm.utility.pretty_json_dumps(result))

if __name__ == '__main__':
    pm.config.log.configure_log()
    _main()
