#!/bin/sh
# 
# Note: In Solaris start/stop scripts are always executed by /bin/sh!
#
# start/stop script for manserver
#
# Defined return codes:
#
#   0 - everything okay
#   1 - usage message printed and exit
#
#
# Fill all parts of the script marked with '???' with your code
#
#
# History: 
#   17.01.2006 /bs initial release
#
# Author
#   Bernd.Schemmer@gmx.de
#

# ---------------------------------------
# check the user executing this script
#

# ---------------------------------------

  THIS_USER="www-data"
  THIS_USER="root"
#  if [ "`whoami`"x != "${THIS_USER}"x ] ; then
#    su - "${THIS_USER}" -c "cd ` pwd` ; $0 $*"
#    exit $?
#  fi

# ---------------------------------------
#
# save the parameter
#
  ACTION="$1"
  [ $# -ne 0 ] && shift
  ACTION_PARAMETER="$*"

# ---------------------------------------
#
# predefined variables
#

# return code of the script
  main_RC=0

  __TRUE=0
  __FALSE=1

  __EXIT_VIA_DIE=${__FALSE}

#
# set __VERBOSE to __TRUE for debugging (use LogInfo for debugging messages)
#
  __VERBOSE=${__FALSE}

  __THISSCRIPT=` basename $0` 

#
# change the name of the logfile to your need; use __LOGFILE=""
#    to suppress using a logfile at all
#
#  __LOGFILE="/var/tmp/${__THISSCRIPT}.log"
  __LOGFILE=""
  
  __HOSTNAME=` uname -n `

  __OS=` uname -s `

# __OS_VERSION - Operating system version (e.g 5.8)
#
  __OS_VERSION=` uname -r `

  __RUNLEVEL=`who -r | tr -s " " | cut -f8 -d " " `

#
# set __USER_BREAK_ALLOWED to __FALSE to suppress user aborts with CTRL-C
#
  __USER_BREAK_ALLOWED=${__TRUE}

# set to the name of the application to start/stop with this script
#
  __APPLICATION="manserver"

# ---------------------------------------
#
# define variables here
#
# Note: Do not use leading underscores (__) for variable names -
#      these names are reserved for internal variables
#

# ---------------------------------------
#
# sub routines
#

# ---------------------------------------
#
# Usage: automatically called in the sub routine die
#
cleanup() {

  LogInfo "Doing house keeping ..."

## ??? add code for house keeping here

  if [ "${ACTION}"x = "start"x ] ; then
:
  fi

  if [ "${ACTION}"x = "status"x ] ; then
:
  fi

  if [ "${ACTION}"x = "stop"x ] ; then
:
  fi

}

# ---------------------------------------
# 
# Usage: LogMsg [message]
#
LogMsg() {
  LogMsg_THISMSG="$*"
  echo "${__THISSCRIPT} - ${LogMsg_THISMSG}"
  [ "${__LOGFILE}"x != ""x ] && echo "${__THISSCRIPT} - ${LogMsg_THISMSG}" >>"${__LOGFILE}"
}

# ---------------------------------------
# 
# Usage: LogInfo [message]
#
# Note: LogInfo only prints messages if __VERBOSE is true
#
LogInfo() {
  [ ${__VERBOSE} -eq ${__TRUE} ] && LogMsg "INFO: $*"
}

# ---------------------------------------
#
# Usage: LogWarning [message]
#
LogWarning() {
  LogWarning_THISMSG="${__THISSCRIPT} - ERROR: $*!"
  echo "${LogWarning_THISMSG}" >&2
  [ "${__LOGFILE}"x != ""x ] && echo "${LogWarning_THISMSG}" >>${__LOGFILE}
}


# ---------------------------------------
#
# Usage: LogError [message]
#
# Note: Error messages are written to STDERR
#
LogError() {
  LogError_THISMSG="${__THISSCRIPT} - ERROR: $*!"
  echo "${LogError_THISMSG}" >&2
  [ "${__LOGFILE}"x != ""x ] && echo "${LogError_THISMSG}" >>${__LOGFILE}
}


# ---------------------------------------
#
# Usage: die [returncode] [message]
# 
die() {  
  die_THISRC=$1
  [ $# -ne 0 ] && shift
  die_THISMSG="$*"
  __EXIT_VIA_DIE=${__TRUE}

  cleanup

  if [ $# -ne 0 ] ; then
    if [ "${die_THISRC}"x = "0"x ] ; then
      LogMsg "${die_THISMSG}"
    else
      LogError "${die_THISMSG}"
    fi
  fi

  exit ${die_THISRC}
}


# ---------------------------------------
# GENERAL_SIGNAL_HANDLER
#
# general trap handler 
#
# usage: called automatically (parameter $1 is the signal number)
#
# returns: -
#
GENERAL_SIGNAL_HANDLER() {

  case $1 in 

    1 )
        LogInfo "HUP signal received."
        ;;

    2 )
        if [ ${__USER_BREAK_ALLOWED} -eq ${__TRUE} ] ; then
          die 252 "Script aborted by the user via signal BREAK (CTRL-C)" 
        else
          LogInfo "Break signal (CTRL-C) received and ignored (Break is disabled)."
        fi
        ;;

    3 )
        die 251 "QUIT signal received" 
        ;;

   15 )
        die 253 "Script aborted by the external signal TERM" 
        ;;

   "exit" | 0 )
        if [ "${__EXIT_VIA_DIE}"x != "${__TRUE}"x ] ; then
          LogWarning "You should use the function \"die\" to end the program"
        fi    

        ;;
       
    * ) die 254 "Unknown signal catched: $1 "
        ;;

  esac
}


