#!/bin/sh /etc/rc.common

START=99
USE_PROCD=1

BOINCEXE_NAME=boinc_client
BOINCDIR=/opt/boinc/
PRESETDIR=/usr/share/boinc
BOINCUSR=boinc
BOINCEXE_OPTS="--check_all_logins --redirectio --dir $BOINCDIR"
PID_FILE="/var/run/$BOINCEXE_NAME.pid"

start_service() {
   # First check that BOINCDIR exists
   if ! [ -d "$BOINCDIR" ]; then
      if ! mkdir -p $BOINCDIR 2>/dev/null ; then
         echo "ERROR: $BOINCDIR doesn't exist and couldn't be created"
         return 1
      fi
   fi

   # adjust some presettings if necessary
   for f in global_prefs_override.xml remote_hosts.cfg; do
      if ! [ -f $BOINCDIR/$f ]; then
         cp $PRESETDIR/$f $BOINCDIR
      fi
   done

   # and ensure it is accessible by boinc
   BOINCDIR_OWNER="$(ls -ld $BOINCDIR | awk '{print $3}')"
   if [ "$BOINCUSR" != "$BOINCDIR_OWNER" ] ; then
      chown -R $BOINCUSR:$BOINCUSR $BOINCDIR
      BOINCDIR_OWNER="$(ls -ld $BOINCDIR | awk '{print $3}')"

      if [ "$BOINCUSR" != "$BOINCDIR_OWNER" ] ; then
         echo "User boinc can't access $BOINC_DIR"
         return 3
      fi
   fi

   # now use procd to start boinc
   procd_open_instance $BOINCEXE_NAME

   procd_set_param command $BOINCEXE_NAME
   procd_append_param command $BOINCEXE_OPTS
   procd_set_param user $BOINCUSR
   procd_set_param limits core="unlimited"
   procd_set_param stdout 1
   procd_set_param stderr 1
   procd_set_param pidfile $PID_FILE

   procd_close_instance
}
