#!/bin/bash 

# rc.boinc - BOINC startup/control script for Slackware Linux
#
# Copyright 2022 Edward Koenig, Vancouver, WA, USA
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
# EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

BOINC_DIR=/var/lib/boinc_data    # directory of boinc files
BOINC_BIN=boinc                  # name of the boinc binary
BOINC_USER=root                  # user that will run boinc process
BOINC_OPTIONS="--dir $BOINC_DIR --redirectio"
# "--dir $BOINC_DIR --daemon" will send logs syslog instead of
# stdoutdae.txt and stderrdae.txt

boinc_status() {
  if ( ps -ef | grep "$BOINC_BIN$" > /dev/null 2>&1 ); then
    return 0
  else
    return 3
fi
}

boinc_start() {
  boinc_status
  if [ $? = 0 ]; then
    echo "BOINC is already running"
    exit 1
  fi

  if [ ! -d $BOINC_DIR ]; then
    echo "ERROR: $BOINC_DIR does not exist"
    exit 1
  elif [ ! -x BOINC_BIN ]; then
    echo "ERROR: BOINC_BIN does not exist or not executable"
    exit 1
  fi

  echo "Starting BOINC client"
  su - $BOINC_USER -c "cd $BOINC_DIR; exec /usr/bin/BOINC_BIN $BOINC_OPTIONS" &
  
}

boinc_stop() {
  echo "Stopping BOINC client"
  killall $BOINC_BIN 
}

boinc_restart() {
  echo "Restarting BOINC client"

  boinc_status
    if [ $? = 0 ]; then 
    boinc_stop 
    sleep 3
    boinc_start
  else
    boinc_start
  fi
}


case "$1" in 
  start)
    boinc_start
    exit 0
  ;;
  stop)
    boinc_stop
    exit 0
  ;;
  restart)
    boinc_restart
    exit 0
  ;;
  status)
    boinc_status
    if [ $? = 0 ]; then
      echo "BOINC is running"
    else
      echo "BOINC is not running"
    fi
  ;;
  *)
    echo "Usage: $0 start|stop|restart|status"
    exit 1
  ;;

esac
