#!/usr/local/bin/python2.7
"""Compute subsets of the TeX Live texmf tree."""

import argparse
from texscythe import config, VERSION, COPYRIGHT, orm

EPILOG = """
INCLUDE and EXCLUDE are package specs of the form:

  pkgname | pkgname:filetype1,...,filetype_n

The first variant includes all file types. Filetypes: run, src, doc, bin.

Example usage:

  Compute a subset with scheme-tetex excluding scheme-mininial's docfiles:

      $ texscyther -t texlive2015.tlpdb.gz --subset -i scheme-tetex -x scheme-minimal:doc

  texscyther will accept gzipped or normal tlpdb files.
"""


def print_version():
        print(72 * "-")
        print("  TeXScythe Version %s" % (VERSION))
        print("  %s" % COPYRIGHT)
        print(72 * "-")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        epilog=EPILOG,
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter
    )

    parser.add_argument("--initdb", action='store_true',
                        help="initialise the database")
    parser.add_argument("-s", "--subset", action='store_true',
                        help="compute a subset")
    parser.add_argument("-i", "--include", nargs='*',
                        help="include package in subset")
    parser.add_argument("-x", "--exclude", nargs='*',
                        help="exclude package in subset")
    parser.add_argument("--version", action='store_true',
                        help="show version")
    parser.add_argument("-p", "--prefix_filenames",
                        help="prefix string to filenames")
    parser.add_argument("-o", "--output-plist",
                        help="output filename")
    parser.add_argument("-t", "--tlpdb",
                        help="path to texive.tlpdb")
    parser.add_argument("-D", "--nodirs", action='store_true',
                        help="do not add directory entries in packing lists")
    parser.add_argument("-a", "--arch",
                        help="cpu architecure, e.g. 'alpha-linux' "
                        "(if not set, ARCH pkgs ignored)")
    parser.add_argument("-r", "--regex",
                        help="regex filter final file list before writing out")
    parser.add_argument("-q", "--quiet", action='store_true',
                        help="be quiet")
    parser.add_argument("-S", "--skip-missing-archpkgs",
                        action='store_true', help="skip missing ARCH packages")

    args = parser.parse_args()

    # No two of these should be enabled at once
    primary_tasks = [args.subset, args.version, args.initdb]
    chosen_tasks = [x for x in primary_tasks if x]

    if len(chosen_tasks) != 1:
        parser.error("please select a single primary task.\n" +
                     " one of: --initdb, --subset, --version")

    if args.tlpdb is None:
        parser.error("No TLPDB specified")

    cfg_kws = {}
    if args.prefix_filenames is not None:
        cfg_kws["prefix_filenames"] = args.prefix_filenames
    if args.output_plist is not None:
        cfg_kws["plist"] = args.output_plist
    if args.arch is not None:
        cfg_kws["arch"] = args.arch
    if args.nodirs:
        cfg_kws["dirs"] = False
    if args.regex is not None:
        cfg_kws["regex"] = args.regex
    if args.include is not None:
        cfg_kws["inc_pkgspecs"] = args.include
    if args.exclude is not None:
        cfg_kws["exc_pkgspecs"] = args.exclude
    if args.quiet is not None:
        cfg_kws["quiet"] = args.quiet
    if args.skip_missing_archpkgs:
        cfg_kws["skip_missing_archpkgs"] = args.skip_missing_archpkgs

    cfg = config.Config(args.tlpdb, **cfg_kws)

    if not args.version and not cfg.quiet:
        print_version()
        print(cfg)
        print("")

    # primary tasks
    if args.subset:
        sess = orm.init_orm(cfg)
        from texscythe import subset
        subset.compute_subset(cfg, sess)
        sess.close()
    elif args.initdb:
        from texscythe import tlpdbparser
        sess = orm.init_orm(cfg, force_create=True)
        sess.close()
    elif args.version:
        print_version()
    else:
        assert False  # should not happen