# ---------------------------------------
# PrintVariables
#
PrintVariables() {
  
  for PrintVariables_CURVAR in __THISSCRIPT __LOGFILE __HOSTNAME __OS __OS_VERSION __RUNLEVEL ; do
    eval "PrintVariables_CURVALUE=\${${PrintVariables_CURVAR}}"
    LogInfo "${PrintVariables_CURVAR} is \"${PrintVariables_CURVALUE}\" "
  done

}


# ---------------------------------------
# add_man_path_entry path
#
add_man_path_entry() {
  add_man_path_entry_THISRC=0

  echo ":${MANPATH}:" | grep ":$1:" >/dev/null
  if [ $? -ne 0 ] ; then
    LogMsg "Adding the path \"$1\" to MANPATH ..."
    MANPATH="${MANPATH}:$1"
  else
    add_man_path_entry_THISRC=1
  fi

  return ${add_man_path_entry_THISRC}
}



# ---------------------------------------
# create_config_file
#
create_config_file() {
  create_config_file_THISRC=0
  LOCAL_MAN_PATH=""
  if [ ! -f "${MANSERVER_CONFIG_FILE}" ] ; then
    LogMsg "Creating the config file \"${MANSERVER_CONFIG_FILE}\" ..."
    cat <<EOT >"${MANSERVER_CONFIG_FILE}"
#     
# config file for the manserver
#
# known entries:
#  MANPATH=[manpath]
#  MANSERVER_PORT=[PORT]
#
MANPATH="${MANPATH}"
MANSERVER_PORT=${MANSERVER_PORT}
EOT

    chown "${THIS_USER}" "${MANSERVER_CONFIG_FILE}" 
  else
    LogMsg "The config file \"${MANSERVER_CONFIG_FILE}\" already exists"
    create_config_file_THISRC=1
  fi

  return ${create_config_file_THISRC}
}


# ---------------------------------------
# delete_config_file
#
delete_config_file() {
  delete_config_file_THISRC=0

  if [  -f "${MANSERVER_CONFIG_FILE}" ] ; then
    rm "${MANSERVER_CONFIG_FILE}" 1>/dev/null
    delete_config_file_THISRC=$?
  else
    delete_config_file_THISRC=1  
  fi

  return ${delete_config_file_THISRC}
}


# ---------------------------------------
# read_config_file - read the config file
#
read_config_file() {
  read_config_file_THISRC=0

  if [  -f "${MANSERVER_CONFIG_FILE}" ] ; then
    LogMsg "Reading the config file \"${MANSERVER_CONFIG_FILE}\" ..."
    . ${MANSERVER_CONFIG_FILE}

    for CUR_PATH in ` echo ${MAN_SERVER_MANPATH} | tr ":" " " `  ; do
      if [ -d "${CUR_PATH}" ] ; then
        add_man_path_entry "${CUR_PATH}"
      else
        LogWarning "The directory \"${CUR_PATH}\" does not exist; the directory is ignored"
      fi
    done
  else
    LogWarning "The config file \"${MANSERVER_CONFIG_FILE}\" does not exist"
    read_config_file_THISRC=1    
  fi

  LogMsg "The MANPATH for manserver is \"${MANPATH}\" "
  export MANPATH  

  return ${read_config_file_THISRC}
}


