#!/bin/bash
##############################################################
#-----------------
function usage() {
cat 1>&2 <<EOF
usage: update-gratia-local [-S <source-prefix>] [-j <jre-home>] [-s]
                           [-p <prefix>] [-d <db-root-pw>]
                           [-i <collector-info-file>]
                           [-c <configure-collector-script>]
                           [-C <config-name>]
                           [--force-log4j]
                           [--install-tomcat]
                           [-h] [-v <vdt_location>] [--] <instance>

       -c <configure-collector-script>

          Execute <configure-collector-script> instead of
          <source-prefix>/common/configuration/configure-collector.

       -C <config-name>

          Name of configuration in .dat file where different to <instance>

       --force-log4j

          Force overwrite of configurable files (like log4j.properties).

       -S <source-prefix>

          Find all sources under <source-prefix>.

       -i <collector-info-file>

          Use collector-info-file instead of the default files
          (collector-pro.dat collector-itb.dat collector-dev.dat)

       --install-tomcat

          Install latest tomcat from ~gratia/tomcat-tarballs.

       -j <jre-home>

          JRE location.

       -s

          Enable SSL.

       -p <prefix>

          Instance path prefix (default $tomcat_root).

       -d <db-root-pw>

          Configure post-install with this DB root password.

       -v <vdt_location>

          Indicates a VDT installation. 

       <instance>

          Name of tomcat directory (sans tomcat- prefix).

EOF
}
#-----------------
function logerr {
    echo "ERROR: $1"
    exit 1
}
#-----------------
function set_env_for_vdt {
  vdtsetup=$vdt_location/setup.sh
  if [ ! -e $vdtsetup ];then
    echo "ERROR: Cannot find VDT setup scrpt ($vdtsetup)" 1>&2
    exit 1
  fi
  source $vdtsetup
  if [ -z $vdt_location ];then
    echo "ERROR: VDT_LOCATION variable not set ($vdt_location)" 1>&2
    exit 1
  fi
  tomcat_root=$vdt_location/tomcat/v55
  java_jre=$JAVA_HOME
  tomcat_top=$tomcat_root
  init_service=tomcat-55
}
#-----------------
function set_env_for_local {
  if [[ -n "$tomcat_root" ]] && [[ -z "$java_jre" ]]; then
    java_jre="${tomcat_root}/jre"
  fi
  tomcat_top=$tomcat_root/tomcat-$instance
  init_service=tomcat-$instance
}
#-----------------
function stop_tomcat {
  echo "... stopping tomcat services"
  if [ $vdt_install ];then
    vdt-control --off tomcat-55;rtn=$?
    if [ "$rtn" != "0" ];then
      logerr "Unable to stop tomcat service"
    fi
  else
    if [ ! -e /etc/init.d/$init_service ];then
      echo "... no tomcat initd service defined"
    else
      shutdown_local_tomcat
    fi
  fi
}
#-----------------
function shutdown_local_tomcat {
    echo "... finding tomcat pid for later verfication that ports are free"
    pid="$(ps axxx |grep $init_service |grep Dcom.sun.management.jmxremote  |egrep -v grep |awk '{print $1}')"
    if [ -z "${pid}" ];then
      echo "... tomcat process does not appear to be running"
      return
    fi
    echo "... tomcat pid: $pid"
    echo "... stopping tomcat service ($init_service)"
    sleep 2
    /sbin/service $init_service stop;rtn=$?
    if [ "$rtn" != "0" ];then
      logerr "Unable to stop tomcat service"
    fi
    verify_shutdown $pid
    echo "... tomcat service ($init_service) successfully stopped"
    sleep 2
}
#-----------------
function verify_shutdown {
    pid="$1"
    echo "... verify ports are free and tomcat fully shutdown for pid ($pid)"
    tries=20
    sleep=5
    while
      [ $tries -gt 1 ]
    do
      connection_cnt="$(/bin/netstat -n --listening --program |egrep ${pid}/java |egrep -v grep |wc -l)"
      if [ $connection_cnt -eq 0 ];then
        break   # all ports free
      fi
      tries=$(($tries -1))
      echo "... found $connection_cnt ports still in use for pid($pid)"
      echo "$(/bin/netstat -n --listening --program |egrep ${pid}/java |egrep -v grep)"
      echo "... sleeping $sleep seconds for them to free.. will try $tries more times"
      sleep $sleep
    done
    if [ $connection_cnt -gt 0 ];then 
      logerr "Server never fully shutdown.. $connection_cnt ports are still in use by pid ($pid).
$(/bin/netstat -n --listening --program |egrep $pid |egrep -v grep)
  "
    fi
}
#-----------------
function maybe_install_tomcat() {
  if (( ${install_tomcat:-0} )); then
    # Install latest tomcat from tomcat-tarballs
    if [[ ! -d "$tomcat_tarballs" ]] || [[ ! -r "$tomcat_tarballs" ]]; then
      echo "ERROR: cannot install tomcat from missing or unreadable directory \"$tomcat_tarballs\""
      exit 1
    fi
    echo "... installing latest version of tomcat from $tomcat_tarballs"
    declare -a latest_version
    for i in $tomcat_tarballs/apache-tomcat-*; do
      version=${i#*/apache-tomcat-}
      version=${version%%.[^0-9]*}
      if (( $(echo $version | cut -d. -f 1) > ${latest_version[0]:-0} )) ||
         (( $(echo $version | cut -d. -f 1) == ${latest_version[0]:-0} &&
            $(echo $version | cut -d. -f 2) > ${latest_version[1]:-0} )) ||
         (( $(echo $version | cut -d. -f 1) == ${latest_version[0]:-0} &&
            $(echo $version | cut -d. -f 2) == ${latest_version[1]:-0} &&
            $(echo $version | cut -d. -f 3) > ${latest_version[2]:-0} )); then
        latest_version=($(echo $version | cut -d. -f 1),$(echo $version | cut -d. -f 2),$(echo $version | cut -d. -f 3))
        latest_tomcat=$i
      fi
    done
    if [[ -z "$latest_tomcat" ]]; then
      echo "ERROR: unable to identify latest tomcat tarball in $tomcat_tarballs"
      exit 1
    fi
    echo "... installing $latest_tomcat to $tomcat_top"
    file_type=$(file "$latest_tomcat")
    if [[ $file_type == *gzip* ]]; then
      compress_arg="z"
    elif [[ $file_type == *bzip2* ]]; then
      compress_arg="j"
    fi
    tar -${compress_arg}xf "$latest_tomcat" --strip=1 -C "$tomcat_top"
    if (( $? != 0 )); then
      echo "ERROR: untar of $latest_tomcat into $tomcat_top failed!"
      exit 1
    fi
  fi
}
#-----------------
function remove_deprecated_webapps_services {
  sleep 3
  removed_services=n
  echo
  echo "... removing obsolete services in $tomcat_webapps:
$deprecated_webapps_services
"
  ( cd "$tomcat_webapps/" ; \
    ls -l ;
    for service in $deprecated_webapps_services
    do
      if [ -d $service ];then
        echo "...... removing:
`ls -ld ${service}*`
"
        rm -rf ${service}*
        if [ "$?" != "0" ];then
          echo "ERROR: failed to remove ${service}*";exit 1
        fi
        removed_services=y
      fi
    done
    if [ "$removed_services" = "n" ];then
      echo "...... no deprecated services found... looks good."
    else 
      echo "...... services remaining:"
      ls -l
    fi
  )
  echo
}

function populate_server_lib {
    cd "$tomcat_top/server/lib"
    if [[ -x "$tomcat_gratia/cleanup_server_lib" ]]; then
      echo "... running cleanup script in $tomcat_top/server/lib:"
      "$tomcat_gratia/cleanup_server_lib"
    fi
    echo "... populating $tomcat_top/server/lib:"
    tar xvf ${target_dir}/server_lib.tar
}

function populate_common_lib {
    cd "$tomcat_top/common/lib"
    if [[ -x "$tomcat_gratia/cleanup_common_lib" ]]; then
      echo "... running cleanup script in $tomcat_top/common/lib:"
      "$tomcat_gratia/cleanup_common_lib"
    fi
    echo "... populating $tomcat_top/common/lib:"
    tar xvf ${target_dir}/common_lib.tar
}

function misc_cleanup {
    cd "$tomcat_top"
    if [[ -x "$tomcat_gratia/cleanup_misc" ]]; then
      echo " running cleanup script in $tomcat_top:"
      "$tomcat_gratia/cleanup_misc"
    fi
}

function populate_common_classes {
    cd "$tomcat_top/common/classes"
    echo "... populating $tomcat_top/common/classes"
    if [[ -z "$forcelog4j" ]] && [[ -f "$tomcat_top/common/classes/log4j.properties" ]]; then
      echo "$tomcat_top/common/classes/log4j.properties exists --"
      echo "Check ${tomcat_top}/gratia/log4j.properties for updates"
    else
      cp -vf "${tomcat_top}/gratia/log4j.properties" .
      if (( $? != 0 )); then
        echo "ERROR: Unable to copy ${tomcat_top}/gratia/log4j.properties in to $tomcat_top/common/classes/ -- pleae check"
        exit 1
      fi
    fi
    tar xvf ${target_dir}/common_classes.tar
}


## MAIN ########################################
# Defaults
source_prefix=~greenc/gratia
tomcat_root=/data
#--- deprecated webapps serrvices ----
deprecated_webapps_services="GratiaServices
gratia-report-configuration
gratia-util
gratia-security
birt
"

# Use getopt(1) -- enhanced to process long options
TEMP=`getopt -o :c:C:i:j:sp:d:v:hS: --long force-log4j --long install-tomcat -n "update-gratia-local" -- "$@"`

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

eval set -- "$TEMP"

#--- get command line args ----
while true; do
    case "$1" in
        -c)
            configure_script="$2"
            shift 2
            ;;
        -C)
            config_name="$2"
            shift 2
            ;;
        --force-log4j)
            forcelog4j=1
            shift
            ;;
        --install-tomcat)
            install_tomcat=1
            shift
            ;;
        -S)
            source_prefix="$2"
            shift 2
            ;;
        -j)
            java_jre="$2"
            shift 2
            ;;
        -i)
            collector_info="--collector-info=$2"
            shift 2
            ;;
        -s)
            use_ssl="-s"
            shift
            ;;
        -p)
            tomcat_root="$2"
            shift 2
            ;;
        -d)
            declare -a dbp_arg=(-d "$2")
            shift 2
            ;;
        -v)
            vdt_install=1
            vdt_location="$2"
            shift 2
            ;;
        -h)
            usage
            exit 1
            ;;
        --)
            shift
            break
            ;;
        *)
            usage
            exit 1
    esac
