#!/bin/sh
#
# Copyright (C) 2018-2025 Ruilin Peng (Nick) <pymumu@gmail.com>.
#
# smartdns is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# smartdns is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

### BEGIN INIT INFO
# Provides:        smartdns
# Required-Start:  $network 
# Required-Stop:   $network 
# Default-Start:   2 3 4 5
# Default-Stop:
# Short-Description: Start smartdns server
### END INIT INFO

PATH=/sbin:/bin:/usr/sbin:/usr/bin

. /etc/default/smartdns
SMARTDNS=/usr/sbin/smartdns
PIDFILE=/run/smartdns.pid
if [ ! -d "/run" ]; then
	PIDFILE=/var/run/smartdns.pid
fi

test -x $SMARTDNS || exit 5

case $1 in
	start)
		$SMARTDNS "$SMART_DNS_OPTS" -R
		while true; do
			if [ -e "$PIDFILE" ]; then
				break;
			fi
			sleep .5
		done
		PID="$(cat $PIDFILE 2>/dev/null)"
		if [ -z "$PID" ]; then
			echo "start smartdns server failed."
			exit 1
		fi
		if [ ! -e "/proc/$PID" ]; then
			echo "start smartdns server failed."
			exit 1
		fi
		echo "start smartdns server success."
		;;
	stop)
		if [ ! -f "$PIDFILE" ]; then
			echo "smartdns server is stopped."
			exit 0
		fi
		PID="$(cat $PIDFILE 2>/dev/null)"
		if [ ! -e "/proc/$PID" ] || [ -z "$PID" ]; then
			echo "smartdns server is stopped"
			exit 0
		fi

		kill -TERM "$PID"
		if [ $? -ne 0 ]; then
			echo "Stop smartdns server failed."
			exit 1;
		fi
		LOOP=1
		while true; do
			if [ ! -d "/proc/$PID" ]; then
				break;
			fi

			if [ $LOOP -gt 12 ]; then
				kill -9 "$PID"
				break;
			fi
			LOOP=$((LOOP+1))
			sleep .5
		done
		echo "Stop smartdns server success."
		;;
	restart)
		"$0" stop && "$0" start
		;;
	status)
		PID="$(cat "$PIDFILE" 2>/dev/null)"
		if [ ! -e "/proc/$PID" ] || [ -z "$PID" ]; then
			echo "smartdns server is not running."
			exit 1
		fi
		echo "smartdns server is running."
		status=0
		;;
	*)
		echo "Usage: $0 {start|stop|restart|status}"
		exit 2
		;;
esac

exit $status