# ---------------------------------------
# start_manserver
#
start_manserver() {
  start_manserver_THISRC=0

  if [ ${PROCESS_RUNNING} = ${__TRUE} ] ; then
    LogMsg "${__APPLICATION} already running; the PID is ${PROCESS_PID}"
  else	
    LogMsg "Starting ${__APPLICATION} ..." 

    TMPFILE="/tmp/test.$$"
    rm "${MANSERVER_PID_FILE}" 1>/dev/null 2>/dev/null

    cat <<EOT >${TMPFILE}  
. "${MANSERVER_CONFIG_FILE}"
export MANPATH
nohup ${MANSERVER_BINARY} -s ${MANSERVER_PORT} >${MANSERVER_LOGFILE} 2>&1 &
echo \$! >"${MANSERVER_PID_FILE}"
EOT
    chmod 755 "${TMPFILE}"

    cat "${TMPFILE}"   
    su - "${THIS_USER}" -c "${TMPFILE}"   

    rm "${TMPFILE}"
  fi

  return ${start_manserver_THISRC}
}

# ---------------------------------------
# stop_manserver
#
stop_manserver() {
  stop_manserver_THISRC=0
  if [ ${PROCESS_RUNNING} != ${__TRUE} ] ; then
    LogMsg "${__APPLICATION} is not running"
  else	
    LogMsg "Stopping ${__APPLICATION} ..." 
    kill ${PROCESS_PID}
    PROCESS_RUNNING=${__FALSE}
    rm "${MANSERVER_PID_FILE}" 1>/dev/null 2>/dev/null
  fi

  return ${stop_manserver_THISRC}
}

# ---------------------------------------
# status_manserver
#
status_manserver() {
  status_manservere_THISRC=0

  if [ ${PROCESS_RUNNING} = ${__TRUE} ] ; then
    LogMsg "${__APPLICATION} already running; the PID is ${PROCESS_PID}"
    status_manserver_THISRC=0
  else	
    LogMsg "${__APPLICATION} not running"
    status_manserver_THISRC=1
  fi

  return ${status_manserver_THISRC}
}

# ---------------------------------------
#
# main code
#

# install trap handler
  trap "GENERAL_SIGNAL_HANDLER  1"  1
  trap "GENERAL_SIGNAL_HANDLER  2"  2
  trap "GENERAL_SIGNAL_HANDLER  3"  3
  trap "GENERAL_SIGNAL_HANDLER 15" 15
  trap "GENERAL_SIGNAL_HANDLER exit" 0

# check the logfile
  if [ "${__LOGFILE}"x != ""x ] ; then
    touch ${__LOGFILE}
    [ $? -ne 0 ] && __LOGFILE=""
  fi

  MANSERVER_INSTALLDIR="/tools/scripts"
  MANSERVER_BINARY="${MANSERVER_INSTALLDIR}/manServer_107.pl"

  MANSERVER_PORT=8888
  
  MANSERVER_CONFIG_FILE="/etc/manserver.conf"
  MANSERVER_PID_FILE="/tmp/manserver.pid"
  MANSERVER_LOGFILE="/tmp/manserver.$$.log"
  
  [ ! -d "${MANSERVER_INSTALLDIR}" ] && die 5 "The directory \"${MANSERVER_INSTALLDIR}\" does not exist"
  [ ! -x "${MANSERVER_BINARY}" ] && die 5 "The file \"${MANSERVER_BINARY}\" does not exist or is not executable"
  grep "^${THIS_USER}:" /etc/passwd 1>/dev/null || die 6 "The user \"${THIS_USER}\" does not exist"
  
  PID_FILE="${MANSERVER_PID_FILE}"
  [ -f ${PID_FILE} ]  && PROCESS_PID=` cat ${PID_FILE} `
  [ "${PROCESS_PID}"x != ""x ] && PROCESS_PID=`ps -p ${PROCESS_PID} -o pid=`
  [ "${PROCESS_PID}"x != ""x ] && PROCESS_RUNNING=${__TRUE} || PROCESS_RUNNING=${__FALSE} 

  LogInfo "Action is \"${ACTION}\""
  LogInfo "Actionparameter are \"${ACTION_PARAMETER}\""
  
  case ${ACTION} in

    createconfig | init )
       create_config_file 
       main_RC=$?
       ;;

    refresh | restart )
       stop_manserver   
       create_config_file
       start_manserver
       main_RC=$?
       ;;
                  
    start ) 
      create_config_file 
      read_config_file
      start_manserver
      main_RC=$?      
      ;;

    status )
      status_manserver
       main_RC=$?
       ;;

    stop )
      stop_manserver
       main_RC=$?
      ;;

    * ) 
      LogMsg "Usage: ${__THISSCRIPT} [start|stop|status|init|refresh]"
      main_RC=1
      ;;

  esac

# ---------------------------------------
 
  die ${main_RC}

# ---------------------------------------