done


instance=$1

[[ -z "$config_name" ]] && config_name=$instance

#--- set env for either vdt or local install ----
if [ $vdt_install ];then
  set_env_for_vdt
  source $vdt_location/setup.sh
else
  set_env_for_local
fi

configuration_dir=$source_prefix/common/configuration
       target_dir=$source_prefix/target
   tomcat_work=$tomcat_top/work/Catalina/localhost
   tomcat_webapps=$tomcat_top/webapps
    tomcat_gratia=$tomcat_top/gratia
  tomcat_tarballs=~gratia/tomcat-tarballs

for dir in $source_prefix \
           $configuration_dir \
           $tomcat_root \
           $target_dir
do
  echo "... checking $dir"
  if [ ! -d $dir ]; then
    echo "ERROR: Unable to find specified directory ($dir)" 1>&2
    exit 1
  fi
done

if (( ! ${install_tomcat:-0} )) && [ ! -d "$tomcat_webapps" ]; then
  echo "ERROR: Unable to find specified directory $tomcat_webapps and --install-tomcat not specified." 1>&2
  exit 1
fi

#-----------------------
# Check for java
#-----------------------
##echo "... checking for java"
##if [ "$(type java >/dev/null 2>&1;echo $?)" ];then
##  if [ ! -x $java_jre/bin/java ];then
##    echo;echo "ERROR: Cannot find java ($java_jre/bin/java)";echo
##    exit 1
##  fi
##fi
#-----------------------
# Check for mysql
#-----------------------
##echo "... checking for mysql"
##if [ "$(type mysql >/dev/null 2>&1;echo $?)" != "0" ];then
##  echo;echo "ERROR: Cannot find mysql client on this node";echo
##  exit 1
##fi


