#!/bin/bash

FLEX_DIR=/usr/local/foundry/FLEXlm
TOOL_DIR=/usr/local/foundry/FLEXlmTools5.0
LIC_DIR=${FLEX_DIR}
BIN_DIR=${TOOL_DIR}/bin
DOC_DIR=${TOOL_DIR}/docs
LOG_DIR=${FLEX_DIR}/log
INIT_DIR=/etc/init.d

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

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 FLEXlm Tools 5.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 lmgrd.foundry` ]
    then
      echo "Stopping the server"
      /etc/init.d/foundryflexlmserver stop
  fi
  # Remove foundryflexlmserver 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
  rm -f ${TOOL_DIR}/bin/lmgrd.foundry
  rm -f ${TOOL_DIR}/bin/lmutil
  rm -f ${TOOL_DIR}/bin/uninstall.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
  if [ `ls ${DOC_DIR}` ]
  then
    echo
    echo "${DOC_DIR} is not empty so not removing"
  else
    rm -rf ${DOC_DIR}
  fi

  rm -f ${TOOL_DIR}/FoundryLicenseInstaller
  rm -f ${TOOL_DIR}/FoundryServerUtility

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

