#! /bin/sh
## NOAA PMEL TMAP
## Finstall
## Modifies ferret_paths_template.{sh,csh} and pyferret_template scripts 
## to specify locations of ferret software and demo data sets to create 
## the ferret_paths and pyferret scripts. 


### Assign $fer_dir, the desired FER_DIR value
get_fer_dir() {
    if [ -n "${FER_DIR}" ]; then
        if [ -d "${FER_DIR}/ext_func/pylibs" ]; then
            fer_dir="${FER_DIR}"
            echo " "
            echo " The environment variable FER_DIR is currently defined as "
            echo " "
            echo "     '${FER_DIR}' "
            echo " "
            echo " This should be the directory created from extracting the PyFerret "
            echo " tar.gz file.  It contains subdirectories bin, contrib, examples, "
            echo " ext_func, go, lib, and ppl. "
            read -p " Is that correct and acceptable (y/n) [y] " ans
            if [ -z "${ans}" ] || [ "${ans}" = "Y" ] || [ "${ans}" = "y" ]; then
                return 0
            fi
        fi
    fi

    until [ 0 = 1 ]; do
        echo " "
        echo " Enter the name of the PyFerret installation directory (FER_DIR). "
        echo " This should be the directory created from extracting the PyFerret "
        echo " tar.gz file.  It contains subdirectories bin, contrib, examples, "
        echo " ext_func, go, lib, and ppl. "
        echo " A relative path name can be given (such a '.') "
        echo " "
        read -p " FER_DIR --> " fer_dir
        if [ ! -d "${fer_dir}" ]; then
            echo " '${fer_dir}' is not a directory"
        else
#           resolve relative pathnames
            fer_dir=`cd "${fer_dir}" ; pwd`
            if [ ! -d "${fer_dir}/ext_func/pylibs" ]; then
                echo " The PyFerret files are not in "
                echo "     '${fer_dir}' "
            else
                return 0
            fi
        fi
    done
#   should not get here - return error
    return 1
}


### Assign $fer_dsets, the desired FER_DSETS value
get_fer_dsets() {
    if [ -n "${FER_DSETS}" ]; then
        if [ -f "${FER_DSETS}/data/coads_climatology.cdf" ]; then
            fer_dsets="${FER_DSETS}"
            echo " "
            echo " The environment variable FER_DSETS is currently defined as "
            echo " "
            echo "     '${FER_DSETS}' "
            echo " "
            echo " This is the directory containing the default Ferret datasets. "
            echo " It contains subdirectories data, descr, and grids, including "
            echo " the data file data/coads_climatology.cdf "
            echo " "
            read -p " Is that correct and acceptable (y/n) [y] " ans
            if [ -z "${ans}" ] || [ "${ans}" = "Y" ] || [ "${ans}" = "y" ]; then
                return 0
            fi
        fi
    fi

    until [ 0 = 1 ]; do
        echo " "
        echo " Enter the name of the directory containing the default Ferret "
        echo " data sets (FER_DSETS).  It contains subdirectories data, descr, "
        echo " and grids, including the data file data/coads_climatology.cdf "
        echo " A relative path name can be given (such a '../FerretDatasets') "
        echo " "
        read -p " FER_DSETS --> " fer_dsets
        if [ ! -d "${fer_dsets}" ]; then
            echo " '${fer_dsets}' is not a directory"
        else
#           resolve relative pathnames
            fer_dsets=`cd "${fer_dsets}" ; pwd`
            if [ ! -f "${fer_dsets}/data/coads_climatology.cdf" ]; then
                echo " The Ferret default data files are not in "
                echo "     '${fer_dsets}' "
            else
                return 0
            fi
        fi
    done
#   should not get here - return error
    return 1
}


