#!/bin/bash

wait_for_congend() {
    local wait_time=30
    echo -e -n "Waiting maximum $wait_time seconds for xivo-confgend container to be healthy..."

    local is_healthy="false"
    for _ in $(seq 1 $wait_time); do
        if [ "$(docker inspect -f '{{.State.Health.Status}}' xivo-confgend-1)" = "healthy" ]; then
            is_healthy="true"
            break
        else
            sleep 1
            echo -e -n "."
        fi
    done
    echo
    if [ "$is_healthy" = "false" ]; then
        echo -e "\e[31mERROR: xivo-confgend container is not healthy.\e[0m"
        exit 1
    fi
}

# Force asterisk reload to regenerate configuration
wait_for_congend
curl --insecure --silent --output /dev/null -XPOST -H 'Content-Type: application/json' 'http://localhost:8668/exec_request_handlers' -d '{"ipbx": ["module reload res_pjsip.so", "dialplan reload"]}'
echo "pjsip.conf was correctly generated"
