#!/usr/bin/env python
"""
Gets and sets some of the prerequisites before running the setup.py script.

Copyright:
    Southern California Earthquake Center

Author:
    David Gill <davidgil@usc.edu>
"""
# Python Imports
import os
import socket
import sys
import shutil
from subprocess import Popen, PIPE
from distutils.spawn import find_executable

try:
    host = socket.gethostbyaddr(socket.gethostname())[0]
except socket.herror:
    host = socket.gethostname()
except socket.gaierror:
    host = socket.gethostname()

if find_executable("python3"):
    if "python3" not in sys.executable:
        os.execv(find_executable("python3"), [find_executable("python3")] + sys.argv)
elif find_executable("python-3"):
    if "python-3" not in sys.executable:
        os.execv(find_executable("python-3"), [find_executable("python-3")] + sys.argv)
else:
    if "hpc-login" in host and "usc.edu" in host:
        print(
            "Error: UCVM requires at least Python 3 or higher to install. On USC HPC, you must source Python 3 before\n"
            "running this script. To do so, type in source /usr/usc/python/3.5.2/setup.csh if you are running Tcsh or\n"
            "source /usr/usc/python/3.5.2/setup.sh if you are running Bash. Then run this script again."
        )
    else:
        print("Error: UCVM requires at least Python 3 or higher to install. Please install Python 3 and try again.")
    sys.exit(-1)

print(
    "\n"
    "Thank you for downloading and installing UCVM!\n"
    "\n"
    "The UCVM framework is a collection of software tools designed to provide a standard\n"
    "interface to multiple, alternative 3D velocity models.\n"
    "\n"
    "UCVM requires the 1D velocity model, the DataProductReader model, the USGS/NOAA digital\n"
    "elevation model, and the Wills-Wald Vs30 model to operate. Additional velocity, elevation,\n"
    "and Vs30 models are available for download. These models cover various regions within the\n"
    "world, although most are located within California.\n"
)

if "mira" in host and "alcf.anl.gov" in host:
    print("Setup has detected that you are installing on Mira.\n")
    p = Popen(["/usr/local/bin/myprojectquotas"], stdout=PIPE, stdin=PIPE)
    out = p.communicate()[0].decode("ASCII").split("\n")
    default_dir = ""
    for i in range(len(out)):
        if "=====" in out[i] and len(str(out[i + 1]).split()) > 1 and str(out[i + 1]).split()[0].strip() != "":
            default_dir = os.path.join("/", "projects", str(out[i + 1]).split()[0].strip(), "ucvm-17.2.0")
elif "hpc-login" in host and "usc.edu" in host:
    print("Setup has detected that you are installing on USC HPC.\n")
    # Check for MPI loaded.
    if not shutil.which("mpicc"):
        print(
            "UCVM includes support for MPI. This support is required to extract large-scale material models. It is\n"
            "recommended that you exit this install script (Ctrl-C) and include MPI support. On USC HPC, the way you\n"
            "do this is source /usr/usc/openmpi/default/setup.csh if you are on Tcsh or \n"
            "source /usr/usc/openmpi/default/setup.sh if you are on Bash.\n"
        )
    default_dir = os.path.abspath(os.path.expanduser("~/ucvm-17.2.0"))
else:
    default_dir = os.path.abspath(os.path.expanduser("~/ucvm-17.2.0"))

if "VIRTUAL_ENV" not in os.environ:
    directory = ""

    while directory == "":
        directory = input(
            "The default installation path for UCVM %s.\nHit enter to install UCVM there or type in a different path: " %
            ("is " + default_dir if default_dir != "" else "cannot be determined")
        )
        if directory.strip() == "" and default_dir != "":
            directory = default_dir
        elif directory.strip() == "":
            print("Error: no directory provided.")
            directory = ""

    print("")
    p = Popen([sys.executable, "setup.py", "install", "--prefix=" + os.path.abspath(directory)])
else:
    p = Popen([sys.executable, "setup.py", "install"])

p.wait()
