#!/bin/bash
#
# kadmind      Start and stop the Kerberos 5 administrative server.
#
# chkconfig:   - 35 65
# description: Kerberos 5 is a trusted third-party authentication system.  \
#         This script starts and stops the Kerberos 5 administrative \
#              server, which should only be run on the master server for a \
#              realm.
# processname: kadmind
# config: /etc/default/kadmin
# pidfile: /var/run/kadmind.pid
#

### BEGIN INIT INFO
# Provides: kadmin
# Required-Start: $local_fs $network
# Required-Stop: $local_fs $network
# Should-Start: portreserve
# Default-Start:
# Default-Stop: 0 1 2 3 4 5 6
# Short-Description: start and stop the Kerberos 5 admin server
# Description: The kadmind service allows administrators to remotely manage \
#              the Kerberos 5 realm database.  It should only be run on a \
#              master KDC.
### END INIT INFO

# Get config.
unset KADMIND_ARGS
[ -r /etc/default/kadmin ] && . /etc/default/kadmin

prog="Kerberos 5 Admin Server"
kadmind="/usr/sbin/kadmind"
lockfile=/var/lock/subsys/kadmin
pidfile=/var/run/kadmind.pid

RETVAL=0

PID=$(/sbin/pidof -o %PPID ${kadmind})

# Shell functions to cut down on useless shell instances.
start() {
  if [ -f /var/kerberos/krb5kdc/kpropd.acl ] ; then
    echo "Error. This appears to be a slave server, found kpropd.acl"
    exit 6
  else
    [ -x ${kadmind} ] || exit 5
  fi
  echo -n "Starting ${prog}: "

  if [ -z "${PID}" ] ;then 
    ${kadmind} ${KRB5REALM:+-r ${KRB5REALM}} -P ${pidfile} ${KADMIND_ARGS} 2>/dev/null
    RETVAL=$?
  else
    RETVAL=1
  fi
  if test ${RETVAL} -ne 0 ; then
    if /sbin/pidof -o %PPID ${kadmind} > /dev/null ; then
      RETVAL=0
    fi
  fi
  if [ ${RETVAL} -eq 0 ] && touch ${lockfile} ; then
    echo -e "\t\t\t\t[  OK  ]\r"
  else
    echo -e "\t\t\t\t[FAILED]\r"
  fi
  return ${RETVAL}
}

stop() {
  echo -n "Stopping ${prog}: "
  if [ -n "${PID}" ] ;then
    kill ${PID} &>/dev/null
    RETVAL=$?
  else
    RETVAL=1
  fi
  if [ ${RETVAL} -eq 0 ] && rm -f ${lockfile} ; then
    echo -e "\t\t\t\t[  OK  ]\r"
  else
    echo -e "\t\t\t\t[FAILED]\r"
  fi
  return ${RETVAL}
}

reload(){
  echo -n "Reopening ${prog} log file: "
  if [ -n "${PID}" ] ;then
    kill ${PID} -HUP
    RETVAL=$?
  else
    RETVAL=1
  fi
  if [ ${RETVAL} -eq 0 ] ; then
    echo -e "\t\t\t[  OK  ]\r"
  else
    echo -e "\t\t\t[FAILED]\r"
  fi
  return ${RETVAL}
}

restart(){
  stop
  unset PID
  sleep 1
  start
}

status() {
  if [ -n "${PID}" ] ;then
    echo "${kadmind} is running in pid ${PID}."
  else
    echo "${kadmind} is not running."
    RETVAL=3
  fi
  return ${RETVAL}
}

condrestart(){
  [ -e ${lockfile} ] && restart
  return 0
}

# See how we were called.
case "$1" in
  start|stop|restart|reload|status|condrestart)
    $1
    ;;
  *)
  echo "Usage: $0 {start|stop|restart|reload|status|condrestart}"
  RETVAL=2
  ;;
esac

exit ${RETVAL}
