#!/bin/bash
# Copyright 2012 The Foundry
#
# chkconfig: 345 99 06
# description: Foundry License Server

#NOTE : The Foundry Server Utility uses these 2 elements to locate the server daemon, 
#and the floating license files in use if you alter these ensure they still point to 
#the FLT RLM bin tools dir and the license directory in use
TOOL_DIR=/usr/local/foundry/LicensingTools7.0
FnLicDir=/usr/local/foundry/RLM

FnGetFloatingLicenseFiles()
{
  fileList=""
  dirList=$(echo $1 | tr ":" "\n")
  for dirItem in ${dirList}
  do
    for file in ${dirItem}/*
    do
      #Locate only license files containing floating licenses to serve
      isvLine=`grep "ISV foundry" $file | sed 's/^ *//g'`
      if [ "${isvLine:0:1}" = "#" ]
      then
        #Commented out, skip it
        isvLine=""
      fi
      if [ "$isvLine" != "" ]
      then
        if [ "$fileList" != "" ]
        then
          fileList=$fileList":"
        fi
        fileList=$fileList$file
      fi
    done
  done
  if [ "$fileList" == "" ]
  then
    echo $1
  else
    echo $fileList
  fi
  return 0
}

#The Foundry Web Server is on port 4102

BIN_DIR=${TOOL_DIR}/bin/RLM
LIC_FILES=`FnGetFloatingLicenseFiles ${FnLicDir}`
LOG_DIR=${FnLicDir}/log
DEF_ULIMIT=`ulimit -n`
FOUNDRY_ULIMIT=28000

case "$1" in
'start')
  foundryRLMWSRunning=`ps ax | grep -v grep | grep rlm.foundry | grep '\-ws'`
  if [ "${foundryRLMWSRunning}" != "" ]
  then
    $0 reload
  else
    #Not running the web service yet, start it
    if [ ${DEF_ULIMIT} -lt ${FOUNDRY_ULIMIT} ]
    then
      echo -e "\033[33mDefault descriptor limit ${DEF_ULIMIT} insufficient, increasing to ${FOUNDRY_ULIMIT}\033[0m"
      ulimit -n ${FOUNDRY_ULIMIT}
      TEST_ULIMIT=`ulimit -n`
      if [ ${TEST_ULIMIT} -eq ${FOUNDRY_ULIMIT} ]
      then
        echo -e "\033[32mSuccessfully increased descriptor limit to ${TEST_ULIMIT} \033[0m"
      else
        echo -e "\033[31mFailed to increase descriptor limit, currently set to ${TEST_ULIMIT} \033[0m"
      fi
    fi
    echo -e "\033[32mStarting RLM Server\033[0m"
    ${BIN_DIR}/rlm.foundry -ws 4102 -c ${LIC_FILES} -dlog ${LOG_DIR}/foundry.log & >> ${LOG_DIR}/boot.log 2>&1
    ${BIN_DIR}/rlmutil rlmstat -i foundry 2>&1 >> ${LOG_DIR}/foundry.log
  fi
  ;;

'stop')
  echo -e "\033[32mStopping RLM Server\033[0m"
  ${BIN_DIR}/rlmutil rlmdown foundry -c ${LIC_FILES} -q & >> ${LOG_DIR}/boot.log 2>&1 
  #No, if we do this it'll kill the web server and then they can't restart the server using that. Let's try and play nice - RMCE
  #killall -s SIGTERM rlm.foundry 
  ;;

'reload')
  echo -e "\033[32mReloading RLM licenses\033[0m"
  #Don't give the vendor name as the foundy one may be down, it'll get it from the files given
  #${BIN_DIR}/rlmutil rlmreread foundry -c ${LIC_FILES} 2>&1 >> ${LOG_DIR}/foundry.log
  ${BIN_DIR}/rlmutil rlmreread -c ${LIC_FILES} 2>&1 >> ${LOG_DIR}/foundry.log
  ;;

'restart')
  $0 stop
  $0 start
  ;;

*)
   echo "usage: $0 {start|stop|reload|restart}"
   ;;
esac
