# Installs an NTP server daemon on your Mac via the OpenNTPD project
# source code (http://www.openntpd.org/).
#
# For use with SecuritySpy (https://bensoftware.com/securityspy) or any client
# requiring an NTP server.
#
# Use "chmod +x ntpd-install.sh" to make this script executable before running.
#
# Apple's Command Line Tools are required to run this script - this can usuallly
# be installed via the Terminal command "xcode-select --install".
#
# Tested on macOS 10.14 and 10.15. Older macOS versions have ntpd built in -
# on those systems, use the built-in version rather than installing one yourself.
#
# Written by Ben Bird, 11 May 2020. Free for anyone to use or distribute for
# any purpose.

BASE="openntpd-6.2p3"

cd /tmp

launchctl stop ntpd
launchctl unload /Library/LaunchDaemons/ntpd.plist
touch /var/db/ntp-kod
chmod 666 /var/db/ntp-kod

if [ -d "$BASE" ]; then
	rm -r $BASE
fi
if [ -f "$BASE.tar.gz" ]; then
	rm $BASE.tar.gz
fi
if [ -f "$BASE.tar" ]; then
	rm $BASE.tar
fi
if [ ! -d "/Library/StartupItems" ]; then
	mkdir "/Library/StartupItems"
fi

curl -o $BASE.tar.gz https://bensoftware.com/$BASE.tar.gz

gunzip $BASE.tar.gz
tar -xvf $BASE.tar

rm $BASE.tar.gz
rm $BASE.tar
cd $BASE

./configure --with-privsep-user=root
make
make install

cd ..
rm -r $BASE

echo "server time.apple.com
listen on *" > /usr/local/etc/ntpd.conf

echo "sleep 30
while true
do
sudo /usr/local/sbin/ntpd
sleep 3600
sudo killall -9 ntpd
sleep 1
done" > ntpd.sh
mv ntpd.sh /Library/StartupItems/ntpd.sh
chmod +x /Library/StartupItems/ntpd.sh
chown root /Library/StartupItems/ntpd.sh

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>ntpd</string>
		<key>ProgramArguments</key>
		<array><string>/Library/StartupItems/ntpd.sh</string></array>
		<key>RunAtLoad</key>
		<true/>
	</dict>
</plist>" > ntpd.plist

mv ntpd.plist /Library/LaunchDaemons
launchctl load /Library/LaunchDaemons/ntpd.plist
launchctl start ntpd