# Copyright (C) 2007-2008, ENPC - INRIA - EDF R&D
#     Author(s): Pierre Tran
#
# This file is part of the air quality modeling system Polyphemus.
#
# Polyphemus is developed in the INRIA - ENPC joint project-team CLIME and in
# the ENPC - EDF R&D joint laboratory CEREA.
#
# Polyphemus is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# Polyphemus is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# For more information, visit the Polyphemus web site:
#      http://cerea.enpc.fr/polyphemus/
import commands, os, shutil, sys, tempfile

# The older 5.7 FastJX sources are not available anymore.
# A backup is used, waiting for Polyphemus to upgrade
# to newer FastJX versions.

#fastjx_url = "http://www.ess.uci.edu/group/prather/files/"
#fastjx_archive = "uci_fastjx71-f90.zip"
fastjx_url = "http://cerea.enpc.fr/"
fastjx_archive = "UCI_FastJX-5.7.zip"

# The Fastjx archive is put into a cache directory separated from the
# source directory to avoid the build server to download it every time.
cache_path = os.path.join(tempfile.gettempdir(), "polyphemus")


def run_cmd(cmd, action):
    s, o = commands.getstatusoutput(cmd)
    if s != 0:
        print "[ERROR] Failed %s the FastJX library:" % action
        print cmd
        print o
        print "return status: ", s
        exit(s)


# Checks for the FastJX source files.
if not os.path.isfile("fastJX.f"):
    # Downloads the FastJX archive, if necessary.
    if not os.path.isfile(fastjx_archive):
        cached_fastjx_archive = os.path.join(cache_path, fastjx_archive)
        if not os.path.isfile(cached_fastjx_archive):
            if not os.path.exists(cache_path):
                os.makedirs(cache_path)

        download_cmd = "wget " + fastjx_url + fastjx_archive \
                       + " -O " + cached_fastjx_archive
        run_cmd(download_cmd, "downloading")
        shutil.copyfile(cached_fastjx_archive, fastjx_archive)

    # Extracts the archive.
    if os.path.isfile(fastjx_archive):
        unzip_cmd = "unzip -o " + fastjx_archive
        run_cmd(unzip_cmd, "downloading")
