#!/bin/sh

po_domain="alterator-bacula"
alterator_api_version=1

. bacula-alterator-sh-functions
. alterator-sh-functions

. shell-quote
. shell-regexp

daemon_status()
{
    test -n "$1" || return
    local IFS=' '
    local runlevel="$(/sbin/runlevel | cut -c3)"

    LANG=C LC_ALL=C /sbin/chkconfig --list "$1"|grep -qs "${runlevel}:on" || return 1
    /sbin/service "$1" status >/dev/null || return 1
}

daemon_on()
{
    test -n "$1" || return
    daemon_status "$1" && return 0

    /sbin/chkconfig "$1" on
    /sbin/service "$1" start >&2 || :
}

daemon_off()
{
    test -n "$1" || return
    /sbin/service "$1" condstop >&2
    /sbin/chkconfig "$1" off
}


on_message()
{
  case "$in_action" in
    init)
	mysql_create_database_bacula
	;;
    type)
	write_type_item director_name system-computer-name
	write_type_item storage_address system-computer-address
	;;
    read)
        ! daemon_status bacula-dir
        write_bool_param director_server "$?"
	! daemon_status bacula-sd
        write_bool_param storage_server "$?"
	local address="$(bacula_storage_get_address)"
	local name="$(bacula_director_get_name)"
	if [ $address = "127.0.0.1" ]; then address=""; fi
	write_string_param storage_address "$address"
	write_string_param director_name "$name"
	write_string_param director_pass ""
	write_string_param storage_pass ""

	;;
    write)
	daemon_ready || return

	if [ -n "$in_director_pass" ];then
	    bacula_director_set_password "$in_director_pass"
	elif [ -z "$(bacula_director_get_password)" ];then
	    write_error "`_ "Password director not specified!"`"
	    return
	fi

	if [ -n "$in_storage_pass" ];then
	    bacula_storage_set_password "$in_storage_pass"
	elif [ -z "$(bacula_storage_get_password)" ];then
	    write_error "`_ "Password storage not specified!"`"
	    return
	fi

	if [ -n "$in_director_name" ] && [ -n "$in_storage_address" ]; then
	    bacula_director_set_name	"$in_director_name" #bacula-dir
	    bacula_storage_set_director "$in_director_name" #bacula-sd
	    bacula_file_set_director	"$in_director_name" #bacula-fd
	    bacula_console_set_director	"$in_director_name" #bacula-console
	    bacula_storage_set_address	"$in_storage_address"
	fi
	
	if [ -z "$in_storage_address" ] || [ $in_storage_address = "127.0.0.1" ]; then
	write_error "`_ "You should define valid storage address!"`"
	fi

	if test_bool "$in_director_server"; then
           daemon_on bacula-dir
         else
	   daemon_off bacula-dir
	fi
	
	if test_bool "$in_storage_server"; then
           daemon_on bacula-sd
         else
	   daemon_off bacula-sd
	fi
	
	daemon_restart_all
	;;
  esac
}

message_loop
