#!/bin/bash

# Traefik install hooks — interactive email prompt (LE notices), static +
# dynamic config copy, dashboard-access mode wiring (local-only / domain-
# only / public), monitoring toggle on traefik.yml, whitelist + login.

traefik_install_pre()
{
    local app_name="$1"

    if [[ -z "$CFG_TRAEFIK_EMAIL" || "$CFG_TRAEFIK_EMAIL" == "changeme" || "$CFG_TRAEFIK_EMAIL" == "Change-Me" ]]; then
        if [[ "$LIBREPORTAL_NONINTERACTIVE" == "1" ]]; then
            isError "CFG_TRAEFIK_EMAIL not set. Run 'libreportal config update CFG_TRAEFIK_EMAIL=you@example.com' first."
            return 1
        fi
        local traefik_email=""
        while true; do
            isQuestion "Administrator email for LetsEncrypt (cert-expiry notices) : "
            read -p "" traefik_email
            emailValidation "$traefik_email"
            [[ $? -eq 0 ]] && break
            isNotice "Please provide a valid email address."
        done
        updateConfigOption "CFG_TRAEFIK_EMAIL" "$traefik_email"
        sourceScanFiles "libreportal_configs"
    fi
}

traefik_install_post_compose()
{
    local app_name="$1"

    local result
    result=$(createFolders "loud" $docker_install_user "$containers_dir$app_name/etc" "$containers_dir$app_name/etc/certs" "$containers_dir$app_name/etc/dynamic" "$containers_dir$app_name/etc/dynamic/middlewears")
    checkSuccess "Created etc and certs & dynamic Directories"

    result=$(copyResource "$app_name" "traefik.yml" "etc")
    checkSuccess "Copy Traefik configuration file for $app_name"

    result=$(runFileOp sed -i "s|DEBUGLEVEL|$CFG_TRAEFIK_LOGGING|g" "$containers_dir$app_name/etc/traefik.yml")
    checkSuccess "Configured Traefik debug level with: $CFG_TRAEFIK_LOGGING for $app_name"

    configSetupFileWithData $app_name "traefik.yml" "etc"

    # Apply CFG_TRAEFIK_DASHBOARD_ACCESS: rewrites api.insecure + the
    # `traefik:` entrypoint in traefik.yml, and (for local-only) prefixes
    # the compose port mapping with 127.0.0.1: so :8080 binds to loopback.
    local traefik_yml="$containers_dir$app_name/etc/traefik.yml"
    local compose_yml="$containers_dir$app_name/docker-compose.yml"
    local access="${CFG_TRAEFIK_DASHBOARD_ACCESS:-local-only}"

    case "$access" in
        local-only)
            runFileOp sed -i 's|^\(\s*insecure:\s*\).*$|\1true|' "$traefik_yml"
            runFileOp sed -i '/#LIBREPORTAL|PORTS_TAG_1|/ {
                /127\.0\.0\.1:/! s|"\([0-9]\+:[0-9]\+\)"|"127.0.0.1:\1"|
            }' "$compose_yml"
            checkSuccess "Dashboard access: local-only (loopback :8080 + auth-protected domain)"
            ;;
        domain-only)
            runFileOp sed -i 's|^\(\s*insecure:\s*\).*$|\1false|' "$traefik_yml"
            runFileOp sed -i '/^\s*traefik:\s*$/,/^\s*address:\s*:8080\s*$/d' "$traefik_yml"
            checkSuccess "Dashboard access: domain-only (auth-protected via Host route only)"
            ;;
        public)
            runFileOp sed -i 's|^\(\s*insecure:\s*\).*$|\1true|' "$traefik_yml"
            runFileOp sed -i '/#LIBREPORTAL|PORTS_TAG_1|/ s|"127\.0\.0\.1:\([0-9]\+:[0-9]\+\)"|"\1"|' "$compose_yml"
            checkSuccess "Dashboard access: public (unauthenticated :8080 on all interfaces — legacy)"
            ;;
        *)
            isNotice "Unknown CFG_TRAEFIK_DASHBOARD_ACCESS='$access'; leaving traefik.yml at defaults."
            ;;
    esac

    # Traefik's metrics block lives in traefik.yml; toggle that here. The
    # driver already toggled docker-compose.yml.
    monitoringToggleAppConfig "$app_name" "etc/traefik.yml"

    result=$(copyResource "$app_name" "config.yml" "etc/dynamic")
    checkSuccess "Copy Traefik Dynamic config.yml configuration file for $app_name"

    result=$(runFileOp sed -i "s|ERRORWEBSITE|$CFG_TRAEFIK_404_SITE|g" "$containers_dir$app_name/etc/dynamic/config.yml")
    checkSuccess "Configured Traefik error website with URL: $CFG_TRAEFIK_404_SITE for $app_name"

    configSetupFileWithData $app_name "config.yml" "etc/dynamic"

    result=$(copyResource "$app_name" "whitelist.yml" "etc/dynamic")
    checkSuccess "Copy Traefik Dynamic whitelist.yml configuration file for $app_name"

    result=$(copyResource "$app_name" "protectionauth.yml" "etc/dynamic/middlewears")
    checkSuccess "Copy Traefik Dynamic protectionauth.yml configuration file for $app_name"

    traefikUpdateWhitelist

    result=$(copyResource "$app_name" "tls.yml" "etc/dynamic")
    checkSuccess "Copy Traefik Dynamic tls.yml configuration file for $app_name"

    traefikSetupLoginCredentials
}
