#!/bin/bash

function set_capa_doc() {
    echo_bold "=> If you use a value < 1024 as [nginx]/$1"
    echo_bold "=> you have to execute (as root): setcap cap_net_bind_service=+ep \"$2\""
    echo_bold ""
    echo_bold "(this manual setting will be lost after a metwork update unless you do (as root):"
    echo_bold " touch /etc/metwork.config.d/mfserv/set_cap_net_bind_service)"
}

RES=0
echo -n "- Checking nginx conf generation..."
NGINX="${MFEXT_HOME}/opt/openresty/nginx/sbin/nginx"
if test "${MFSERV_NGINX_PORT}" -le 1024; then
    CAPA=$(getcap "${NGINX}" |grep -E "cap_net_bind_service[+=]ep" 2>/dev/null)
    if test "${CAPA}" = ""; then
        echo_nok
        set_capa_doc port "${NGINX}"
        exit 1
    fi
fi
if test "${MFSERV_NGINX_HTTPS_PORT}" != "null"; then
    if test "${MFSERV_NGINX_HTTPS_PORT}" -le 1024; then
        CAPA=$(getcap "${NGINX}" |grep -E "cap_net_bind_service[+=]ep" 2>/dev/null)
        if test "${CAPA}" = ""; then
            echo_nok
            set_capa_doc https_port "${NGINX}"
            exit 1
        fi
    fi
fi
_make_nginx_conf >/dev/null 2>&1
if test $? -eq 0; then
    echo_ok
else
    echo_nok
    RES=1
    for TMP in $(plugins.list --raw 2>/dev/null); do
        PLUGIN=$(echo "${TMP}" |awk -F '~~~' '{print $1;}')
        PHOME=$(echo "${TMP}" |awk -F '~~~' '{print $4;}')
        TMPOUTPUT="${MFMODULE_RUNTIME_HOME}/tmp/confdebug.$(get_unique_hexa_identifier)"
        _make_nginx_conf "${PHOME}" >"${TMPOUTPUT}" 2>&1
        if test $? -ne 0; then
            echo_bold "=> the plugin ${PLUGIN} seems to break nginx conf"
            echo_bold "   please check your plugin configuration and ${TMPOUTPUT} output"
        else
            rm -f "${TMPOUTPUT}"
        fi
    done
fi
exit ${RES}
