#!/bin/sh

po_domain="alterator-ahttpd"
alterator_api_version=1

cron_file=/etc/cron.d/alterator-ahttpd
shutdown_cmd="/sbin/shutdown -t 3 -h now"
reboot_cmd="/sbin/shutdown -t 3 -r now"

. alterator-sh-functions

read_shutdown_time()
{
    [ ! -s "$cron_file" ] ||
	while read min hour monthday month weekday rest;do
	    [ -n "${min%\#*}" ] || continue

	    echo "$hour:$min:00"
	    return
	done <"$cron_file"
}

read_cron()
{
    local shutdown_time="$(read_shutdown_time)"
    write_string_param shutdown_time "${shutdown_time:-23:00:00}"

    ! [ -s "$cron_file" ]
    write_bool_param shutdown_cron "$?"
}

write_cron()
{
    if test_bool "$in_shutdown_cron" && [ -n "$in_shutdown_time" ]; then
	local time="${in_shutdown_time%:*}"
	local hour="${time%:*}"
	local min="${time#*:}"
	printf '%s %s * * * root %s\n' "$min" "$hour" "$shutdown_cmd" >"$cron_file"
    else
	rm -f "$cron_file"
    fi
}

reboot()
{
    $reboot_cmd >&2
}

poweroff()
{
    $shutdown_cmd >&2
}

alterator_export_var  shutdown_time time
alterator_export_proc read_cron
alterator_export_proc write_cron
alterator_export_proc reboot
alterator_export_proc poweroff

message_loop
