#!/usr/bin/env bash

# Installs the NTP server relay daemon on your Mac.
#
# This daemon opens automatically at Mac startup, and listens on NTP port 123
# for clients. Data is forwarded to time.apple.com and the replies are relayed
# back to clients.
#
# Written by Ben Bird, June 2021. Free for anyone to use or distribute for
# any purpose.

if [ ! -d "/usr/local/sbin" ]; then
	mkdir "/usr/local/sbin"
fi

if [ -f "/Library/StartupItems/ntpd.sh" ]; then
	rm -f "/Library/StartupItems/ntpd.sh"
fi

if [ -f "/Library/LaunchDaemons/ntpd.plist" ]; then
	launchctl stop ntpd
	launchctl unload /Library/LaunchDaemons/ntpd.plist
	rm -f "/Library/LaunchDaemons/ntpd.plist"
fi

if [ -f "/Library/LaunchDaemons/ntp-relay.plist" ]; then
	launchctl stop ntp-relay
	launchctl unload /Library/LaunchDaemons/ntp-relay.plist
	rm -f "/Library/LaunchDaemons/ntp-relay.plist"
fi

if [ -f "/Library/LaunchDaemons/com.bensoftware.ntp-relay.plist" ]; then
	launchctl stop com.bensoftware.ntp-relay
	launchctl unload /Library/LaunchDaemons/com.bensoftware.ntp-relay.plist
	rm -f "/Library/LaunchDaemons/com.bensoftware.ntp-relay.plist"
fi

if [ -f "/usr/local/sbin/ntp-relay" ]; then
	rm -f "/usr/local/sbin/ntp-relay"
fi

BASE=$(dirname "$0")	#The directory in which we reside

cp "$BASE/ntp-relay" "/usr/local/sbin/ntp-relay"

cd /tmp

echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
<plist version=\"1.0\">
	<dict>
		<key>Label</key>
		<string>com.bensoftware.ntp-relay</string>
		<key>ProgramArguments</key>
		<array><string>/usr/local/sbin/ntp-relay</string></array>
		<key>RunAtLoad</key>
		<true/>
		<key>KeepAlive</key>
		<true/>
	</dict>
</plist>" > com.bensoftware.ntp-relay.plist

mv com.bensoftware.ntp-relay.plist /Library/LaunchDaemons

chown root:wheel /Library/LaunchDaemons/com.bensoftware.ntp-relay.plist
chown root:wheel /usr/local/sbin/ntp-relay

launchctl load /Library/LaunchDaemons/com.bensoftware.ntp-relay.plist
