#!/bin/sh
#
# NTP daemon start script
#
# author: Thorsten Muehlfelder <thenktor@gmx.de>
# version: 1.17

PID=""

ntpd_sync() {
	PID=`pidof -o %PPID /usr/sbin/ntpd`
	if [ -z "$PID" ]; then
		/usr/sbin/ntpd -gq
		/sbin/hwclock -w
	else
		echo "The ntpd is already running with pid: $PID"
		exit 2
	fi
}

ntpd_start() {
	PID=`pidof -o %PPID /usr/sbin/ntpd`
	if [ -z "$PID" ]; then
		echo "Starting ntpd..."
		/usr/sbin/ntpd -g -U 180 -p /var/run/ntpd.pid
		echo ""
	else
		echo "The ntpd is already running with pid: $PID"
		exit 2
	fi
}

ntpd_stop() {
	PID=`pidof -o %PPID /usr/sbin/ntpd`
	if [ ! -z "$PID" ]; then
		echo "Stopping ntpd..."
		killall -q -TERM ntpd
		sleep 1
		killall -9 ntpd 1> /dev/null 2>&1
		rm -f /var/run/ntpd.pid
		echo ""
	else
		echo "The ntpd is not running."
	fi
}

ntpd_status() {
	PID=`pidof -o %PPID /usr/sbin/ntpd`
	if [ ! -z "$PID" ]; then
		echo "The ntpd is running with pid: $PID"
		exit 0
	else
		echo "The ntpd is not running"
		exit 1
	fi
}

ntpd_info() {
	PID=`pidof -o %PPID /usr/sbin/ntpd`
	if [ ! -z "$PID" ]; then
		/usr/sbin/ntpq -p 127.0.0.1
		echo ""
		exit 0
	else
		echo "The ntpd is not running."
		exit 1
	fi
}

case "$1" in
'start')
	ntpd_start
	;;

'stop')
	ntpd_stop
	;;

'restart')
	ntpd_stop
	sleep 1
	ntpd_start
	;;

'status')
	ntpd_status
	;;

'info')
	ntpd_info
	;;

'sync')
	ntpd_sync
	;;

*)
	echo "Usage: $0 start|stop|restart|status|info|sync"
esac