#!/bin/sh

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

_()
{
LANG=${in_language%%;*}.utf8 gettext "alterator-chkconfig" "$1"
}

#turn off auto expansion
set -f

. /usr/share/alterator/build/backend3.sh


on_message()
{
	case "$in_action" in
		constraints)
			echo '('
			printf 'onboot (label "%s" default #f)' "`_ "Start on system booting"`"
			printf 'status (label "%s")' "`_ "Service status"`"
			echo ')'
			;;
		list)
			echo '('
			printf '( "nochanges" label "%s")\n' "`_ "leave without changes"`"
			printf '( "start" label "%s")\n' "`_ "start"`"
			printf '( "stop" label "%s")\n' "`_ "stop"`"
			printf '( "restart" label "%s")\n' "`_ "restart"`"
			echo ')'
			;;
		read)
			echo '('
			if [ "$in_objects" != "/" ];then
			    local runlevel=$(read_runlevel)
			    [ -n "$runlevel" ] || runlevel=3

			    if LANG=C chkconfig --list "$in__objects"|fgrep -qsw "$runlevel:on";then
				printf ' onboot #t\n'
			    else
				printf ' onboot #f\n'
			    fi
			    printf ' info "%s"\n' "$(service "$in__objects" status|head -n1|simple_quote)"
			    printf ' name "%s"\n' "$in__objects"
			fi
			echo ')'
			;;
		write)
			if [ "$in__objects" != "/" ];then
			    case "$in_status" in
				start|stop|restart)
				    service "$in__objects" "$in_status" >/dev/null
				    ;;
				*)
			    esac
			    if [ "$in_onboot" = "#t" ];then
				chkconfig --add "$in__objects" >/dev/null
				chkconfig "$in__objects" on >/dev/null
			    else
				chkconfig "$in__objects" off >/dev/null
			    fi
			fi
			echo '()'
			;;
		*)
			echo '#f'
			;;
	esac
}

message_loop
