#!/bin/bash

#####
# FERRET & LAS for ESGF
# This script is intended to be an adjunct to the esg-node script
#****************************************************************************
#*                                                                          *
#*   Copyright (c) 2009, Lawrence Livermore National Security, LLC.         *
#*   Produced at the Lawrence Livermore National Laboratory                 *
#*   Written by: Gavin M. Bell (gavin@llnl.gov)                             *
#*   LLNL-CODE-420962                                                       *
#*                                                                          *
#*   All rights reserved. This file is part of the:                         *
#*   Earth System Grid (ESG) Data Node Software Stack, Version 1.0          *
#*                                                                          *
#*   For details, see http://esg-repo.llnl.gov/esg-node/                    *
#*   Please also read this link                                             *
#*    http://esg-repo.llnl.gov/LICENSE                                      *
#*                                                                          *
#*   * Redistribution and use in source and binary forms, with or           *
#*   without modification, are permitted provided that the following        *
#*   conditions are met:                                                    *
#*                                                                          *
#*   * Redistributions of source code must retain the above copyright       *
#*   notice, this list of conditions and the disclaimer below.              *
#*                                                                          *
#*   * Redistributions in binary form must reproduce the above copyright    *
#*   notice, this list of conditions and the disclaimer (as noted below)    *
#*   in the documentation and/or other materials provided with the          *
#*   distribution.                                                          *
#*                                                                          *
#*   Neither the name of the LLNS/LLNL nor the names of its contributors    *
#*   may be used to endorse or promote products derived from this           *
#*   software without specific prior written permission.                    *
#*                                                                          *
#*   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS    *
#*   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT      *
#*   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS      *
#*   FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE    *
#*   LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR     *
#*   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,           *
#*   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT       *
#*   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF       *
#*   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND    *
#*   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,     *
#*   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT     *
#*   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF     *
#*   SUCH DAMAGE.                                                           *
#*                                                                          *
#****************************************************************************
######

#####
# description: Installer for the ESG Product server applications
#	(authors: gavin@llnl.gov & roland.schweitzer@noaa.gov)
#####

#uses: perl, awk, ifconfig, tar, wget, curl, su, useradd, id, chmod,
#      chown, chgrp, cut, svn, mkdir, killall, java


DEBUG=${DEBUG:-0}
force_install=${force_install:-0}
compress_extensions=${compression_extensions:-".tar.gz|.tar.bz2|.tgz|.bz2|.tar"}
word_size=${globus_word_size:-$(file /bin/bash | perl -ple 's/^.*ELF\s*(32|64)-bit.*$/$1/g')}
workdir=${workdir:-/usr/local/src/esgf/workbench/esg}
envfile=${envfile:-"/etc/esg.env"}
install_logfile=${install_logfile:-"/etc/esg.install_log"}

esg_root_dir=${esg_root_dir:-"/esg"}
content_dir=${content_dir:-${esg_root_dir}/content}
tomcat_user=${tomcat_user:-"tomcat"}
tomcat_group=${tomcat_group:-"tomcat"}
ferret_envfile=${ferret_envfile:-${envfile}}

ferret_version=${ferret_version:-"6.8"}
las_version=${las_version:-"8.6.4"}
#There seems to be two different variables keeping track of the LAS version; this makes no sense smh.
VERSION=8.6.4

esg_install_prefix=${esg_install_prefix:-"/usr/local"}
INSTALLPATH=${esg_install_prefix}/las-esgf/$VERSION
las_server_dir=${content_dir}/las #why did you decide to make it there and not /esg/content/las/[conf/server] ??

esg_functions_file=${esg_install_prefix}/bin/esg-functions
esg_init_file=${esg_install_prefix}/bin/esg-init
esg_installarg_file=${esg_install_prefix}/bin/esg-installarg
esg_node_file=${esg_install_prefix}/bin/esg-node

