#!/bin/sh
if [ true != "$INIT_D_SCRIPT_SOURCED" ] ; then
  set "$0" "$@"; INIT_D_SCRIPT_SOURCED=true . /lib/init/init-d-script
fi
### BEGIN INIT INFO
# Provides:          acct
# Required-Start:    $remote_fs
# Required-Stop:     $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: process and login accounting
# Description:       GNU Accounting Utilities is a set of utilities which
#                    reports and summarizes data about user connect times and
#                    process execution statistics.
### END INIT INFO

DAEMON=/usr/sbin/accton
NAME=acct
DESC="process accounting"

caps="-all,+sys_pacct"
SETPRIV_ARGS="--inh-caps $caps --ambient-caps $caps --bounding-set $caps --no-new-privs"

# Thanks: oneshot pattern for init-d-script devised by Mark Hindley and
# and adapted for acct by Andrew Bower.

run_accton() {
  # Borrowed from init-d-script:
  if [ "$SETPRIV_ARGS" ] ; then
    PATH=/bin:/usr/bin command -v setpriv  > /dev/null 2>&1 || unset SETPRIV_ARGS
  fi

  ${SETPRIV_ARGS:+setpriv $SETPRIV_ARGS} $DAEMON "$@" >/dev/null 2>/dev/null
}

do_start_prepare() {
  [ -f /run/$NAME.oneshot ] && exit
}

do_stop_cleanup() {
  rm -f /run/$NAME.oneshot
}

do_status_override() {
  if [ -f /run/$NAME.oneshot ]; then
    log_success_msg "$NAME is running"
  else
    log_failure_msg "$NAME is not running"
    return 4
  fi
}

do_start_cmd_override() {

  # Allow the log file preparation commands to fail - defer errors to accton
  file="/var/log/account/pacct"
  mkdir -p "$(dirname $file)"
  touch "$file"
  chmod 640 "$file"
  chown root:adm "$file"

  run_accton "$file"
  rv=$?
  if [ $rv -eq 38 ]; then #ENOSYS
    log_warning_msg "Process accounting not available with this kernel."
  elif [ $rv -eq 16 ]; then #EBUSY
    log_warning_msg "Process accounting already enabled on this system."
  elif [ $rv -eq 1 ]; then #EPERM
    log_warning_msg "Insufficient privileges."
  elif [ $rv -eq 0 ]; then
    touch /run/$NAME.oneshot
    return 0
  fi
  return 2
}

do_stop_cmd_override() {
  [ -f /run/$NAME.oneshot ] || return 1
  run_accton off
}
