#!/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"
}

write_shutdown_time()
{
    local time="${1%:*}"
    local hour="${time%:*}"
    local min="${time#*:}"
    printf '%s %s * * * root %s\n' "$min" "$hour" "$shutdown_cmd" >"$cron_file"
    /sbin/service crond restart
}

clear_shutdown_time()
{
    rm -f "$cron_file"
    /sbin/service crond restart
}

on_message() {
  case "$in_action" in
    type)
	write_type_item shutdown_time time
	;;
    read)
	local shutdown_time="$(read_shutdown_time)"
	write_string_param shutdown_time "${shutdown_time:-23:00:00}"

	! [ -s "$cron_file" ]
	write_bool_param shutdown_cron "$?"
	;;
    reboot) $reboot_cmd >&2 ;;
    poweroff) $shutdown_cmd >&2 ;;
    write)
	if test_bool "$in_shutdown_cron"; then
	    [ -z "$in_shutdown_time" ] ||
		write_shutdown_time "$in_shutdown_time"
	else
	    clear_shutdown_time
	fi
	;;
  esac
}

message_loop