# Sourcing esg-installarg esg-functions file and esg-init file
[ -e ${esg_functions_file} ] && source ${esg_functions_file} && ((VERBOSE)) && printf "sourcing from: ${esg_functions_file} \n"
[ -e ${esg_init_file} ] && source ${esg_init_file} && ((VERBOSE)) && printf "sourcing from: ${esg_init_file} \n"
[ -e ${esg_installarg_file} ] && source ${esg_installarg_file} && ((VERBOSE)) && printf "sourcing from: ${esg_installarg_file} \n"

# get esgf_host
esgf_host=${esgf_host}
[ -z "${esgf_host}" ] && get_property esgf_host

# Determining if devel or master directory of the ESGF distribution mirror will be usde for download of installation files
[ -z "$(grep 'script_version=' ${esg_node_file} | sed -n 's/-devel/\0/p')" ] && devel=0 || devel=1

# Determining ESGF distribution mirror
get_esgf_dist_mirror "fastest" $devel


# Setting esg_dist_url with previously gathered information
esg_dist_url_root=${esgf_dist_mirror}/dist
esg_dist_url=${esg_dist_url_root}$( ((devel == 1)) && echo "/devel" || echo "")

thredds_config_file_template_url=${esg_dist_url}/thredds/threddsConfig.xml.tmpl
las_config_file_template_url=${esg_dist_url}/esgf-product-server/las_tds.xml.tmpl
las_config_input_file_url=${esg_dist_url}/esgf-product-server/esg-las-config
esgcet_las_config_file="esgcet_las.xml"
esgcet_las_sisters_file="las_servers.xml"
esgcet_las_static_sisters_file="las_servers_static.xml"


setup_product_server() {

    #TODO: Present the user with the choices and select the package of
    #choice.  (hint) Do the same bit switch trick since order is
    #important... well, at least that LAS is installed first!

    echo "Starting Product Services installation (Ferret/LAS)..."

    get_property las_xml_config_dir ${las_server_dir}/conf/server

    write_as_property las_xml_config_dir

    init_ferret && setup_ferret && init_las && setup_las

    rm -f $INSTALLPATH/$0
    cp $0 $INSTALLPATH
}


#----
# Ferret
#----

setup_ferret() {

    # Reinstall ferret if LAS does not exist
    echo -n "Checking for LAS Product Server v${las_version}"
    check_webapp_version "las" ${las_version}
    local ret=$?
    ((ret == 0)) && (( ! force_install )) && echo " [OK]" && return 0

    echo
    echo "*******************************"
    echo "Setting up Ferret..."
    echo "*******************************"
    echo

    local upgrade=${1:-0}

    get_ferret
    setup_support_files
    setup_data_files
    set_ferret_environment
    pushd ${ferret_install_dir}/bin >& /dev/null
    ## Install the executable files by running Finstall.

echo This is the install dir: ${ferret_install_dir}
echo This is the exec dir: ${ferret_workdir}
./Finstall<<FER_END
1

${ferret_install_dir}

${ferret_workdir}

3
FER_END
    write_ferret_env && write_ferret_install_log && echo "Ferret Installed :-)"
    popd >& /dev/null
    return 0
}


#----
# LAS
#----

