#!/bin/bash
########################################################################
# install-release
#
# Low-fuss wrapper around gratia-upgrade.sh, which is a wrapper around
# upgrade-gratia-local.sh, which is a wrapper around
# configure-collector. Sheesh.
########################################################################

####################################
# Useful variables
username=${USER:-${LOGNAME:-$(whoami)}}
install_access_type=remote
TMP=`mktemp ${TMPDIR:-/tmp}/install-release.XXXXXXXXXX`

# Trap for cleanup
trap "[[ -n "\$TMP" ]] && rm -f \"$TMP*\" 2>/dev/null" EXIT

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

########################################################################
# Functions

####################################
# usage
function usage() {
cat 1>&2 <<EOF
${0##*/} [<opt>] -R <release>
${0##*/} [<opt>] -B <official-build>
${0##*/} [<opt>] -L <full-release-path>
${0##*/} [<opt>] <release> (deprecated)
${0##*/} [-h]

Build-specifying options:
   -R <release>
      Official release (found as ~gratia/gratia-releases/gratia-<release>).
   -B <official-build>
      Official build (found as ~gratia/gratia-builds/gratia-<official-build>).
   -L <full-release-path>
      Local build (found as <full-release-path>).

Help:
   -h
      This help.

Options:
   -a
      Auto-start collector (default no start).

   -C <config-dat>
      Specify explicitly the config file from which to take the instance
      configuration.
      
   -c <config>
      Instance name is tomcat-<config> (except see -p).

   -t
      Install latest tomcat from ~gratia/tomcat-tarballs.

   -m <notify-mail>[,...]
      Comma-separated list of email addresses for notification of release.

   -p
      Production: shorthand for "-m gratia-operation@fnal.gov." Also
      triggers an extra check for a specified configuration name.

   -v
      Verbose: mention a little more about what we're doing.

   --configure-script <configure-script>
      Use a different configure-collector script than the one in the release.

   --force-local
      Force local install even if local host name and remote host name don't
      match (ignored if user is not root).

   --upgrade-script <upgrade-script>
      Use a different gratia-upgrade.sh script than the one in the release.

Default config name is current user name ($username), unless -p is
specified (in which case there is no default and -c is required).

Examples

   Install and start a development collector tomcat-greenc as root on
   the machine in question:

      install-release -a -c greenc -L ~greenc/gratia-test

   Install and start a development collector tomcat-greenc remotely
   (assuming user is greenc):

      install-release -a -L ~greenc/gratia-test

   Install an integration collector with the latest build (manual
   start):

      install-release -c itb_gratia_itb -B latest

NOTES

   Any specified instance (either explicitly with -c or implicitly as
   <user>) must correspond to a configuration cluse in a collector-*.dat
   file. See gratia/common/configuration/collector*.dat for examples.

EOF
}
####################################

####################################
# get_config
#
# Get config or property item.
function get_config() {
  OPTIND=1  
  while getopts :pv OPT; do
    case $OPT in
      v)
         local verbose=1
         ;;
      p)
         local config_opt=obtain-properties-item
         ;;
      *)
         return 1;
    esac
  done
  shift $[ OPTIND - 1 ]
  local item=$1
  if (( ${verbose:-0} )); then
    echo "Executing ${get_config_cmd[@]} --${config_opt:-obtain-config-item} $item $config_name"
  fi
  "${get_config_cmd[@]}" --${config_opt:-obtain-config-item} $item $config_name \
   >"$TMP.out" \
   2>"$TMP.err" && cat "$TMP.out" | sed -ne 's/\(config\|property\): '"$item"' = //p'
  if (( $? != 0 )); then
    echo "ERROR executing ${get_config_cmd[@]} --${config_opt:-obtain-config-item} $item $config_name: " 1>&2
    cat "$TMP.out" 1>&2
    cat "$TMP.err" 1>&2
    return 1
  fi
}

####################################
# install_collector
#
# Actually perform the install.
function install_collector() {
  local status
  if [[ "${1:-remote}" == "local" ]]; then
    printf "INFO: performing LOCAL install of collector $instance_name ($config_name) with $type ${release:-build} from $release_dir ... "
    if (( ${autostart:-0} )); then
      "${install_command[@]}" >/dev/null 2>&1
      status=$?
    else
      yes n | "${install_command[@]}" >/dev/null 2>&1
      status=$?
    fi
  else
    echo "INFO: checking root login privilege to install host $remote_host for user $username"
    ssh root@$remote_host echo >/dev/null 2>&1
    status=$?
    if (( ${status:-1} != 0 )); then
      if [[ "$username" == root ]] && [[ "$KRB5CCNAME_OLD" ]] && [[ "$KRB5CCNAME" != "$KRB5CCNAME_OLD" ]]; then
        # install-group saved the existing credentials location prior to
        # getting host credentials -- restore and try again.
        echo "WARNING: unable to login as root to $remote_host with current credentials ... " 1>&2
        echo "         resetting KRB5CCNAME and trying again" 1>&2
        KRB5CCNAME=$KRB5CCNAME_OLD
        install_collector "$@"
        return $?
      else
        echo "ERROR: User $username unable to login as root to $remote_host for install!" 1>&2
        exit 2
      fi
    fi
    printf "INFO: performing REMOTE install of collector $instance_name ($config_name) on host $remote_host with $type ${release:-build} from $release_dir ... "
    if (( ${autostart:-0} )); then
      ssh root@$remote_host "${install_command[@]}" >/dev/null 2>&1
      status=$?
    else
      ssh root@$remote_host "yes n | ${install_command[@]}" >/dev/null 2>&1
      status=$?
    fi
  fi 
  if (( ${status:-1} == 0 )); then
    echo "OK"
    if [[ "$username" == "root" ]]; then
      if (( ${autostart:-0} )); then
        echo "INFO: locally installed collector $instance_name ($config_name) is now running."
      else
        echo "INFO: locally installed collector must be started -- use:"
        echo "      service $instance_name start"
      fi
    else
      if (( ${autostart:-0} )); then
        echo "INFO: collector $instance_name ($config_name) is now running on $remote_host"
      else
        echo "INFO: collector $instance_name ($config_name) on $remote_host must be started -- use:"
        echo "      ssh root@$remote_host service $instance_name start"
      fi
    fi
  else
    echo "FAILED!"
  fi
  return $status
}
####################################

########################################################################
# Main body.

####################################
# Options
OPTIND=1
TEMP=`getopt -o :B:C:L:R:ac:h\?m:ptv --long configure-script: --long force-local --long help --long mail: --long upgrade-script: -n "install-release" -- "$@"`

if [ $? != 0 ]; then
  echo "ERROR :terminating due to option parse errors" 1>&2
  exit 1
fi

eval set -- "$TEMP"

while true; do
    case $1 in
        -B)
            type=build
            relarg=$2
            shift 2
            ;;
        -C)
            config_dat=$2
            shift 2
            ;;
        -L)
            type=local
            relarg=$2
            shift 2
            ;;
        -R)
            type=release
            relarg=$2
            shift 2
            ;;
        -a)
            autostart=1
            shift
            ;; 
        -c)
            config_name=$2
            shift 2
            ;;
        --help|-h|-\?)
            usage
            exit 1
            ;;
        --mail|-m)
            mail=$2
            shift 2
            ;;
        -p)
            production=1
            shift
            ;;
        -t)
            tomcat_arg=--install-tomcat
            shift
            ;;
        -v)
            verbose=1
            shift
            ;;
        --configure-script)
            configure_script="$2"
            shift 2
            ;;
        --force-local)
            force_local=1
            shift
            ;;
        --upgrade-script)
            upgrade_script="$2"
            shift 2
            ;;
        --)
            shift
            break
            ;;
        *)
            echo "ERROR: unknown argument \"$1\"" 1>&2
            usage
            exit 2
    esac