### Assign $ferpaths_dir, the directory to contain the ferret_paths.* files
get_ferpaths_dir() {
    until [ 0 = 1 ]; do
        echo " "
        echo " Enter the name of the directory where you want to place "
        echo " the newly created 'ferret_paths.csh', 'ferret_path.sh', "
        echo " and pyferret scripts."
        echo " A relative path name can be given (such a '.') "
        echo " "
        read -p " desired ferret_paths location --> " ferpaths_dir
        if [ ! -d "${ferpaths_dir}" ]; then
            echo " '${ferpaths_dir}' is not a directory"
        else
#           resolve relative pathnames
            ferpaths_dir=`cd "${ferpaths_dir}" ; pwd`
#           if ferret_paths* exists, check to see if it's OK to replace
            if [ -f "${ferpaths_dir}/ferret_paths.csh" ] || \
               [ -f "${ferpaths_dir}/ferret_paths.sh" ] ||
               [ -f "${ferpaths_dir}/pyferret.csh" ] ||
               [ -f "${ferpaths_dir}/pyferret.sh" ] ; then
                echo " "
                if [ -f "${ferpaths_dir}/ferret_paths.csh" ]; then
                    echo " ${ferpaths_dir}/ferret_paths.csh already exists"
                fi
                if [ -f "${ferpaths_dir}/ferret_paths.sh" ]; then
                    echo " ${ferpaths_dir}/ferret_paths.sh already exists"
                fi
                if [ -f "${ferpaths_dir}/pyferret.csh" ]; then
                    echo " ${ferpaths_dir}/pyferret.csh already exists"
                fi
                if [ -f "${ferpaths_dir}/pyferret.sh" ]; then
                    echo " ${ferpaths_dir}/pyferret.sh already exists"
                fi
                read -p " Rename and create new? (n/y) [n] " ans
                if [ "${ans}" = "Y" ] || [ "${ans}" = "y" ]; then
                    return 0
                fi
                read -p " Select a different directory? (y/n) [y] " ans
                if [ -n "${ans}" ] && [ "${ans}" != "Y" ] && [ "${ans}" != "y" ]; then
                    return 1
                fi
            else
                return 0
            fi
        fi
    done
#   should not get here - return error
    return 1
}


### assign $ferpaths_link, the link destination, if any, for ferret_paths
get_ferpaths_link() {
    echo " "
    echo " To duplicate behavior found in older version of Ferret, you can "
    echo " create a link (shortcut) 'ferret_paths' that refers to either "
    echo " 'ferret_paths.csh' or 'ferret_paths.sh'.  This is simply a "
    echo " convenience for users and should only be done on systems where "
    echo " all Ferret users work under the same shell (such as tcsh or bash). "
    echo " The files 'ferret_path.csh' and 'ferret_paths.sh' can always be "
    echo " used regardless of the answer to this question. "
    until [ 0 = 1 ]; do
        echo " "
        echo " ferret_paths link options: "
        echo "    c - link to ferret_paths.csh (all users work under tcsh, csh) "
        echo "    s - link to ferret_paths.sh (all users work under bash, dash, ksh, sh) "
        echo "    n - do not create the link (use ferret_paths.csh or ferret_paths.sh)"
        read -p " ferret_paths link to create? (c/s/n) [n] --> " ans
        if [ -z "$ans" ] || [ "$ans" = 'n' ] || [ "$ans" = 'N' ]; then
           ferpaths_link=''
           return 0
        elif [ "$ans" = 'c' ] || [ "$ans" = 'C' ]; then
           ferpaths_link='ferret_paths.csh'
           return 0
        elif [ "$ans" = 's' ] || [ "$ans" = 'S' ]; then
           ferpaths_link='ferret_paths.sh'
           return 0
        fi
    done
#   should not get here - return error
    return 1
}


### Get python_executable and python_subdirectory
get_python_vars() {
    echo " "
    echo " Enter the desired python executable to use for running PyFerret. "
    echo " This may simply be 'python', but on systems with multiple versions "
    echo " of python, you need to specify the version to use, such as 'python2.6' "
    echo " or 'python2.7', or the full-path name to desired version of python. "
    until [ 0 = 1 ]; do
        echo " "
        read -p " python executable to use: ['python'] --> " ans
        if [ -z "$ans" ]; then
            ans='python'
        fi
#       expand to the full path name, just to be safe (may not be necessary)
        python_executable=`which "$ans"`
#       assign python_subdirectory as 'pythonx.x' using the version
#       number reported by the python executable (which validates the python executable)
        python_subdirectory=`${ans} -c "from __future__ import print_function; import sys; print('python%i.%i' % sys.version_info[:2])"`
        if echo "${python_subdirectory}" | grep -q '^python2\.[67]$'; then
            return 0
        elif echo "${python_subdirectory}" | grep -q '^python3'; then
            return 0
        elif echo "${python_subdirectory}" | grep -q '^python'; then
            echo " ${ans} appears to be ${python_subdirectory}; only python2.6 or later is supported "
        else
            echo " ${ans} does not appear to be a valid python executable "
        fi
    done
#   should not get here - return error
    return 1
}


### Write a message to ${fer_dir}/bin/Finstall.log (creating it if it does not exist)
write_log_message() {
#   Sanity check
    if [ -z "${fer_dir}" ]; then
        echo " "
        echo " Unexpected script error: fer_dir not defined in write_log_message "
        exit 1
    fi
#   get_fer_dir ensures ${fer_dir}/bin already exists
#   Create Finstall.log file if it does not exist
    logfile="${fer_dir}/bin/Finstall.log"
    if [ ! -f "${logfile}" ]; then
        timestamp=`/bin/date +' %D %T'`
        if ! echo "${timestamp} Created Finstall.log " > "${logfile}" ; then
            return 1
        fi
        echo " "
        echo " Created Finstall.log in ${fer_dir}/bin "
    fi

    timestamp=`/bin/date +' %D %T'`
    if ! echo "${timestamp} $1 " >> "${logfile}" ; then
        return 1
    fi
}