setup_las() {

    echo -n "Checking for LAS Product Server v${las_version}"
    check_webapp_version "las" ${las_version}
    local ret=$?
    ((ret == 0)) && (( ! force_install )) && echo " [OK]" && return 0

    echo
    echo "*******************************"
    echo "Setting up LAS Product Server..."
    echo "*******************************"
    echo

    local upgrade=${1:-0}

    local default="Y"
    ((force_install)) && default="N"
    local dosetup
    if [ -d ${tomcat_install_dir}/webapps/las ]; then
	echo "Detected an existing LAS installation..."
        read -p "Do you want to continue with LAS installation and setup? $([ "$default" = "N" ] && echo "[y/N]" || echo "[Y/n]") " dosetup
        [ -z "${dosetup}" ] && dosetup=${default}
	if [ "${dosetup}" != "Y" ] && [ "${dosetup}" != "y" ]; then
	    echo "Skipping LAS installation and setup - will assume it's setup properly"
	    return 0
	fi

	local dobackup="N"
	read -p "Do you want to make a back up of the existing distribution?? [y/N] " dobackup
	if [ "${dobackup}" = "Y" ] || [ "${dobackup}" = "y" ]; then
	    echo "Creating a backup archive of this application ${tomcat_install_dir}/webapps/las"
	    backup ${tomcat_install_dir}/webapps/las
	fi

	echo
    fi

    local ret=0
    get_las && echo "get_las [OK]" || (echo "get_las [FAIL]" && return 1)
    install_las && echo "install_las [OK]" || (echo "install_las [FAIL]" && return 1)
    integrate_into_tds && echo "integrate_into_tds [OK]" || (echo "integrate_into_tds [FAIL]" && return 1)
    write_esgcet_las_config_file
    write_las_install_log && echo "write_las_install_log [OK]" || (echo "write_las_install_log [FAIL]" && return 1)
    chown -R ${tomcat_user}:${tomcat_group} ${content_dir} && echo "chown [OK]" || (echo "chown [FAIL]" && return 1)
    return 0
}

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



########
# FERRET
########

init_ferret() {

    ferret_workdir=${workdir}/ferret/${las_version}
    mkdir -p ${ferret_workdir}

    ferret_install_dir=${FERRET_HOME:-/usr/local/ferret}
    ferret_data_dir=${FERRET_HOME:-/usr/local/ferret_data}

    #NOTE: see http://ferret.pmel.noaa.gov/static/Downloads/shared_libraries.html
    #      see http://ferret.pmel.noaa.gov/static/Downloads/ferret_downloads.html

    #******************************
    #ZOIKS - VERY OPERATING SYSTEM DEPENDENT!!!!!! (works for RH and CentOS)
    #******************************
    local redhat_ver=$(uname -a | sed -n 's/^Linux\(.*\)\.el\([^ ]\)\(.*\)/\2/p')
    if ((word_size == 32)); then
        if ((redhat_ver == 5)); then
            ferret_exec_url=${esg_dist_url}/ferret/rhel5_32/fer_executables.tar.gz
            ferret_env_url=${esg_dist_url}/ferret/rhel5_32/fer_environment.tar.gz
        elif ((redhat_ver == 6)); then
            ferret_exec_url=${esg_dist_url}/ferret/rhel6_32/fer_executables.tar.gz
            ferret_env_url=${esg_dist_url}/ferret/rhel6_32/fer_environment.tar.gz
        else
            echo "WARNING: Unsupported Operating System or Operating System version [${redhat_ver}]."
            echo "  Attempting to use the Redhat 6 binaries, but success is not guaranteed..."
            ferret_exec_url=${esg_dist_url}/ferret/rhel6_32/fer_executables.tar.gz
            ferret_env_url=${esg_dist_url}/ferret/rhel6_32/fer_environment.tar.gz
        fi
    elif ((word_size == 64)); then
        if ((redhat_ver == 5)); then
            ferret_exec_url=${esg_dist_url}/ferret/rhel5_64/fer_executables.tar.gz
            ferret_env_url=${esg_dist_url}/ferret/rhel5_64/fer_environment.tar.gz
        elif ((redhat_ver == 6)); then
            ferret_exec_url=${esg_dist_url}/ferret/rhel6_64/fer_executables.tar.gz
            ferret_env_url=${esg_dist_url}/ferret/rhel6_64/fer_environment.tar.gz
        else
            echo "WARNING: Unsupported Operating System or Operating System version [${redhat_ver}]."
            echo "  Attempting to use the Redhat 6 binaries, but success is not guaranteed..."
            ferret_exec_url=${esg_dist_url}/ferret/rhel6_64/fer_executables.tar.gz
            ferret_env_url=${esg_dist_url}/ferret/rhel6_64/fer_environment.tar.gz
        fi
    else
        echo "invalid word size: ${word_size}"
        checked_done 1
    fi

    # Ferret data files
    ferret_data_url=${esg_dist_url}/ferret/data/fer_dsets.tar.gz
    ferret_exec_file=${ferret_workdir}/fer_executables.tar.gz
    ferret_env_file=${ferret_workdir}/fer_environment.tar.gz
    ferret_data_file=${ferret_workdir}/fer_dsets.tar.gz
    return 0
}

