#!/bin/bash
#
# script: rc.dnsmasq
#
# Start/stop/restart dnsmasq (a small DNS/DHCP server)
#
# LimeTech - modified for Unraid OS
# Bergware - modified for Unraid OS, October 2023

DAEMON="DNSmasq daemon"
PIDFILE="/var/run/dnsmasq.pid"

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

dnsmasq_running(){
  sleep 0.1
  pgrep --ns $$ -l -F $PIDFILE 2>/dev/null | grep -q dnsmasq
}

dnsmasq_start(){
  log "Starting $DAEMON..."
  local REPLY
  if [[ -x /usr/sbin/dnsmasq ]]; then
    run /usr/sbin/dnsmasq
    if dnsmasq_running; then REPLY="Started"; else REPLY="Failed"; fi
  else
    REPLY="Missing executable"
  fi
  log "$DAEMON...  $REPLY."
}

dnsmasq_stop(){
  log "Stopping $DAEMON..."
  local REPLY
  if dnsmasq_running; then
    # try to use the .pid file first
    pkill -F $PIDFILE 2>/dev/null
  else
    # kill any dnsmasq processes in this namespace:
    killall --ns $$ dnsmasq 2>/dev/null
  fi
  if ! dnsmasq_running; then REPLY="Stopped"; else REPLY="Failed"; fi
  log "$DAEMON...  $REPLY."
}

dnsmasq_restart(){
  log "Restarting $DAEMON..."
  dnsmasq_stop
  sleep 1
  dnsmasq_start
}

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

case "$1" in
'start')
  dnsmasq_start
  ;;
'stop')
  dnsmasq_stop
  ;;
'restart')
  dnsmasq_restart
  ;;
'status')
  dnsmasq_status
  ;;
*)
  echo "Usage: $BASENAME start|stop|restart|status"
  exit 1
esac
exit 0
