#!/bin/bash

traefikSetupLabelsMiddlewares() 
{
    local app_name="$1"
    local middleware_entries=()

    # Default chain unless the app opts out via its per-app hook
    # (containers/<app>/scripts/<app>_traefik.sh defines
    # appTraefikSkipsDefaultMiddleware_<app>).
    if ! declare -F "appTraefikSkipsDefaultMiddleware_${app_name}" >/dev/null 2>&1; then
        middleware_entries+=("default@file")
    fi

    # App-specific extras (e.g. onlyoffice-headers) via the per-app hook.
    if declare -F "appTraefikExtraMiddlewares_${app_name}" >/dev/null 2>&1; then
        local _mw
        while IFS= read -r _mw; do
            [[ -n "$_mw" ]] && middleware_entries+=("$_mw")
        done < <("appTraefikExtraMiddlewares_${app_name}")
    fi

    if [[ "$authelia_setup" == "true" && "$whitelist" == "true" ]]; then
        middleware_entries+=("global-ipwhitelist@file")
        if [[ $(dockerCheckAppInstalled "authelia" "docker") == "installed" ]]; then
            middleware_entries+=("authelia@docker")
        fi
    elif [[ "$authelia_setup" == "true" && "$whitelist" == "false" ]]; then
        if [[ $(dockerCheckAppInstalled "authelia" "docker") == "installed" ]]; then
            middleware_entries+=("authelia@docker")
        fi
    elif [[ "$authelia_setup" == "false" && "$whitelist" == "true" ]]; then
        middleware_entries+=("global-ipwhitelist@file")
    fi

    local middlewares_string="$(IFS=,; echo "${middleware_entries[*]}")"
    traefik_middlewares=$middlewares_string
}