get_ferret() {
    echo "Setting up Ferret..."
    pushd ${ferret_workdir} >& /dev/null
    ((DEBUG)) && echo "(pwd = $(pwd))"
    #Download:
    #fer_executables.tar.gz
    if [ ! -e ${ferret_exec_file} ] || ((force_install)); then
        [ ! -e ${ferret_exec_file} ] && echo "Don't see Ferret executables file ${ferret_exec_file}"
	echo "Downloading Ferret from ${ferret_exec_url} to ${ferret_exec_file}"

	wget -O ${ferret_exec_file} ${ferret_exec_url}
	[ $? != 0 ] && echo " ERROR: Could not download Ferret:${ferret_exec_file}" && popd && checked_done 1
    fi
    #fer_environment.tar.gz
    if [ ! -e ${ferret_env_file} ] || ((force_install)); then
	[ ! -e ${ferret_env_file} ] && echo "Don't see Ferret environment file ${ferret_env_file}"
	echo "Downloading Ferret from ${ferret_env_url}"

	wget -O ${ferret_env_file} ${ferret_env_url}
	[ $? != 0 ] && echo " ERROR: Could not download Ferret:${ferret_env_file}" && popd && checked_done 1
    fi
    #fer_dsets.tar.gz
    if [ ! -e ${ferret_data_file} ] || ((force_install)) ; then
	[ ! -e ${ferret_data_file} ] && echo "Don't see Ferret data file ${ferret_data_file}"
	echo "Downloading Ferret from ${ferret_data_url}"

	wget -O ${ferret_data_file} ${ferret_data_url}
	[ $? != 0 ] && echo " ERROR: Could not download Ferret:${ferret_data_file}" && popd && checked_done 1
    fi
    popd > /dev/null
    return 0
}

setup_support_files() {
    echo "Setting up Ferret support files..."
    mkdir -p ${ferret_install_dir}
    pushd ${ferret_install_dir} > /dev/null

    tar -zxf ${ferret_env_file}

    popd > /dev/null
    return 0
}

setup_data_files() {
    echo "Setting up Ferret data files..."
    mkdir -p ${ferret_data_dir}
    pushd ${ferret_data_dir} > /dev/null

    tar -zxf ${ferret_data_file}

    popd > /dev/null
    return 0
}

set_ferret_environment() {
    echo "Setting up Ferret environment variables..."

    # You may want to customize the pathname of the `ferret' directory:
    export FER_DIR=${ferret_install_dir}

    # This directory will contain FERRET demonstration data files (30+ Mbytes)
    export FER_DSETS=${ferret_data_dir}

    export PATH="$PATH:$FER_DIR/bin"

    export FER_EXTERNAL_FUNCTIONS="$FER_DIR/ext_func/libs"

    export FER_GO=". $FER_DIR/go $FER_DIR/examples $FER_DIR/contrib"

    export FER_DATA=". $FER_DSETS/data $FER_DIR/go $FER_DIR/examples $FER_DIR/contrib /data/ncep"
    export FER_DESCR=". $FER_DSETS/descr"
    export FER_GRIDS=". $FER_DSETS/grids"

    export TMAP="$FER_DIR/fmt"
    export PLOTFONTS="$FER_DIR/ppl/fonts"
    export FER_FONTS="$FER_DIR/ppl/fonts"
    export SPECTRA="$FER_DIR/ppl"	  # for old ferret versions
    export FER_PALETTE=". $FER_DIR/ppl"	      # palette search list

}

