#!/usr/bin/env python

import os, shutil, sys, glob, imp

CIMEROOT = os.environ.get("CIMEROOT")
if CIMEROOT is None:
    raise SystemExit("ERROR: must set CIMEROOT environment variable")
sys.path.append(os.path.join(CIMEROOT, "scripts", "Tools"))

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

logger = logging.getLogger(__name__)

###############################################################################
def _build_cice():
###############################################################################

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

    with Case(caseroot) as case:
        casetools = case.get_value("CASETOOLS")
        gmake_j   = case.get_value("GMAKE_J")
        gmake     = case.get_value("GMAKE")
        srcroot   = case.get_value("SRCROOT")

        # call buildcpp  to set the cppdefs
        cmd = os.path.join(os.path.join(srcroot,"components","cice","cime_config","buildcpp"))
        logger.info("     ...calling cice buildcpp to set build time options")
        try:
            mod = imp.load_source("buildcpp", cmd)
            cice_cppdefs = mod.buildcpp(case)
        except:
            raise

        # create Filepath file
        objroot = case.get_value("OBJROOT")
        filepath_file = os.path.join(objroot,"ice","obj","Filepath")
        if not os.path.isfile(filepath_file):
            srcroot = case.get_value("SRCROOT")
            caseroot = case.get_value("CASEROOT")
            paths = [os.path.join(caseroot,"SourceMods","src.cice"), 
                     os.path.join(srcroot,"components","cice","src","drivers","cesm"),
                     os.path.join(srcroot,"components","cice","src","io_pio"),
                     os.path.join(srcroot,"components","cice","src","mpi"),
                     os.path.join(srcroot,"components","cice","src","source")]
            with open(filepath_file, "w") as filepath:
                filepath.write("\n".join(paths))
                filepath.write("\n")

        # build the library
        complib = os.path.join(libroot,"libice.a")
        makefile = os.path.join(casetools, "Makefile")

        cmd = "%s complib -j %d MODEL=cice COMPLIB=%s -f %s USER_CPPDEFS=\"%s\"" \
            % (gmake, gmake_j, complib, makefile, cice_cppdefs )

        rc, out, err = run_cmd(cmd, from_dir=bldroot)
        expect(rc == 0, "Command %s failed rc=%d\nout=%s\nerr=%s" % (cmd, rc, out, err))

        logger.info("Command %s completed with output %s\nerr %s" ,cmd, out, err)

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

if __name__ == "__main__":
    _build_cice()
