#!/bin/sh

po_domain="alterator-datetime"
ntpd_file=/etc/ntpd.conf
datadir=/usr/share/alterator-datetime/
default_pool_file="$datadir/pools"

rdelim='[[:space:]]\+'
wdelim=' '

date_re='[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}'
time_re='[[:digit:]]{2}:[[:digit:]]{2}:[[:digit:]]{2}'

. alterator-sh-functions
. shell-config

read_pool()
{
	shell_config_get "$ntpd_file" "servers" "$rdelim"|head -n1
}

write_pool()
{
    shell_config_del "$ntpd_file" "server" "$rdelim"
    shell_config_del "$ntpd_file" "servers" "$rdelim"
    shell_config_set "$ntpd_file" "servers" "$1" "$rdelim" "$wdelim"
}

read_runlevel()
{
    sed -nr '/:initdefault:$/ {s,^id:([^:]+):.*,\1,;p}' /etc/inittab
}

on_message()
{
	case "$in_action" in
		constraints)
			echo '('
			printf 'ntp_pool (label "%s" hostname #t)\n' \
			    "`_ "NTP server"`"
			printf 'date (label "%s" match ("%s" "%s"))\n' \
			    "`_ "Current date"`" \
			    "$date_re" \
			    "`_ "date should be in YYYY-MM-DD format"`"
			printf 'time (label "%s" match ("%s" "%s"))\n' \
			    "`_ "Current time"`" \
			    "$time_re" \
			    "`_ "time should be in HH:MM:SS format"`"
			echo ')'
			;;
	    	read)
			echo '('

			#date&time
			write_string_param 'date' "$(date +%F)"
			write_string_param 'time' "$(date +%T)"

			#ntp
			write_string_param ntp_pool "$(read_pool)"

			if [ "$(/usr/sbin/control ntpd)" = "client" ];then
				printf 'ntp_accept #f\n'
			else
				printf 'ntp_accept #t\n'
			fi

			local runlevel=$(read_runlevel)
			if LANG=C /sbin/chkconfig --list ntpd 2>/dev/null|fgrep -qsw "$runlevel:on";then
				printf 'ntp_status #t\n'
			else
				printf 'ntp_status #f\n'
			fi

			echo ')'
			;;
		write)
			#date&time
			if  [ -n "$in_date" -a -n "$in_time" ] &&
			    ! date --set="$in_date $in_time" 2>/dev/null >/dev/null; then
				write_error "`_ "unable to setup time"`"
				return
			fi

			#ntp
			if [ -n "$in_ntp_pool" ] ;then
			    write_pool "$in_ntp_pool" || return
			fi

			if test_bool "$in_ntp_accept";then
			    /usr/sbin/control ntpd server >&2
			else
			    /usr/sbin/control ntpd client >&2
			fi

			if test_bool "$in_ntp_status"; then
				/sbin/chkconfig ntpd on
				service ntpd start >/dev/null 2>/dev/null
			else
				/sbin/chkconfig ntpd off
				service ntpd condstop >/dev/null 2>/dev/null
			fi

			service clock sync >/dev/null 2>/dev/null

			write_nop
			;;
		*)
			echo '#f'
			;;
	esac
}

message_loop