write_ferret_env() {
    ((show_summary_latch++))

    #actual environment variables
    echo "export FERRET_HOME=${ferret_install_dir}" >> ${envfile}
    echo "export FER_DIR=${ferret_install_dir}" >> ${envfile}
    echo "export FER_DSETS=${ferret_data_dir}" >> ${envfile}
    echo "export PATH=$PATH:$FER_DIR/bin" >> ${envfile}
    dedup ${envfile} && source ${envfile}

    #faux ferret environment varabables - requires space delimeter >:-(
    echo "export FER_EXTERNAL_FUNCTIONS='$FER_DIR/ext_func/libs'" >> ${ferret_envfile}
    echo "export FER_GO='. $FER_DIR/go $FER_DIR/examples $FER_DIR/contrib'" >> ${ferret_envfile}
    echo "export FER_DATA='. $FER_DSETS/data $FER_DIR/go $FER_DIR/examples $FER_DIR/contrib /data/ncep'" >> ${ferret_envfile}
    echo "export FER_DESCR='. $FER_DSETS/descr'" >> ${ferret_envfile}
    echo "export FER_GRIDS='. $FER_DSETS/grids'" >> ${ferret_envfile}
    echo "export TMAP='$FER_DIR/fmt'" >> ${ferret_envfile}
    echo "export PLOTFONTS='$FER_DIR/ppl/fonts'" >> ${ferret_envfile}
    echo "export FER_FONTS='$FER_DIR/ppl/fonts'" >> ${ferret_envfile}
    echo "export SPECTRA='$FER_DIR/ppl'" >> ${ferret_envfile}
    echo "export FER_PALETTE='. $FER_DIR/ppl'" >> ${ferret_envfile}
    dedup ${ferret_envfile} && source ${ferret_envfile}
    return 0
}

write_ferret_install_log() {
    echo "$(date ${date_format}) ferret=${ferret_version} ${ferret_install_dir}" >> ${install_logfile}
    dedup ${install_logfile}
    return 0
}

