#! /bin/sh
### BEGIN INIT INFO
# Provides:          boinc_client
# Required-Start:    $local_fs $remote_fs
# Required-Stop:     $local_fs $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: BOINC core client
# Description:       core client for the BOINC distributed computing
#                    infrastructure
### END INIT INFO

# Debian init.d script for the BOINC core client
# Copyright © 2005, 2006
# Debian BOINC Maintainers <pkg-boinc-devel@lists.alioth.debian.org>
#
# This file is licensed under the terms of the GNU General Public License,
# Version 2 or any later version published by the Free Software Foundation.

set -e

ENABLED=0

. /lib/lsb/init-functions

# Source defaults file. Edit that file to configure this script.
if [ -e /etc/default/boinc-client ]; then
  . /etc/default/boinc-client
fi

# Quit quietly, if $ENABLED is 0.
test "$ENABLED" != "0" || exit 0

if [ ! -x "$BOINC_CLIENT" ]; then
  log_failure_msg "BOINC client '$BOINC_CLIENT' does not exist or is not " \
    "executable."
  exit 5
fi

if [ ! -d "$BOINC_DIR" ]; then
  log_failure_msg "BOINC data directory '$BOINC_DIR' does not exist."
  exit 6
fi

if [ -z "$BOINC_USER" ]; then
  log_failure_msg "BOINC_USER variable is empty. Set it to a user to run " \
    "the BOINC core client."
  exit 6
fi

PIDFILE=/var/run/boinc_client.pid
DESC="BOINC core client"
NAME=`basename $BOINC_CLIENT`
BOINC_OPTS="-redirectio -dir $BOINC_DIR $BOINC_OPTS"

is_running()
{
  retval=1
  if [ -r $PIDFILE ]; then
    pid=`cat $PIDFILE`
    if [ -e /proc/$pid ]; then
      procname=`/bin/ps h -p $pid`
      [ -n "$procname" ] && retval=0
    fi
  fi
  return $retval
}

start()
{
  log_begin_msg "Starting $DESC: $NAME"
  if is_running; then
    log_progress_msg "already running"
  else
    start-stop-daemon --start --quiet --background --pidfile $PIDFILE \
      --make-pidfile --user $BOINC_USER --chuid $BOINC_USER --chdir $BOINC_DIR \
      --exec $BOINC_CLIENT -- $BOINC_OPTS
  fi
  log_end_msg 0
}

stop()
{
  log_begin_msg "Stopping $DESC: $NAME"
  if ! is_running; then
    log_progress_msg "not running"
  else
    start-stop-daemon --stop --quiet --oknodo --pidfile $PIDFILE \
      --user $BOINC_USER --exec $BOINC_CLIENT
  fi

  rm -f "$BOINC_DIR/lockfile"
  rm -f $PIDFILE
  log_end_msg 0
}

status()
{
  STATUS="Status of $DESC:"
  if is_running; then
    log_success_msg "$STATUS running."
  else
    log_success_msg "$STATUS stopped."
  fi
}

case "$1" in
  start)
    start
    ;;

  stop)
    stop
    ;;

  restart|force-reload)
    stop
    sleep 1
    start
    ;;

  status)
    status
    ;;

  *)
    log_success_msg "Usage: $0 {start|stop|restart|force-reload|status}" >&2
    exit 1
    ;;
esac

exit 0
