#!/bin/sh
#
# Author: Mark Felder <feld@FreeBSD.org>

# PROVIDE: ntimed
# REQUIRE: LOGIN
# KEYWORD: shutdown

# Add the following lines to /etc/rc.conf to enable ntimed:
# ntimed_enable="YES"
# ntimed_flags="<set as needed>"

. /etc/rc.subr

name=ntimed
rcvar=ntimed_enable

load_rc_config $name

: ${ntimed_enable:=NO}
: ${ntimed_flags:="0.freebsd.pool.ntp.org"}

start_precmd=ntimed_prestart
pidfile=/var/run/ntimed.pid
ntimed_cmd="/usr/local/sbin/ntimed-client"
command=/usr/sbin/daemon

can_run_nonroot()
{
        # Try to set up the the MAC ntpd policy so ntimed can run with reduced
        # privileges.  Detect whether MAC is compiled into the kernel, load
        # the policy module if not already present, then check whether the
        # policy has been disabled via tunable or sysctl.
        [ -n "$(sysctl -qn security.mac.version)" ] || return 1
        sysctl -qn security.mac.ntpd >/dev/null || kldload -qn mac_ntpd || return 1
        [ "$(sysctl -qn security.mac.ntpd.enabled)" == "1" ] || return 1
}

ntimed_prestart()
{
        # Have to empty rc_flags so they don't get passed to daemon(8)
        rc_flags=""

        if can_run_nonroot; then
            _ntimed_user="ntpd"
        else
            _ntimed_user="root"
        fi

        command_args=" -r -P ${pidfile} -u ${_ntimed_user} ${ntimed_cmd} ${ntimed_flags}"
}

run_rc_command "$1"