### Edit the ferret_paths_template.{csh,sh} files to create the ferret_paths.{csh,sh} files 
### and edit the pyferret_template file to create the pyferret file.
create_ferret_paths_and_pyferret() {
#   Define the pyferret site relative to ${FER_DIR}
    pyferret_site="\${FER_DIR}/lib/${python_subdirectory}/site-packages"
#   Check for existing ferret_paths.csh
    if [ -f "${ferpaths_dir}/ferret_paths.csh" ]; then
        if mv -f "${ferpaths_dir}/ferret_paths.csh" "${ferpaths_dir}/ferret_paths.csh.old"; then
            write_log_message "Renamed existing ${ferpaths_dir}/ferret_paths.csh"
            write_log_message "              to ${ferpaths_dir}/ferret_paths.csh.old"
            echo " "
            echo " Renamed existing ${ferpaths_dir}/ferret_paths.csh "
            echo "               to ${ferpaths_dir}/ferret_paths.csh.old "
        fi
    fi
#   Create new ferret_paths.csh
    if sed -e "s%##FER_DIR##%${fer_dir}%" \
           -e "s%##FER_DSETS##%${fer_dsets}%" \
           -e "s%##PYTHON_EXECUTABLE##%${python_executable}%" \
           -e "s%##PYFERRET_SITE##%${pyferret_site}%" \
           "${fer_dir}/bin/ferret_paths_template.csh" \
           > "${ferpaths_dir}/ferret_paths.csh" ; then
        write_log_message "Created ${ferpaths_dir}/ferret_paths.csh"
        echo " "
        echo " Created ${ferpaths_dir}/ferret_paths.csh "
    else
        write_log_message "Unable to create ${ferpaths_dir}/ferret_paths.csh"
        echo " "
        echo " Unable to create ${ferpaths_dir}/ferret_paths.csh "
    fi
#   Check for existing ferret_paths.sh
    if [ -f "${ferpaths_dir}/ferret_paths.sh" ]; then
        if mv -f "${ferpaths_dir}/ferret_paths.sh" "${ferpaths_dir}/ferret_paths.sh.old"; then
            write_log_message "Renamed existing ${ferpaths_dir}/ferret_paths.sh"
            write_log_message "              to ${ferpaths_dir}/ferret_paths.sh.old"
            echo " "
            echo " Renamed existing ${ferpaths_dir}/ferret_paths.sh "
            echo "               to ${ferpaths_dir}/ferret_paths.sh.old "
        fi
    fi
#   Create new ferret_paths.sh
    if sed -e "s%##FER_DIR##%${fer_dir}%" \
           -e "s%##FER_DSETS##%${fer_dsets}%" \
           -e "s%##PYTHON_EXECUTABLE##%${python_executable}%" \
           -e "s%##PYFERRET_SITE##%${pyferret_site}%" \
           "${fer_dir}/bin/ferret_paths_template.sh" \
           > "${ferpaths_dir}/ferret_paths.sh" ; then
        write_log_message "Created ${ferpaths_dir}/ferret_paths.sh"
        echo " "
        echo " Created ${ferpaths_dir}/ferret_paths.sh "
    else
        write_log_message "Unable to create ${ferpaths_dir}/ferret_paths.sh"
        echo " "
        echo " Unable to create ${ferpaths_dir}/ferret_paths.sh"
    fi
#   Check for existing ferret_paths
    if [ -f "${ferpaths_dir}/ferret_paths" ]; then
        if mv -f "${ferpaths_dir}/ferret_paths" "${ferpaths_dir}/ferret_paths.old"; then
            write_log_message "Renamed existing ${ferpaths_dir}/ferret_paths"
            write_log_message "              to ${ferpaths_dir}/ferret_paths.old"
            echo " "
            echo " Renamed existing ${ferpaths_dir}/ferret_paths "
            echo "               to ${ferpaths_dir}/ferret_paths.old "
        fi
    fi
#   Link ferret_paths to the appropriate file
    if [ -n "${ferpaths_link}" ]; then
        if ( cd "${ferpaths_dir}" ; ln -s "${ferpaths_link}" "ferret_paths" ) ; then
            write_log_message "Created ${ferpaths_dir}/ferret_paths"
            write_log_message "    as a link to ${ferpaths_link}"
            echo " "
            echo " Created ${ferpaths_dir}/ferret_paths "
            echo "     as a link to ${ferpaths_link} "
        else
            write_log_message "Unable to create ${ferpaths_dir}/ferret_paths"
            echo " "
            echo " Unable to create ${ferpaths_dir}/ferret_paths "
        fi
    fi
#   Check for existing pyferret.csh and move it out of the way
    if [ -f "${fer_dir}/bin/pyferret.csh" ]; then
        if mv -f "${fer_dir}/bin/pyferret.csh" "${fer_dir}/bin/pyferret.csh.old"; then
            write_log_message "Renamed existing ${fer_dir}/bin/pyferret.csh"
            write_log_message "              to ${fer_dir}/bin/pyferret.csh.old"
            echo " "
            echo " Renamed existing ${fer_dir}/bin/pyferret.csh "
            echo "               to ${fer_dir}/bin/pyferret.csh.old "
        fi
    fi
#   Check for existing pyferret.sh and move it out of the way
    if [ -f "${fer_dir}/bin/pyferret.sh" ]; then
        if mv -f "${fer_dir}/bin/pyferret.sh" "${fer_dir}/bin/pyferret.sh.old"; then
            write_log_message "Renamed existing ${fer_dir}/bin/pyferret.sh"
            write_log_message "              to ${fer_dir}/bin/pyferret.sh.old"
            echo " "
            echo " Renamed existing ${fer_dir}/bin/pyferret.sh "
            echo "               to ${fer_dir}/bin/pyferret.sh.old "
        fi
    fi
#   Check for existing pyferret
    if [ -f "${fer_dir}/bin/pyferret" ]; then
        if mv -f "${fer_dir}/bin/pyferret" "${fer_dir}/bin/pyferret.old"; then
            write_log_message "Renamed existing ${fer_dir}/bin/pyferret"
            write_log_message "              to ${fer_dir}/bin/pyferret.old"
            echo " "
            echo " Renamed existing ${fer_dir}/bin/pyferret "
            echo "               to ${fer_dir}/bin/pyferret.old "
        fi
    fi
#   Create new pyferret
    if sed -e "s%##PYTHON_EXECUTABLE##%${python_executable}%" \
           -e "s%##FERRET_PATHS_SH_SCRIPT##%${ferpaths_dir}/ferret_paths.sh%" \
           "${fer_dir}/bin/pyferret_template" \
           > "${fer_dir}/bin/pyferret" ; then
        chmod +x "${fer_dir}/bin/pyferret"
        write_log_message "Created executable script ${fer_dir}/bin/pyferret"
        echo " "
        echo " Created executable script ${fer_dir}/bin/pyferret"
    else
        write_log_message "Unable to create ${fer_dir}/bin/pyferret"
        echo " "
        echo " Unable to create ${fer_dir}/bin/pyferret"
    fi
}



