#!/usr/bin/env bash

set -o pipefail

# Create file for TestHub
# This file will be populated during math/test
echo "# If this file contains only this line, install failed before math/test" > testhub.yml

export BUILD_LOG="build.log"

make data/version_number

# Get system info
./help > $BUILD_LOG  2>&1

# By scoping the code in brackets we only need to write the redirect once
# at the end of the file
{

# Block sudo access, this check should come first as if a user blindly types "sudo ./install" then MESA_DIR won't be set
# So lets catch this error first rather then forcing them to set MESA_DIR under sudo
if  [ ${EUID:-$(id -u)} -eq 0 ];
then
    echo
    echo "****************************************************************"
    echo "*                                                              *"
    echo "*      MESA should not be installed with root privileges.      *"
    echo "*       Using sudo is a bad idea and unlikely to fix the       *"
    echo "*                   problem you think you have.                *"
    echo "*                                                              *"
    echo "*                If you have permission issues,                *"
    echo "*             contact the mesa-users mailing list.             *"
    echo "*                                                              *"
    echo "*        If you wish to install MESA in a root location        *"
    echo "*                then we assume you can edit the               *"
    echo "*             ./install file to remove this check.             *"
    echo "*                                                              *"
    echo "****************************************************************"
    echo
    exit 1
fi

# Check we are on git and if so did git lfs work?
if [ -d ".git" ] || [ -f ".git" ]
then
	# First check if git lfs is installed
	if ! command -v git-lfs >/dev/null 2>&1
	then
		echo
		echo "****************************************************************"
		echo "*                     git lfs is not installed                 *"
		echo "*                                                              *"
		echo "****************************************************************"
		echo
		exit 1
	fi

        # empirically on lustre filesystems the LFS files don't immediately appear
        # if requested, sleep for a bit before proceeding and doing the check
        if [ -n "${MESA_GIT_LFS_SLEEP}" ]; then
            sleep "${MESA_GIT_LFS_SLEEP}"
        fi

        # check that each LFS file has a full copy on disk
        FILE_LIST=$(git-lfs ls-files | awk '{print $NF}')
        for LFS_FILE in ${FILE_LIST}; do
            # the checks have this form to handle uncommitted changes to LFS files
            # if no file exists, that means the file was probably deleted and that's OK
            # if the file exists, but is short, then it is probably the bare LFS pointer
            #   and that indicates a problem retrieving the file
            if [ -f "${LFS_FILE}" ] && [ $(du -k "${LFS_FILE}" | cut -f1) -le 4 ];
            then
                echo
                echo "${LFS_FILE} is smaller than expected for a file tracked by git LFS"
                echo
                echo "****************************************************************"
                echo "*        Some data files were not successfully retrieved       *"
                echo "*                                                              *"
                echo "*                         Try running:                         *"
                echo "*                   git lfs install --force                    *"
                echo "*                           and then                           *"
                echo "*                         git lfs pull                         *"
                echo "*                                                              *"
                echo "****************************************************************"
                echo
                exit 1
            fi
        done

fi




if [ -z "$MESA_DIR" ]
then
	if [ -z "$MESA_DIR_INTENTIONALLY_EMPTY" ]
	then
		echo
		echo "****************************************************************"
		echo "*                                                              *"
		echo "*                      MESA_DIR is not set                     *"
		echo "*         Please set MESA_DIR and run ./install again          *"
		echo "*                                                              *"
		echo "*                        Please also read:                     *"
		echo "*  http://www.astro.wisc.edu/~townsend/static.php?ref=mesasdk  *"
		echo "*                      To set up the MESASDK                   *"
		echo "*                                                              *"
		echo "****************************************************************"
		echo
		exit 1
	fi
fi

if [[ "$MESA_DIR" == *" "* ]];
then
	echo
	echo "****************************************************************"
	echo "*                                                              *"
	echo "*               MESA_DIR can not contain whitespace            *"
	echo "*              Please move your MESA_DIR to a folder           *"
	echo "*                     without spaces in its name               *"
	echo "*                                                              *"
	echo "****************************************************************"
	echo
	exit 1
fi


# there is also a tool called ndiff which is part of the nmap security
# scanner.  if called with the -? argument, that tool returns 2.
# The ndiff utility we want recognizes this will return 0.
# We send the output, which is on stderr, to dev/null

ndiff -? 2> /dev/null
if [ $? -ne 0 ]
then
	echo
	echo "****************************************************************"
	echo "*                                                              *"
	echo "*    You need to install ndiff before you can install mesa.    *"
	echo "*                                                              *"
	echo "*                                                              *"
	echo "*    But only if you are not using the SDK. If you see this    *"
	echo "*            message and are trying to use the sdk             *"
	echo "*         then please check your environment variables         *"
	echo "*                        are set first.                        *"
	echo "*                                                              *"
	echo "*                                                              *"
	echo "*    The ndiff tar file is in the mesa/scripts directory.      *"
	echo "*    Unpack it anywhere (tar -zxvf ndiff-2.00.tar.gz),         *"
	echo "*    and cd to the ndiff directory.                            *"
	echo "*    Then do the usual sequence:                               *"
	echo "*                                                              *"
	echo "*           ./configure                                        *"
	echo "*           make all                                           *"
	echo "*           sudo make install                                  *"
	echo "*                                                              *"
	echo "*    Note: 'make check' seems to give lots of false alarms.    *"
	echo "*    I suggest skipping that step in the ndiff installation.   *"
	echo "*                                                              *"
	echo "*    BTW: there's another 'ndiff' out there in the unix world. *"
	echo "*           http://nmap.org/ndiff/                             *"
	echo "*    I'm sure it's a great tool, but it isn't what we need.    *"
	echo "*                                                              *"
	echo "****************************************************************"
	echo
	exit 1
fi

# Check mesasdk version
if [ ! -z "$MESASDK_ROOT" ]; then
    if [ -z "$MESA_DIR_INTENTIONALLY_EMPTY" ]; then
	MINIMUM_VERSION=26.3.2
	VERSION_CHECK=$(echo $($MESA_DIR/scripts/check_sdk_version $MINIMUM_VERSION))
	echo MESASDK version check $VERSION_CHECK
	if [ $VERSION_CHECK != "passed" ]; then
	    echo Your MESASDK is too old please update to version $MINIMUM_VERSION or newer
	    exit 1
        fi
    else
	echo MESASDK_ROOT environment variable is not set. See https://docs.mesastar.org/en/latest/installation.html#set-your-environment-variables
	exit 1
    fi
fi

SYSTEM=`uname -s`

function enum_procs {
    if [ -n "$NPROCS" ]; then
	echo $NPROCS
    else
	case `uname -s` in
	    Linux)
		if [ -r /proc/cpuinfo ]; then
		    grep -c processor /proc/cpuinfo
		else
		    echo 1
		fi
		;;
	    Darwin)
		sysctl hw.ncpu | awk '{print $2}'
		;;
	    *)
	    echo 1
	    ;;
	esac
    fi
}

# MacOS has gnumake version 3.81, which does not support -Oline
if [ "${SYSTEM}" = "Darwin" ]; then
    make -w -j$(enum_procs)
else
    make -w -Oline -j$(enum_procs)
fi

if [ $? -ne 0 ]
then
    echo
    echo "!! MESA install failed, see above or $BUILD_LOG for details !!"
    echo
    exit 1
fi

echo
echo
echo
echo
echo
echo
echo
echo "************************************************"
echo "************************************************"
echo "************************************************"
echo
echo 'MESA installation was successful'
echo
echo "************************************************"
echo "************************************************"
echo "************************************************"
echo
echo
echo
echo

# end scope and redirect output
} 2>&1 | tee -a $BUILD_LOG | grep -Ev "(Leaving|Entering) directory"