#!/usr/bin/env python

"""
build ww3 library
"""
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, "scripts", "Tools")
sys.path.append(_LIBDIR)

from standard_script_setup import *
from CIME.buildlib import parse_input
from CIME.build import get_standard_makefile_args
from CIME.case import Case
from CIME.utils import run_cmd, expect

logger = logging.getLogger(__name__)

###############################################################################
def _main_func():
###############################################################################

    caseroot, libroot, bldroot = parse_input(sys.argv)

    with Case(caseroot) as case:

        casetools = case.get_value("CASETOOLS")
        wav_root = case.get_value("COMP_ROOT_DIR_WAV")
        gmake_j = case.get_value("GMAKE_J")
        gmake = case.get_value("GMAKE")
        driver = case.get_value("COMP_INTERFACE")

        #-------------------------------------------------------
        # create Filepath file
        #-------------------------------------------------------
        filepath_file = os.path.join(bldroot,"Filepath")
        if not os.path.isfile(filepath_file):
            caseroot = case.get_value("CASEROOT")
            paths = [os.path.join(caseroot,"SourceMods","src.ww3"),
                     os.path.join(wav_root,"src","source"),
                     os.path.join(wav_root,"src","cpl_" + driver)]
            with open(filepath_file, "w") as filepath:
                filepath.write("\n".join(paths))
                filepath.write("\n")

        #-------------------------------------------------------
        # create the library in libroot
        #-------------------------------------------------------

        complib = os.path.join(libroot,"libwav.a")
        makefile = os.path.join(casetools, "Makefile")

        cmd = "{} complib -j {} MODEL=ww3 COMPLIB={} -f {} {}" \
              .format(gmake, gmake_j, complib, makefile, get_standard_makefile_args(case))

        rc, out, err = run_cmd(cmd)
        logger.info("%s: \n\n output:\n %s \n\n err:\n\n%s\n"%(cmd,out,err))
        expect(rc == 0, "Command %s failed with rc=%s" % (cmd, rc))

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

if __name__ == "__main__":
    _main_func()