########
# L A S
########
init_las() {
    echo "init_las..."
    las_tar_url=${esg_dist_url}/las/las-esgf-v${las_version}.tar.gz
    las_dist_file=${las_tar_url##*/}
    las_dir=${INSTALLPATH}/$(echo ${las_dist_file} | awk 'gsub(/('$compress_extensions')/,"")')
    echo "las_tar_url = ${las_tar_url}"
    echo "las_dist_file = ${las_dist_file}"
    echo "las_dir = $las_dir"

    return 0
}

get_las() {
    echo "Getting LAS..."
    pushd ${ferret_workdir} >& /dev/null
    #Download:
    if [ ! -e ${las_dist_file} ] || ((force_install)) ; then
	echo "Don't see LAS tar file ${las_dist_file}"
	echo "Downloading LAS from ${las_dist_file} -to-> $(pwd)/${las_dist_file}"

	echo "wget -O '${las_dist_file}' '${las_tar_url}'"
	wget -O "${las_dist_file}" "${las_tar_url}"
	[ $? != 0 ] && echo " ERROR: Could not download LAS:${las_dist_file}" && popd >& /dev/null && checked_done 1
    fi
    popd >& /dev/null
    return 0
}

install_las() {
    echo "Installing Live Access Server (LAS)... using local product server file"

    #Obliterate what is currently there (it would be prudent for them to have selected to do a backup)
    if [ -d ${tomcat_install_dir}/webapps/las ]; then
        stop_tomcat
        echo -n "removing current LAS installation ${tomcat_install_dir}/webapps/las "
        rm -rf ${tomcat_install_dir}/webapps/las && echo "[OK]" || (echo "[FAILED]" && checked_done 1)
    fi

    #Remove the link, which at this point will be pointing out into nothing...
    if [ -e ${tomcat_install_dir}/content/las ] && [ -h ${tomcat_install_dir}/content/las ]; then
        echo -n "removing sym link in tomcat: ${tomcat_install_dir}/content/las "
        unlink ${tomcat_install_dir}/content/las && echo "[OK]" || (echo "[FAILED]" && checked_done 1)
    fi

    #Now we can proceed with an install

    echo "creating installation directory"
    mkdir -p $INSTALLPATH

    echo "untarring las distribution file..."
    echo "tar -zxf ${ferret_workdir}/${las_dist_file} -C ${INSTALLPATH}"
    tar -zxf ${ferret_workdir}/${las_dist_file} -C ${INSTALLPATH}

    pushd ${las_dir} >& /dev/null
    #NOTE: this bit of editing based on line numbers is brittle, maybe there is a more robust way?
    wget -O ${ferret_workdir}/${las_config_input_file_url##*/} ${esg_dist_url}/esgf-product-server/esg-las-config
    sed -i '8  s/^.*$/'${esgf_host}'/' ${ferret_workdir}/${las_config_input_file_url##*/}
    sed -i '12 s/^.*$/'${esgf_host}'/' ${ferret_workdir}/${las_config_input_file_url##*/}
    echo "$(pwd)/configure < ${ferret_workdir}/${las_config_input_file_url##*/}"
    ./configure < ${ferret_workdir}/${las_config_input_file_url##*/}
    popd >& /dev/null
    chown -R ${tomcat_user}:${tomcat_group} ${tomcat_install_dir}/webapps/las
    write_las_install_log && return ${ret}
    return 0
}

write_las_install_log() {
    echo "$(date ${date_format}) webapp:las=${las_version} ${tomcat_install_dir}/webapps/las" >> ${install_logfile}
    write_as_property las_service_endpoint "http://${esgf_host}/las"
    write_as_property las_service_app_home "${tomcat_install_dir}/webapps/las"
    dedup ${install_logfile}
    return 0
}

clean_las_webapp_subsystem() {
    init
    local doit="N"
    if [ -e ${las_service_app_home} ]; then
        read -p "remove ESGF LAS web service? (${las_service_app_home}) [y/N]: " doit
        if [ "doit" = "Y" ] || [ "$doit" = "y" ]; then
            echo "removing ${las_service_app_home}"
            if [ -n ${las_service_app_home} ]; then
                rm -rf ${las_service_app_home}
                [ $? != 0 ] && echo "ERROR: Unable to remove ${las_service_app_home}" && return 1
                perl -n -i -e'print unless m!webapp:las!' ${install_manifest}
            fi
        fi
    fi
    if [ ! -e ${las_service_app_home} ]; then
        debug_print "removing orp associated properties..."
        remove_property las_service_app_home
        remove_property las_service_endpoint
        remove_property las_xml_config_dir
    fi

    return 0
}


#######
#
#  To finish the LAS installation you need to complete the steps described here:
#     http://ferret.pmel.noaa.gov/LAS/documentation/installer-documentation/installation/installing-and-integrating-tds-with-las/
#
#######
integrate_into_tds() {
    echo "Integrating Product Server into Thredds..."

    stop_tomcat


    #-------------------
    #Fetch templated thredds config file and edit it by token replacement
    #-------------------

    pushd ${content_dir}/thredds/ >& /dev/null

    local thredds_config_file_template=${thredds_config_file_template_url##*/}
    local thredds_config_file=${thredds_config_file_template%.*}


    [ -e ${thredds_config_file} ] && echo "Backing up current thredds config file..." && mv -v ${thredds_config_file} ${thredds_config_file}.bak
    wget -O ${thredds_config_file_template} ${thredds_config_file_template_url}
    cp -vf ${thredds_config_file_template} ${thredds_config_file}

    #The file with the insertion text (text to be inserted)
    wget -O ${thredds_config_file}.las ${esg_dist_url}/esgf-product-server/${thredds_config_file}.las

    local esgf_las_entry_pattern="<!--@@esgf_las_entry@@-->"

    insert_file_at_pattern $(readlink -f ${thredds_config_file}) ${thredds_config_file}.las "${esgf_las_entry_pattern}"

    local start_comment='<!--'
    local end_comment='-->'
    eval "perl -p -i -e 's/<!--\\@\\@esg_start_comment\\@\\@-->/${start_comment}/g' ${thredds_config_file}"; echo -n "*"
    eval "perl -p -i -e 's/<!--\\@\\@esg_end_comment\\@\\@-->/${end_comment}/g' ${thredds_config_file}"; echo -n "*"
    echo

    #-------------------
    # Fetch templated las_tds.xml file (las_tds.xml.tmpl) and edit it by token replacement
    #-------------------
    local las_config_file_template=${las_config_file_template_url##*/}
    local las_config_file=${las_config_file_template%.*}

    [ -e ${las_config_file} ] && echo "backing up current las config file..." && mv -v ${las_config_file} ${las_config_file}.bak
    wget -O ${las_config_file_template} ${las_config_file_template_url}
    cp -v ${las_config_file_template} ${las_config_file}

    eval "perl -p -i -e 's#\\@\\@las_server_dir\\@\\@#${las_server_dir}#g' ${las_config_file}"; echo -n "*"
    echo

    mkdir -p ${las_server_dir}
    [ $? != 0 ] && echo "ERROR: Not able to create LAS server directory ${las_server_dir}" && popd >& /dev/null

    if [ -e ${tomcat_install_dir}/content/las ] && [ ! -h ${tomcat_install_dir}/content/las ]; then
        echo "transfering content from ${tomcat_install_dir}/content/las to ${las_server_dir}"
        (cd ${tomcat_install_dir}/content/las; tar cvzf - *) | tar xvzf - -C ${las_server_dir}/
        echo "removing ${tomcat_install_dir}/content/las"
        rm -rf ${tomcat_install_dir}/content/las
        echo "sym-linking... src:${las_server_dir} -> alias ${tomcat_install_dir}/content/las"
        ln -s ${las_server_dir} ${tomcat_install_dir}/content/las
    elif [ -h ${tomcat_install_dir}/content/las ]; then
        echo -n "${tomcat_install_dir}/content/las is a symlink... to $(readlink -f ${tomcat_install_dir}/content/las) "
        [ $(readlink -f ${tomcat_install_dir}/content/las) = ${las_server_dir} ] && echo "[OK]" || (echo "[FAIL]" && popd >& /dev/null/ && return 1)
    else
        echo
        echo "ERROR: Could not locate las' server directory ${tomcat_install_dir}/content/las/conf/server"
        echo "       This directory should have been created as part of the ferret/las installation"
        echo "       Check that the installation was performed successfully"
        echo
        popd >& /dev/null
        return 1
    fi

    popd >& /dev/null
    [ ! -e "${las_xml_config_dir}/${esgcet_las_static_sisters_file}" ] && touch ${las_xml_config_dir}/${esgcet_las_static_sisters_file}
    start_tomcat
    local ret=$?
    return $((ret > 1))
}

#For Details See...
#http://esg-pcmdi.llnl.gov/internal/productserver/product-server-node-integration
write_esgcet_las_config_file() {
    pushd ${las_xml_config_dir} >& /dev/null
    [ -e "${esgcet_las_config_file}" ] && mv -v ${esgcet_las_config_file} ${esgcet_las_config_file}.bak
    echo -n "writing las config file $(readlink -f ${esgcet_las_config_file}) "
    cat >> ${esgcet_las_config_file} <<EOF
<datasets>
  <dataset name="ESGF Data" src_type="THREDDS" src="http://${esgf_host}/thredds/esgcet/catalog.xml">
    <properties>
      <property_group type="addXML">
        <property>
          <name>esg</name>
          <value>true</value>
        </property>
      </property_group>
    </properties>
  </dataset>
</datasets>
EOF
  local ret=$?
  [ $ret == 0 ] &&  echo "[OK]" || echo "[FAIL]"
  popd >& /dev/null
  return $ret
}

########
# CDAT
########

setup_cdat() {
    echo "Setting up CDAT (stubbed... no-op)"
    return 0
}

setup_product_server