#! /usr/bin/env python3

import sys, os

_CIMEROOT = os.environ.get("CIMEROOT")
if _CIMEROOT is None:
    raise SystemExit("ERROR: must set CIMEROOT environment variable")

_LIBDIR = os.path.join(_CIMEROOT, "CIME", "Tools")
sys.path.append(_LIBDIR)

from standard_script_setup import *
from CIME.utils import expect, run_bld_cmd_ensure_logging, safe_copy
from CIME.case import Case
from CIME.buildlib import parse_input

logger = logging.getLogger(__name__)

###############################################################################
def buildlib(bldroot, installpath, case):
###############################################################################
    scream_opts = case.get_value("SCREAM_CMAKE_OPTIONS")
    print ("building scream")
    tokens = scream_opts.split()
    expect (len(tokens) % 2 == 0, "Error! SCREAM_CMAKE_OPTIONS should contain a string of the form 'option1 value1 option2 value2 ...'\n")
    it = iter(tokens)

    # Parse all options and put them in a dict first. This allows to overwrite options via
    #  ./xmlchange --append SCRAM_CMAKE_OPTIONS="NAME VALUE"
    # rather than having to reset them all, running ./xmlquery first to see what the others are
    cmake_args_dict = {}
    for item in it:
        cmake_args_dict[item] = next(it)

    cmake_args = ""
    for k,v in cmake_args_dict.items():
        cmake_args += f" -D{k}={v}"

    atm_dyn_tgt = case.get_value("CAM_TARGET")
    cmake_args += " -DSCREAM_DYN_TARGET={}".format(atm_dyn_tgt)
    cmake_args += " -DSCREAM_CIME_BUILD=ON"

    print("scream cmake options: '{}'".format(cmake_args))

    return cmake_args

###############################################################################
def _main(argv, documentation):
###############################################################################
    caseroot, libroot, bldroot = parse_input(sys.argv)
    with Case(caseroot, read_only=False) as case:
        buildlib(bldroot, libroot, case)

if (__name__ == "__main__"):
    _main(sys.argv, __doc__)
