#!/usr/bin/env python

"""
Analyze results from a test root area, finding namelist and non-BFB
changes, and updating baselines. Purpose is, instead of re-running tests
in generate mode, which is very slow, allow for very fast analsis and
blessing of diffs.

You may need to load modules for cprnc to work.
"""

from standard_script_setup import *

from CIME.utils import expect
from CIME.XML.machines import Machines
from CIME.bless_test_results import bless_test_results

import argparse, sys, os, doctest

_MACHINE = Machines()

###############################################################################
def parse_command_line(args, description):
###############################################################################
    parser = argparse.ArgumentParser(
        usage="""\n{0} [-n] [-r <TESTROOT>] [-b <BRANCH>] [-c <COMPILER>] [<TEST> <TEST> ...] [--verbose]
OR
{0} --help
OR
{0} --test

\033[1mEXAMPLES:\033[0m
    \033[1;32m# From most recent run, bless any namelist changes \033[0m
    > {0} -n
    \033[1;32m# From most recent run, bless all changes \033[0m
    > {0}
    \033[1;32m# From most recent run, bless changes to test foo and bar only \033[0m
    > {0} foo bar
    \033[1;32m# From most recent run, bless only namelist changes to test foo and bar only \033[0m
    > {0} -n foo bar
    \033[1;32m# From most recent run of jenkins, bless history changes for next \033[0m
    > {0} -r /home/jenkins/acme/scratch/jenkins -b next --hist-only
""".format(os.path.basename(args[0])),
        description=description,
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )

    default_baseline_name = CIME.utils.get_current_branch(repo=CIME.utils.get_cime_root())
    default_baseline_root = _MACHINE.get_value("BASELINE_ROOT")
    default_compiler      = _MACHINE.get_default_compiler()
    scratch_root          = _MACHINE.get_value("CIME_OUTPUT_ROOT")
    default_testroot      = os.path.join(scratch_root)

    CIME.utils.setup_standard_logging_options(parser)

    parser.add_argument("-n", "--namelists-only", action="store_true",
                        help="Only analyze namelists.")

    parser.add_argument("--hist-only", action="store_true",
                        help="Only analyze history files.")

    parser.add_argument("-b", "--baseline-name", default=default_baseline_name,
                        help="Name of baselines to use, corresponds to branch used.")

    parser.add_argument("--baseline-root", default=default_baseline_root,
                        help="Root of baselines.")

    parser.add_argument("-c", "--compiler", default=default_compiler,
                        help="Compiler of run you want to bless")

    parser.add_argument("-p", "--no-skip-pass", action="store_true",
                        help="Normally, if namelist or baseline phase exists and shows PASS, we assume no bless is needed. "
                        "This option forces the bless to happen regardless.")

    parser.add_argument("--report-only", action="store_true",
                        help="Only report what files will be overwritten and why. Caution is a good thing when updating baselines")

    parser.add_argument("-r", "--test-root", default=default_testroot,
                        help="Path to test results that are being blessed")

    parser.add_argument("-t", "--test-id",
                        help="Limit processes to case dirs matching this test-id. Can be useful if mutiple runs dumped into the same dir.")

    parser.add_argument("-f", "--force", action="store_true",
                        help="Update every diff without asking. VERY DANGEROUS. Should only be used within testing scripts.")

    parser.add_argument("bless_tests", nargs="*",
                        help="When blessing, limit the bless to tests matching these regex")

    args = CIME.utils.parse_args_and_handle_standard_logging_options(args, parser)

    expect(not (args.report_only and args.force),
           "Makes no sense to use -r and -f simultaneously")
    expect(not (args.namelists_only and args.hist_only),
           "Makes no sense to use --namelists-only and --hist-only simultaneously")

    return args.baseline_name, args.baseline_root, args.test_root, args.compiler, args.test_id, args.namelists_only, args.hist_only, args.report_only, args.force, args.bless_tests, args.no_skip_pass

###############################################################################
def _main_func(description):
###############################################################################
    if ("--test" in sys.argv):
        test_results = doctest.testmod(verbose=True)
        sys.exit(1 if test_results.failed > 0 else 0)

    baseline_name, baseline_root, test_root, compiler, test_id, namelists_only, hist_only, report_only, force, bless_tests, no_skip_pass = \
        parse_command_line(sys.argv, description)

    success = bless_test_results(baseline_name, baseline_root, test_root, compiler,
                                 test_id=test_id, namelists_only=namelists_only, hist_only=hist_only,
                                 report_only=report_only, force=force, bless_tests=bless_tests, no_skip_pass=no_skip_pass)
    sys.exit(0 if success else 1)

###############################################################################

if (__name__ == "__main__"):
    _main_func(__doc__)
