#!/bin/sh

PATH=/bin:/usr/bin:/sbin:/usr/sbin

usage() {
    cat <<-EOF
	usage: $(basename $0) action
	    action: start or stop to enable/disable slave services
	EOF
}

start_dhcp() {
    # apply replicated configuration
    xivo-create-config
    xivo-update-config

    # fetch updated phone MAC prefixes
    dhcpd-update -dr

    service isc-dhcp-server start
    update-rc.d isc-dhcp-server defaults
}

stop_dhcp() {
    update-rc.d isc-dhcp-server remove
    service isc-dhcp-server stop
}

reload_pjsip_conf() {
    curl --insecure -XPOST -H 'Content-Type: application/json' 'http://localhost:8668/exec_request_handlers' -d '{"ipbx": ["module reload res_pjsip.so"]}'
}

enable_service() {
    start_dhcp
    service consul start
    xivo-update-keys
    xivo-service enable
    xivo-service start
    # reactivate monitoring because most services failed too much
    monit monitor all
    xivo-agentd-cli -c 'relog all'
    reload_pjsip_conf
}

disable_service() {
    xivo-service stop xivo
    xivo-service disable
    service consul stop
    stop_dhcp
    xivo-service start
}

case $1 in
    start) enable_service;;
    stop)  disable_service;;
    *) usage;;
esac
