#!/bin/bash

FnLicDir=/usr/local/foundry/RLM
TOOL_DIR=/usr/local/foundry/LicensingTools6.0
LIC_DIR=${FnLicDir}
BIN_DIR=${TOOL_DIR}/bin
DOC_DIR=${TOOL_DIR}/docs
LOG_DIR=${FnLicDir}/log
INIT_DIR=/etc/init.d

remove_startup()
{
  echo "Foundry RLM Server stopping."
  /etc/init.d/foundryrlmserver stop

# Should probably use lsb_release here but older dists may not have it
  if [ -f /etc/redhat-release ]
  then
    /sbin/chkconfig --del foundryrlmserver
  elif [ -f /etc/debian_version ]
  then
    /usr/sbin/update-rc.d -f foundryrlmserver remove 
  elif [ -f /etc/SuSE-release ]
  then
    /sbin/chkconfig --del foundryrlmserver
  else
    echo "I don't know how to stop foundry license server running at startup.  Please"
    echo "consult your OS docs.  I have removed the startup script"
  fi
  rm -f /etc/init.d/foundryrlmserver
}

if [ `id -u` -ne 0 ]
then
  echo "You must run this script as root."
  exit 1
fi

# TODO: Preserve licenses?  Where?
echo
echo
echo "Uninstalling The Foundry Licensing Tools 6.0"
echo
echo "*** WARNING ***"
echo "This script will stop The Foundry license server and remove it from this machine"
echo "This script will preserve your licenses and log files."
echo "As a result not all directories will be removed."
echo
echo -n "Do you really want to continue <yes/no> "
read REPLY
if [ "$REPLY" = "yes" ]
then
  echo
  # Stop the server
  if [ `/usr/bin/pgrep rlm.foundry` ]
    then
      echo "Stopping the server"
      /etc/init.d/foundryrlmserver stop
  fi
  # Remove foundryrlmserver from the startup list
  echo
  echo "Removing startup scripts"
  remove_startup

  # Remove the rest of everything
  echo
  echo "Removing installed files"
  rm -f ${TOOL_DIR}/bin/foundry.set
  rm -f ${TOOL_DIR}/bin/install
  rm -f ${TOOL_DIR}/bin/systemid
  rm -f ${TOOL_DIR}/bin/activation
  rm -f ${TOOL_DIR}/bin/ca-bundle.crt
  rm -f ${TOOL_DIR}/bin/libssl.so.4 
  rm -f ${TOOL_DIR}/bin/libcrypto.so.4 
  rm -f ${TOOL_DIR}/bin/foundry.set
  rm -f ${TOOL_DIR}/bin/rlm.foundry
  rm -f ${TOOL_DIR}/bin/rlmutil
  rm -f ${TOOL_DIR}/uninstall.sh
  rm -f ${TOOL_DIR}/activation.sh
  if [ `ls ${TOOL_DIR}/bin` ]
  then
    echo
    echo "${TOOL_DIR}/bin is not empty so not removing"
  else
    echo
    echo "Removing ${TOOL_DIR}/bin"
    rm -rf ${TOOL_DIR}/bin
  fi

  # TODO: I need a name for the pdf, maybe it should be sed'd in scons build
  rm -f ${DOC_DIR}/*.pdf
  rm -f ${DOC_DIR}/RLM_Enduser.html
  rm -rf ${DOC_DIR}/rlm_enduser_images 
  if [ `ls ${DOC_DIR}` ]
  then
    echo
    echo "${DOC_DIR} is not empty so not removing"
  else
    rm -rf ${DOC_DIR}
  fi

  # Report back what's left
  echo
  echo "The following files and directories remain."
  echo
  /usr/bin/find ${FnLicDir}
  /usr/bin/find ${TOOL_DIR}
else
  exit
fi