done

if [[ -z "type" ]]; then
  if [[ -n "$1" ]]; then
    echo "INFO: not specified -R, -L or -B options. Defaulting to official release $1"
    type=release
    relarg="$1"
  else
    echo "ERROR: required options -R, -L or -B not specified."
    usage
    exit 1
  fi
fi

####################################
# Setup
if [[ "$type" == "local" ]]; then
  release_dir="$relarg"
else
  tnstub="${type}s"
  release="$relarg"
  release_dir="/home/gratia/gratia-$tnstub/gratia-${release}"
fi

if [[ "$username" == "root" ]]; then
  printf "INFO: running as root. You should specify config-name."
  [[ -n "$mail" ]] && \
    printf " Mail will be sent to grid-accounting or gratia-operation as appropriate."
  printf "\n"
else
  echo "INFO: running as $username. Collector host will be obtained from config for login and install as root."
  [[ -z "$mail" ]] && mail="${username}@fnal.gov"
fi

# Check for release integrity:
if ! { [[ -d "$release_dir" ]] && [[ -r "$release_dir" ]]; };  then
  echo "ERROR: Specified release directory $release_dir does not exist or is not readable" 1>&2
  exit 2
fi

upgrade_script=${upgrade_script:-${release_dir}/build-scripts/gratia-upgrade.sh}
configure_script=${configure_script:-${release_dir}/common/configuration/configure-collector}

