#!/bin/bash
# chkconfig: 2345 99 60
# description: tinman http application
# processname: tinman
# config: /etc/sysconfig/tinman
# pidfile: /tmp/tinman.pid

# Source function library.
. /etc/init.d/functions

# Installation dir
tinman_DIR="/opt/tinman"

tinman_PID_FILE="/tmp/tinman.pid"

# Additional arguments
tinman_OPTS=""


if [ -f /etc/sysconfig/tinman ]; then
  # Include configuration
  . /etc/sysconfig/tinman
fi


# Configuration file
tinman_CONF="${tinman_CONF:-${tinman_DIR}/tinman.yaml}"

# Run as this user
tinman_USER="${tinman_USER:-tinman}"


if [ ! -d "${tinman_DIR}" ]; then
  echo -n $"cannot find tinman installation dir: '${tinman_DIR}'"
  failure $"cannot find tinman installation dir: '${tinman_DIR}'"
  echo
  exit 1
fi

tinman_OPTS="-c ${tinman_CONF} ${tinman_OPTS}"

prog="tinman"

dostatus() {
  [ -e "${tinman_PID_FILE}" ] || return 1

  local pid=$(cat ${tinman_PID_FILE})
  [ -d /proc/${pid} ] || return 1

  [ -z "$(grep tinman /proc/${pid}/cmdline)" ] && return 1
  return 0
}

start() {
  if [ ${EUID} -ne 0 ]; then
    echo -n $"you must be root"
    failure $"you must be root"
    echo
    return 1
  fi

  echo -n $"Starting ${prog}: "

  dostatus
  if [ $? -eq 0 ]; then
    echo -n $"cannot start $prog: already running (pid: $(cat ${tinman_PID_FILE}))";
    failure $"cannot start $prog: already running (pid: $(cat ${tinman_PID_FILE}))";
    echo
    return 1
  fi

  cd ${tinman_DIR}
  /usr/bin/python2.6 "${tinman_DIR}/tinman" ${tinman_OPTS}
  RETVAL=$?

  echo
  return ${RETVAL}
}

stop() {
  if [ ${EUID} -ne 0 ]; then
    echo -n $"you must be root"
    failure $"you must be root"
    echo
    return 1
  fi

  echo -n $"Stopping ${prog}: "

  dostatus
  if [ $? -ne 0 ]; then
    echo -n $"cannot stop $prog: not running"
    failure $"cannot stop $prog: not running"
    echo
    return 1
  fi

  killproc -p "${tinman_PID_FILE}" "${tinman_DIR}/tinman"
  RETVAL=$?
  [ $RETVAL -eq 0 ] && rm -f ${tinman_PID_FILE}
  echo
  return $RETVAL
}

restart() {
  stop
  start
}

case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart)
    restart
    ;;
  status)
    dostatus
    if [ $? -eq 0 ]; then
      echo $"$prog: running..."
    else
      echo $"$prog: not running"
    fi
    ;;
  *)
    echo $"Usage: $0 {start|stop|status|restart}"
    RETVAL=2
    ;;
esac

exit $RETVAL