#-----------------------
# Stop tomcat
#-----------------------
stop_tomcat

#-----------------------
# Install new tomcat if requested
#-----------------------
maybe_install_tomcat

#-----------------------
# Update gratia directory
#-----------------------
echo
echo
echo "... updating $tomcat_gratia"
mkdir -p $tomcat_gratia
# retrieve the latest pre-tar cleanup script
# the cd /var/tmp; is to avoid the error message 
#    tar: ./cleanup_misc: Cannot open: File exists
# which is seemingly due to the fact that the file must first be extracted in
# the local directory (and/or the loca file is in the way).
(cd /var/tmp; tar xf $target_dir/gratia.tar ./cleanup_misc -C $tomcat_gratia )
# Run it to clean up some miscellaneous files that could cause trouble
misc_cleanup
# Untar the whole thing now.
tar xf $target_dir/gratia.tar -C $tomcat_gratia
# ls check.
ls -l $tomcat_gratia

#----------------------------
# Remove deprecated services
#----------------------------
remove_deprecated_webapps_services

#-----------------------
# Updated war files
#-----------------------
echo "... loading war files in $tomcat_webapps"
for warfile in $(cd $target_dir;ls *.war)
do
  echo "...... $warfile"
  wardir=$(echo $warfile | cut -d'.' -f1)
  rm -rf ${tomcat_webapps}/${wardir} ${tomcat_webapps}/${warfile}
  # Insure the jsp class are always recreated ..
  appname=${warfile%\.*}
  if [ "x${appname}" != "x" ] ; then 
    rm -rf ${tomcat_work}/${appname}
  fi
  if [ ! $vdt_install ];then
    cp -pv ${target_dir}/${warfile}  ${tomcat_webapps}/.
    continue
  fi
  mkdir  ${tomcat_webapps}/${wardir}
  cp -pv ${target_dir}/${warfile}  ${tomcat_webapps}/${wardir}/.
  cd ${tomcat_webapps}/${wardir}
  jar xf $warfile
  rm -f  $warfile
  cd -