# configure command
  declare -a get_config_cmd=("$configure_script")
if [[ -n "$config_dat" ]]; then
  declare -a get_config_cmd=("${get_config_cmd[@]}" \
"-c" "$config_dat"
)
  declare -a config_dat_args=("--config" "$config_dat")
fi

# First, check for configuration (especially DB location).
install_prefix=`get_config install_prefix`
(( $? == 0 )) || exit 1

if (( ${production:-0} )); then
  if [[ -z "$config_name" ]]; then
    echo "ERROR: onfiguration name required for production installs" 1>&2
    usage
    exit 1
  fi
  [[ -z "$mail" ]] && mail="grid-accounting@fnal.gov"
else
  [[ -n "$config_name" ]] || config_name=$username
  [[ -z "$mail" ]] && mail="gratia-operation@fnal.gov"
fi
instance_name=$(get_config instance_name)
(( $? == 0 )) || exit 1

instance_name="tomcat-${instance_name:-$config_name}"
remote_host=`get_config remote_host`
local_host=`hostname -f`

(( $? == 0 )) || exit 1

db_host=`get_config db_host`
(( $? == 0 )) || exit 1

if [[ "$db_host" == "localhost" ]]; then
  db_host=$remote_host
fi

pswd_file=~gratia/.mysql-${db_host%%.*}

if [[ -z "$install_prefix" ]]; then
  echo "WARNING: configuration for instance $config_name does not specify install prefix: defaulting to /data" 1>&2
fi

echo "INFO: If DB password file $pswd_file does not exist or is not readable, configure script will look in $install_prefix/.mysql-${db_host%%.*} on $remote_host"

if (( ${autostart:-0} )); then
  mail_opt=daily
else
  mail_opt=mail
fi

declare -a install_command=("$upgrade_script" \
                            --configure-script ${configure_script} \
                            --instance $instance_name \
                            "${config_dat_args[@]}" \
                            --config-name $config_name \
                            --source "$release_dir" )

if [[ -f "$pswd_file" ]]; then
  declare -a install_command=("${install_command[@]}" --mysql "$pswd_file")
fi

declare -a install_command=("${install_command[@]}" \
                            --$mail_opt "$mail" \
                            ${tomcat_arg} \
                            --force-log4j)

# Now do different things if we're root
if [[ "$username" == "root" ]]; then
  if (( ${force_local:-0} )) || [[ "$local_host" == "$remote_host" ]]; then
    install_access_type=local
  else
    echo "INFO: Local user is root but local and remote host names do not match."
    echo "INFO: use --force-local to force a local install on this node."
  fi
fi

install_collector ${install_access_type}
install_status=$?

echo "INFO: upgrade log may be found in $remote_host:$install_prefix/$instance_name-upgrade.log/"

exit $install_status
