#!/bin/bash
#
# script: rc.acpid
#
# Start/stop/restart acpid.
#
# LimeTech - modified for Unraid OS
# Bergware - modified for Unraid OS, October 2023

DAEMON="ACPI power management daemon"

# run & log functions
. /etc/rc.d/rc.runlog

acpid_running(){
  sleep 0.1
  ps axc | grep -q ' acpid'
}

acpid_start(){
  log "Starting $DAEMON..."
  local REPLY
  if acpid_running; then
    REPLY="Already started"
  else
    if [[ -d /proc/acpi ]]; then
      run /usr/sbin/acpid
      if acpid_running; then REPLY="Started"; else REPLY="Failed"; fi
    else
      REPLY="No ACPI present"
    fi
  fi
  log "$DAEMON...  $REPLY."
}

acpid_stop(){
  log "Stopping $DAEMON..."
  local REPLY
  if ! acpid_running; then
    REPLY="Already stopped"
  else
    run kill $(cat /var/run/acpid.pid 2>/dev/null)
    run killall --ns $$ acpid
    if ! acpid_running; then REPLY="Stopped"; else REPLY="Failed"; fi
  fi
  log "$DAEMON...  $REPLY."
}

acpid_restart(){
  log "Restarting $DAEMON..."
  acpid_stop
  sleep 1
  acpid_start
}

acpid_status(){
  if acpid_running; then
    echo "$DAEMON is currently running."
  else
    echo "$DAEMON is not running."
    exit 1
  fi
}

case "$1" in
'start')
  acpid_start
  ;;
'stop')
  acpid_stop
  ;;
'restart')
  acpid_restart
  ;;
'status')
  acpid_status
  ;;
*)
  echo "Usage: $BASENAME start|stop|restart|status"
  exit 1
esac
exit 0