done

#-----------------------
# Configure gratia dir
#-----------------------
if [ $vdt_install ];then
#--- vdt ---
  #-- need to remove some things from the post-install --
  post_install=$tomcat_gratia/post-install
  cp -p ${post_install} ${post_install}.orig
  cat ${post_install}.orig | awk '{ sub("CMD_PREAMBLE","");sub("CMD_PREFIX","");sub("CMD_SUFFIX","");print $0 }' >${post_install}

  #-- create a special tarball to replace the VDT one used by the VDT configure
  cd $tomcat_root 
  vdt_tar=${vdt_location}/gratia/lib/gratia-services-webbase.tar.gz
  if [ ! -e ${vdt_tar}.original ];then
    cp ${vdt_tar} ${vdt_tar}.original 
  fi
  tar zcf ${vdt_tar} gratia/service-configuration.properties gratia/service-authorization.properties gratia/post-install
  cd -  

  #-- run the VDT configure scripts --
  for arg in --reporting --services
  do
    echo "... running VDT configure_gratia $arg"
    ${vdt_location}/vdt/setup/configure_gratia $arg
    rtn=$?
    if [ "$rtn" != "0" ];then
      echo "ERROR: configure_gratia $arg script FAILED";exit 1
    fi
  done
  #--- remove any services VDT may have re-installed ---
  remove_deprecated_webapps_services
  echo "... loading war files AGAIN in $tomcat_webapps"
  for warfile in $(cd $target_dir;ls *.war)
  do
    echo "...... $warfile"
    wardir=$(echo $warfile | cut -d'.' -f1)
    rm -rf ${tomcat_webapps}/${wardir} ${tomcat_webapps}/${warfile}
    mkdir  ${tomcat_webapps}/${wardir}
    cp -pv ${target_dir}/${warfile}  ${tomcat_webapps}/${wardir}/.
    cd ${tomcat_webapps}/${wardir}
    jar xf $warfile
    rm -f  $warfile
    cd -
  done

  # May not always need to do this ...
  populate_server_lib
  populate_common_lib
  populate_common_classes

  #-- reset some permissions --
  echo "... fixing ownership:"
  chown -R daemon $tomcat_webapps
#--- local ---
else

  #-----------------------
  # Put required libs in server/lib
  #-----------------------
  populate_server_lib

  #-----------------------
  # Put required libs in common/lib
  #-----------------------
  populate_common_lib

  #-----------------------
  # Put required files in common/classes
  #-----------------------
  populate_common_classes

  #-----------------------
  # Run configure script
  #-----------------------  
  [[ -n "$configure_script" ]] || configure_script="$configuration_dir/configure-collector"
  declare -a args=($use_ssl -p "$tomcat_root" -j "$java_jre")
  [[ -n "${dbp_arg[@]}" ]] && declare -a args=("${args[@]}" "${dbp_arg[@]}")
  declare -a args=("${args[@]}" ${collector_info} ${config_name})
  echo "... running $configure_script ${args[@]}"
  "$configure_script" "${args[@]}"
  status=$?
  if (( $status != 0 )); then
    echo "ERROR: configure-collector invocation returned non-zero exit code $status." 1>&2
    exit $status
  fi 
fi 
ls -l ${tomcat_webapps}

# service tomcat-$instance start

echo "... ALL DONE.  Have fun!!!"
exit 0