### Main script
echo " "
echo " This script creates the  'ferret_paths.csh' and 'ferret_paths.sh' in a directory "
echo " you choose using values of FER_DIR (Ferret software directory at your site) and "
echo " FER_DSETS (Ferret default data at your site).  Furthermore, the link (shortcut) "
echo " 'ferret_paths' can be created which refers to either 'ferret_paths.csh' or "
echo " 'ferret_paths.sh'.  Finally, the executable shell script 'pyferret' is created. "
echo " "
echo " Sourcing one of these 'ferret_paths' files ('source ferret_paths.csh' for csh or "
echo " tcsh, '. ferret_paths.sh' for bash, sh ksh, or dash) will set up a user's "
echo " environment for running pyferret.  The pyferret script will automatically source "
echo " the ferret_paths script created here if it detects the ferret environment has "
echo " not already been set up. "
echo " "
echo " You will want to run this script if you are installing PyFerret for the first time "
echo " or if you relocated where PyFerret is installed. "
echo " "
read -p " Proceed? (y/n) [y] " ans
if [ -n "${ans}" ] && [ "${ans}" != "Y" ] && [ "${ans}" != "y" ]; then
    echo " "
    exit 1
fi

## Inquire about values and create scripts
echo " "
echo " Customize ferret_paths files..."
if get_fer_dir && get_fer_dsets && get_ferpaths_dir && get_ferpaths_link && get_python_vars; then
    create_ferret_paths_and_pyferret
    echo " "
    
    echo " "
    echo " "
    echo " ---------------------- "
    echo " "
    echo " Optional test of installation:"
    echo " "
    echo "After you exit this Finstall script,"
    echo " "
    echo "1- Source the ferret_paths shell script just created "
    echo "2- Start PyFerret with"
    echo " "
    echo "> pyferret -nodisplay"
    echo " "
    echo "   at the yes? prompt enter   'GO install_test.jnl'"
    echo "The script output names an image file it has generated"
    echo " "
    echo " ---------------------- "
    echo " "

    exit 0
else
    echo " "
    echo " ferret_paths files NOT created "
    echo " "
    exit 1
fi


