#!/bin/bash

#####
# Installation Script Fetcher
# For the ESGF Node application stack
#        (author: gavin@llnl.gov)
#####

#uses: wget
devel=${devel:-0}
install_prefix=${prefix:-"/usr/local"}
script_maj_version="2.6"
script_sub_version="0"
esg_dist_url=http://distrib-coffee.ipsl.jussieu.fr/pub/esgf/dist$( ((devel == 1)) && echo "/devel" || echo "")/$script_maj_version/$script_sub_version

id_check() {
    id | grep root >& /dev/null
    [ $? != 0 ] && printf "[FAIL] \n\tMust run this program with root's effective UID\n\n" && return 1
    return 0
}

get_latest() {
    esg_dist_url=http://distrib-coffee.ipsl.jussieu.fr/pub/esgf/dist$( ((devel == 1)) && echo "/devel" || echo "")/$script_maj_version/$script_sub_version
    script_install_dir=${install_prefix}/bin
    mkdir -p ${script_install_dir}
    #NOTE: boot script location is a RedHat/CentOS thing... to make this cross distro compatible clean this up.
    local init_scripts_dir=/etc/rc.d/init.d
    pushd $script_install_dir >& /dev/null
    #Get files
    local fetch_file=esg-node

    local ret
    verbose_print "Checking...."
    checked_get ${esg_dist_url}/esgf-installer/${fetch_file}
    ret=$?
    ((ret == 1)) && echo "ESGF Node install script (${fetch_file}) already up-to-date"
    ((ret == 0)) && echo "Updated ESGF Node install script ($fetch_file) from ESGF distribution site"
    (( ret > 1 )) && popd >& /dev/null && return 1
    chmod 755 ${fetch_file}
    [ -e ${init_scripts_dir}/${fetch_file} ] && cp -v ${fetch_file} ${init_scripts_dir}/${fetch_file}

    checked_get ${esg_dist_url}/esgf-installer/esg-functions
    ((ret == 1)) && echo "esg-functions script (esg-functions) already up-to-date"
    ((ret == 0)) && echo "Updated esg-functions script (esg-functions) from ESGF distribution site"
    (( ret > 1 )) && popd >& /dev/null && return 1
    chmod 755 esg-functions

    checked_get ${esg_dist_url}/esgf-installer/esg-init
    ((ret == 1)) && echo "esg-init script (esg-init) already up-to-date"
    ((ret == 0)) && echo "Updated esg-init script (esg-init) from ESGF distribution site"
    (( ret > 1 )) && popd >& /dev/null && return 1
    chmod 755 esg-init

	checked_get ${esg_dist_url}/esgf-installer/esg-bootstrap
    ((ret == 1)) && echo "ESGF Node bootstrap script (esg-bootstrap) already up-to-date"
    ((ret == 0)) && echo "Updated ESGF Node bootstrap script (esg-bootstrap) from ESGF distribution site"
    (( ret > 1 )) && popd >& /dev/null && return 1
    chmod 755 esg-bootstrap

	checked_get ${esg_dist_url}/esgf-installer/setup-autoinstall
    ((ret == 1)) && echo "ESGF Node Auto-install script (esg-bootstrap) already up-to-date"
    ((ret == 0)) && echo "Updated Auto-install script (setup-autoinstall) from ESGF distribution site"
    (( ret > 1 )) && popd >& /dev/null && return 1
    chmod 755 setup-autoinstall

	checked_get ${esg_dist_url}/esgf-installer/esg-purge.sh
    ((ret == 1)) && echo "ESGF Node Purge script (esg-purge.sh) already up-to-date"
    ((ret == 0)) && echo "Updated ESGF Node Purge script (esg-purge.sh) from ESGF distribution site"
    (( ret > 1 )) && popd >& /dev/null && return 1
    chmod 755 esg-purge.sh

	checked_get ${esg_dist_url}/esgf-installer/jar_security_scan
    ((ret == 1)) && echo "jar_security_scan script already up-to-date"
    ((ret == 0)) && echo "Updated jar_security_scan script from ESGF distribution site"
    (( ret > 1 )) && popd >& /dev/null && return 1
    chmod 755 jar_security_scan

    checked_get ${esg_dist_url}/esgf-installer/esg-autoinstall
      ((ret == 1)) && echo "esg-autoinstall script already up-to-date"
      ((ret == 0)) && echo "Updated esg-autoinstall script from ESGF distribution site"
      (( ret > 1 )) && popd >& /dev/null && return 1
      chmod 755 esg-autoinstall

      checked_get esg-autoinstall.conf ${esg_dist_url}/esgf-installer/esg-autoinstall.template
        ((ret == 1)) && echo "esg-autoinstall.conf script already up-to-date"
        ((ret == 0)) && echo "Updated esg-autoinstall.conf script from ESGF distribution site"
        (( ret > 1 )) && popd >& /dev/null && return 1
        chmod 755 esg-autoinstall.conf

        # Move esg-autoinstall to /usr/local/etc and change permissions
        mkdir -p /usr/local/etc
        mv esg-autoinstall.conf /usr/local/etc/esg-autoinstall.conf
        chown root /usr/local/etc/esg-autoinstall.conf
        chmod 600 /usr/local/etc/esg-autoinstall.conf

        yum install -y expect

    popd >& /dev/null
}

