#!/usr/bin/env python3
{{ batchdirectives }}

"""
Performs short term archiving for restart files, history and rpointer
files in the $RUNDIR associated with $CASEROOT.  Normally this script
is called by case.submit on batch systems.

"""

import sys, os, time
os.chdir( '{{ caseroot }}')

_LIBDIR = os.path.join("{{ cimeroot }}", "CIME", "Tools")
sys.path.append(_LIBDIR)

from standard_script_setup          import *
from CIME.case import Case

logger = logging.getLogger(__name__)


###############################################################################
def parse_command_line(args, description):
###############################################################################

    parser = argparse.ArgumentParser(description=description,
                                     formatter_class=argparse.RawTextHelpFormatter)

    CIME.utils.setup_standard_logging_options(parser)

    parser.add_argument("--caseroot", default=os.getcwd(),
                        help="Case directory to build")

    parser.add_argument("--no-incomplete-logs", default=False, action="store_true",
                        help="Whether to archive logs which have been completed or not")

    parser.add_argument("--copy-only", default=False, action="store_true",
                        help="Copy instead of move the files to be archived")

    parser.add_argument("--last-date", default=None,
                        help="WARNING: This option with --force-move may corrupt your run directory! Use at your own risk! "
                        "Last simulation date to archive, specified as 'Year-Month-Day'. "
                        "Year must be specified with 4 digits, while month and day can be specified without zero padding. "
                        "'0003-11-4' would archive at most files for the simulated year 3, month 11, day 4."
                        "This option implies --copy-only unless --force-move is specified ")

    parser.add_argument("--force-move", default=False, action="store_true",
                        help="Move the files even if it's unsafe to do so, dangerous if used with --copy-only.")

    parser.add_argument("--test-all", default=False, action="store_true",
                        help="Run tests of st_archiver functionality on config_arvchive.xml")

    parser.add_argument("--test-case", default=False, action="store_true",
                        help="Run tests of st_archiver functionality on env_arvchive.xml")

    parser.add_argument("--resubmit", default=False, action="store_true",
                        help="If RESUBMIT is set, this performs the resubmissions."
                        "This is primarily meant for use by case.submit")

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

    if args.caseroot is not None:
        os.chdir(args.caseroot)

    if args.last_date is not None and args.force_move is False:
        args.copy_only = True

    if args.force_move is True:
        args.copy_only = False

    return (args.caseroot, args.last_date, args.no_incomplete_logs, args.copy_only,
            args.test_all, args.test_case, args.resubmit)

###############################################################################
def _main_func(description):
###############################################################################
    sys.argv.extend([] if "ARGS_FOR_SCRIPT" not in os.environ else os.environ["ARGS_FOR_SCRIPT"].split())
    caseroot, last_date, no_incomplete_logs, copy_only, testall, testcase, resubmit = parse_command_line(sys.argv, description)
    with Case(caseroot, read_only=False) as case:
        if testall:
            success = case.test_st_archive()
        elif testcase:
            success = case.test_env_archive()
        else:
            success = case.case_st_archive(last_date_str=last_date,
                                           archive_incomplete_logs=not no_incomplete_logs,
                                           copy_only=copy_only, resubmit=resubmit)

    sys.exit(0 if success else 1)

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

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