#!/bin/bash

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


umask 022

FnLicDir=/usr/local/foundry/RLM

#NOTE : The Foundry Server Utility uses this element to locate the server daemon, 
#if you alter this ensure it still points to the FLT tools dir 
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

#Surely we should stop it if we are about to replace it?
if [ -f ${INIT_DIR}/foundryrlmserver ]
then
  echo "There appears to be an installation of The Foundry Licensing Tools"
  echo "on this machine. Please uninstall it before continuing by"
  echo "running /usr/local/foundry/LicensingTools6.0/bin/uninstall.sh"
  exit 1
fi

echo "Installing The Foundry Licensing Tools 6.0"
echo ${BIN_DIR}
if [ ! -d ${BIN_DIR} ]
then
  mkdir -p ${BIN_DIR}
fi

if [ ! -d ${DOC_DIR} ]
then
  mkdir -p ${DOC_DIR}
fi

if [ ! -d ${LIC_DIR} ]
then
  mkdir -p ${LIC_DIR}
fi

if [ ! -d ${LOG_DIR} ]
then
  mkdir -p ${LOG_DIR}
fi

#cp ./FoundryServerUtility ./FoundryLicenseInstaller ${TOOL_DIR}
#chown root:root ${TOOL_DIR}/*
#chmod 755 ${TOOL_DIR}/*

cp foundry.set ./bin/install ./bin/activation ./bin/ca-bundle.crt ./bin/libssl.so.4 ./bin/libcrypto.so.4 ./bin/systemid ./rlm.foundry ./rlmutil ${BIN_DIR}
chown root:root ${BIN_DIR}/*
chmod 755 ${BIN_DIR}/*

cp ./uninstall.sh ./activation.sh ${TOOL_DIR}
chown root:root ${TOOL_DIR}/*
chmod 755 ${TOOL_DIR}/*

cp ./foundry.log ${LOG_DIR}
chown root:root ${LOG_DIR}
chmod -R 666 ${LOG_DIR}

chmod -R 777 ${LIC_DIR}

cp ./foundryrlmserver ${INIT_DIR}
chown root:root ${INIT_DIR}/foundryrlmserver
chmod 755 ${INIT_DIR}/foundryrlmserver

cp -R ./docs/* ${DOC_DIR}
chown root:root ${DOC_DIR}/*
chmod 666 ${DOC_DIR}/*

# Should probably use lsb_release here but older dists may not have it
if [ -f /etc/redhat-release ]
  then
    echo "Setting foundry license server to run at startup"
    /sbin/chkconfig --level 345 foundryrlmserver on
    echo "Starting Foundry RLM Server"
    /etc/init.d/foundryrlmserver start
elif [ -f /etc/debian_version ]
  then
    echo "Setting foundry license server to run at startup"
    /usr/sbin/update-rc.d foundryrlmserver defaults 
    echo "Starting Foundry RLM Server"
    /etc/init.d/foundryrlmserver start
elif [ -f /etc/SuSE-release ]
  then
    echo "Setting foundry license server to run at startup"
    /sbin/chkconfig --level 345 foundryrlmserver on
    echo "Starting Foundry RLM Server"
    /etc/init.d/foundryrlmserver start
else
  echo "I don't know how to set rlm.foundry to run at startup.  Please
  consult your OS documentation."
fi

echo "Done."