############################################
# Utility Functions
############################################
check_for_update() {
    local local_file
    local remote_file
    if (( $# == 1 )); then
        remote_file=${1}
        local_file=$(readlink -f ${1##*/})
    elif (( $# == 2 )); then
        local_file=${1}
        remote_file=${2}
    else
        echo "function \"checked_get\":  Called with incorrect number of args! (fatal)"
        exit 1
    fi

    [ ! -e ${local_file} ] && echo " WARNING: Could not find local file ${local_file}" && return 0
    [ ! -x ${local_file} ] && echo " WARNING: local file ${local_file} not executible" && chmod 755 ${local_file}
    diff <(md5sum ${local_file} | tr -s " " | cut -d " " -f 1) <(curl -s ${remote_file}.md5 | tr -s " " | cut -d " " -f 1) >& /dev/null
    (( $? != 0 )) && echo " Update Available @ ${remote_file}" && return 0
    return 1
}

checked_get() {
    check_for_update $@
    [ $? != 0 ] && return 1

    local local_file
    local remote_file
    if (( $# == 1 )); then
        remote_file=${1}
        local_file=${1##*/}
    elif (( $# == 2 )); then
        local_file=${1}
        remote_file=${2}
    else
        echo "function \"checked_get\":  Called with incorrect number of args! (fatal)"
        exit 1
    fi

    if [ -e ${local_file} ]; then
	cp -v ${local_file} ${local_file}.bak
	chmod 600 ${local_file}.bak
    fi
    wget -O ${local_file} ${remote_file}
    [ $? != 0 ] && echo " ERROR: Problem pulling down [${remote_file##*/}] from esg distribution site" && return 2
    diff <(md5sum ${local_file} | tr -s " " | cut -d " " -f 1) <(curl -s ${remote_file}.md5 | tr -s " " | cut -d " " -f 1) >& /dev/null
    [ $? != 0 ] && echo " WARNING: Could not verify this file!" && return 3
    verbose_print "[VERIFIED]"
    return 0
}

self_verify() {
    md5sum /dev/null >& /dev/null
    [ $? != 0 ] && echo "Could not find program \"md5sum\". Please find program and put it in your path and try again, Sorry :-(" && exit 1
    #echo "diff <(md5sum ${0} | tr -s " " | cut -d " " -f 1) <(curl ${esg_dist_url}/esgf-installer/${0##*/}.md5 | tr -s " " | cut -d " " -f 1) >& /dev/null "
    diff <(md5sum ${0} | tr -s " " | cut -d " " -f 1) <(curl -s ${esg_dist_url}/esgf-installer/${0##*/}.md5 | tr -s " " | cut -d " " -f 1) >& /dev/null
    [ $? != 0 ] && return 3
    verbose_print "[VERIFIED]"
    return 0
}

############################################
verbose_print() { ((VERBOSE)) && echo $@; return 0; }
debug_print() { ((DEBUG)) && echo $@; return 0; }

usage() {
    printf "
    usage:
        esg-bootstrap [--help]
    \n"
    exit 1
}

############################################
# Main
############################################

VERBOSE=0
DEBUG=0

while [ -n "$1" ]; do
    case $1 in
	-v | --version)
	    echo "Earth Systems Grid Federation (http://esgf.llnl.gov)"
	    echo "ESGF Node Bootstrap Script"
	    echo ""
	    exit 0
            ;;
        --verbose)
            VERBOSE=1;
            ;;
        --debug)
            DEBUG=1;
            ;;
        --devel)
            devel=1;
            ;;
        *)
            echo "unknown switch [$1]"
            exit 1
            ;;
    esac
    shift
done

if id_check
then
    (( devel == 1 )) && echo "(Setup to pull from DEVELOPMENT tree...)" && esg_dist_url=http://distrib-coffee.ipsl.jussieu.fr/pub/esgf/dist$( ((devel == 1)) && echo "/devel" || echo "")/$script_maj_version/$script_sub_version/
    self_verify
    (( $? > 0 )) && printf "WARNING: $0 could not be verified!! \n(This file, $(readlink -f ${0}), may have been tampered with or there is a newer version posted at the distribution server.\nPlease re-fetch this script.)\n\n" && exit 1
    echo "checking for updates for the ESGF Node"
    if (($# == 1)) && [ "$1" = "--help" ]; then
	usage
    else
    	get_latest
       [ $? != 0 ]  && exit 1
    fi
fi
exit 0