#!/bin/bash

dockerConfigSetupFileWithData()
{
    local app_name="$1"

    if [[ $compose_setup == "default" ]]; then
        local file_name="docker-compose.yml";
    elif [[ $compose_setup == "app" ]]; then
        local file_name="docker-compose.$app_name.yml";
    fi

    local file_path="$containers_dir$app_name"
    local full_file_path="$file_path/$file_name"

    if command -v sqlite3 &> /dev/null && [[ -f "$docker_dir/$db_file" ]]; then
        ###############################################
        # General Updates
        ###############################################
        tagsManagerUpdateUniversalTag "$full_file_path" "TIMEZONE_TAG" "$CFG_TIMEZONE"
        tagsManagerUpdateUniversalTag "$full_file_path" "CATEGORY_TAG" "$app_category"
        tagsManagerUpdateUniversalTag "$full_file_path" "TITLE_TAG" "$app_title"
        # Generic CFG_<APP>_<KEY> -> #LIBREPORTAL|<APP>_<KEY>_TAG| fill. Covers
        # every app-specific config value (secrets included) with no
        # hand-maintained list — the app-specific block further down is only
        # for the few tags that need computed (non-CFG) values.
        tagsProcessorAppConfigValues "$full_file_path" "$app_name"
        tagsProcessorDockerInstallation "$full_file_path" "$CFG_DOCKER_INSTALL_TYPE" "$CFG_DOCKER_INSTALL_USER"
        tagsProcessorSocketConfiguration "$full_file_path" "$CFG_DOCKER_INSTALL_TYPE" "$CFG_DOCKER_INSTALL_USER" "$docker_rooted_socket"
        # Run the container as the same identity that owns its bind-mounted
        # files (the WebUI writes .auth.json into ./frontend). That identity
        # is install-type dependent and already resolved into
        # $docker_install_user by check_install_type.sh: rooted -> the host
        # $sudo_user_name, rootless -> $CFG_DOCKER_INSTALL_USER. Hardcoding a
        # UID (was 1001) breaks wherever that user's UID differs — the
        # container dies with EACCES on first write and never binds its port.
        # No-op for compose files without a USER_TAG.
        local container_user="${docker_install_user:-$sudo_user_name}"
        local install_uid install_gid
        install_uid=$(id -u "$container_user" 2>/dev/null)
        install_gid=$(id -g "$container_user" 2>/dev/null)
        if [[ -n "$install_uid" && -n "$install_gid" ]]; then
            tagsManagerUpdateUniversalTag "$full_file_path" "USER_TAG" "${install_uid}:${install_gid}"
        fi
        tagsProcessorPasswordAndKeyGeneration "$full_file_path"
        tagsProcessorRandomUserGeneration "$full_file_path"
        tagsProcessorHealthcheck "$full_file_path" "$healthcheck"

        ###############################################
        # Public/Traefik Updates
        ###############################################
        # Legacy whole-app middleware (single MIDDLEWARE_TAG). Kept until
        # all apps have been converted to the per-port routers below.
        traefikSetupLabelsMiddlewares "$app_name"
        tagsManagerUpdateUniversalTag "$full_file_path" "MIDDLEWARE_TAG" "$traefik_middlewares"

        # Per-port middleware (MIDDLEWARE_TAG_1, _2, ...). New apps with
        # one router per Traefik-managed port use this — each port can
        # independently enable basic auth via its login_required column,
        # and Authelia takes precedence when installed.
        tagsProcessorPortMiddlewares "$full_file_path" "$app_name"

        # Per-port subdomains (DOMAINSUBNAME_TAG_1, _2, ...): one host per
        # Traefik-managed port, so a container can serve unlimited hosts.
        tagsProcessorPortSubdomains "$full_file_path" "$app_name"

        # Strip (comment out) router blocks for ports that aren't Traefik-managed,
        # so an unfilled DOMAINSUBNAME_DATA_<n> placeholder can never ship.
        tagsProcessorPortRouterBlocks "$full_file_path" "$app_name"

        tagsProcessorTraefikControl "$full_file_path" "$public"
        tagsManagerUpdateUniversalTag "$full_file_path" "DOMAINSUBNAME_TAG" "$host_setup"

        ###############################################
        # Network Updates (IP + Port Systems)
        ###############################################
        tagsManagerUpdateUniversalTag "$full_file_path" "DOCKER_NETWORK_TAG" "$CFG_NETWORK_NAME"
        tagsManagerUpdateUniversalTag "$full_file_path" "PUBLIC_IP_TAG" "$public_ip_v4"
        tagsManagerUpdateUniversalTag "$full_file_path" "NETWORK_SUBNET_TAG" "$CFG_NETWORK_SUBNET"
        tagsManagerUpdateUniversalTag "$full_file_path" "NETWORK_MTU_TAG" "$CFG_NETWORK_MTU"
        ipUpdateComposeTags "$app_name" "$full_file_path"
        portUpdateComposeTags "$app_name" "$full_file_path"
        tagsProcessorTrustedDomains "$full_file_path"
        tagsProcessorAppUrl "$full_file_path" "$app_name" "$public" "$host_setup" "$public_ip_v4"

        ###############################################
        # Mail Server Settings
        ###############################################
        tagsManagerUpdateUniversalTag "$full_file_path" "MAIL_ENABLED_TAG" "$CFG_MAIL_ENABLED"
        tagsManagerUpdateUniversalTag "$full_file_path" "MAIL_HOST_TAG" "$CFG_MAIL_HOST"
        tagsManagerUpdateUniversalTag "$full_file_path" "MAIL_PORT_TAG" "$CFG_MAIL_PORT"
        tagsManagerUpdateUniversalTag "$full_file_path" "MAIL_SECURE_TAG" "$CFG_MAIL_SECURE"
        tagsManagerUpdateUniversalTag "$full_file_path" "MAIL_USERNAME_TAG" "$CFG_MAIL_USERNAME"
        tagsManagerUpdateUniversalTag "$full_file_path" "MAIL_PASSWORD_TAG" "$CFG_MAIL_PASSWORD"
        tagsManagerUpdateUniversalTag "$full_file_path" "MAIL_FROM_TAG" "$CFG_MAIL_FROM"

        ###############################################
        # App Specific
        ###############################################
        if [[ "$app_name" == "pihole" ]]; then
            # PIHOLE_ADMIN_PASSWORD_TAG / PIHOLE_WEB_THEME_TAG are filled by the
            # generic tagsProcessorAppConfigValues (CFG_PIHOLE_ADMIN_PASSWORD /
            # CFG_PIHOLE_WEB_THEME). Only the computed REV_SERVER tags below
            # need an app-specific handler.
            local default_gateway
            local network_cidr
            default_gateway=$(ip route | grep default | awk '{print $3}' | head -1)
            if [[ -z "$default_gateway" ]]; then
                default_gateway="192.168.1.1"  # Fallback
            fi
            network_cidr=$(ip route | grep -v default | grep -E "192\.168|10\.|172\." | awk '{print $1}' | head -1)
            if [[ -z "$network_cidr" ]]; then
                network_cidr="192.168.0.0/16"  # Fallback
            fi
            tagsManagerUpdateUniversalTag "$full_file_path" "PIHOLE_REV_SERVER_TARGET_TAG" "$default_gateway"
            tagsManagerUpdateUniversalTag "$full_file_path" "PIHOLE_REV_SERVER_CIDR_TAG" "$network_cidr"
        elif [[ "$app_name" == "nextcloud" ]]; then
            # Space-separated trusted-domains list. Built as one value so the
            # compose carries one #LIBREPORTAL annotation per line — multiple
            # annotations on a single line confuse the tag manager's
            # placeholder-capture step. Empty fields (e.g. host_setup when
            # no domain is configured) are filtered by Nextcloud's entrypoint.
            tagsManagerUpdateUniversalTag "$full_file_path" "NEXTCLOUD_TRUSTED_DOMAINS_TAG" "$host_setup $public_ip_v4 localhost 127.0.0.1"
        elif [[ "$app_name" == "searxng" ]]; then
            tagsManagerUpdateUniversalTag "$full_file_path" "SEARXNG_THEME_TAG" "$CFG_SEARXNG_THEME"
        elif [[ "$app_name" == "speedtest" ]]; then
            tagsProcessorSpeedtestPass "$full_file_path" "$CFG_SPEEDTEST_PASSWORD_ENABLED" "$CFG_SPEEDTEST_PASSWORD"
        elif [[ "$app_name" == "vaultwarden" ]]; then
            tagsManagerUpdateUniversalTag "$full_file_path" "VAULTWARDEN_ADMIN_TOKEN_TAG" "$CFG_VAULTWARDEN_ADMIN_TOKEN"
            tagsManagerUpdateUniversalTag "$full_file_path" "VAULTWARDEN_SIGNUPS_ALLOWED_TAG" "$CFG_VAULTWARDEN_SIGNUPS_ALLOWED"
        elif [[ "$app_name" == "wireguard" ]]; then
            local bcrypt_hash
            bcrypt_hash=$(hashPassword "$CFG_WIREGUARD_PASSWORD")
            tagsManagerUpdateUniversalTag "$full_file_path" "WIREGUARD_PASSWORD_TAG" "$bcrypt_hash"
        elif [[ "$app_name" == "gluetun" ]]; then
            tagsManagerUpdateUniversalTag "$full_file_path" "GLUETUN_VPN_SERVICE_PROVIDER_TAG" "$CFG_GLUETUN_VPN_SERVICE_PROVIDER"
            tagsManagerUpdateUniversalTag "$full_file_path" "GLUETUN_VPN_TYPE_TAG" "$CFG_GLUETUN_VPN_TYPE"
            tagsManagerUpdateUniversalTag "$full_file_path" "GLUETUN_VPN_COUNTRIES_TAG" "$CFG_GLUETUN_VPN_COUNTRIES"
            tagsManagerUpdateUniversalTag "$full_file_path" "GLUETUN_OPENVPN_USER_TAG" "$CFG_GLUETUN_OPENVPN_USER"
            tagsManagerUpdateUniversalTag "$full_file_path" "GLUETUN_OPENVPN_PASSWORD_TAG" "$CFG_GLUETUN_OPENVPN_PASSWORD"
            tagsManagerUpdateUniversalTag "$full_file_path" "GLUETUN_WIREGUARD_PRIVATE_KEY_TAG" "$CFG_GLUETUN_WIREGUARD_PRIVATE_KEY"
            tagsManagerUpdateUniversalTag "$full_file_path" "GLUETUN_WIREGUARD_ADDRESSES_TAG" "$CFG_GLUETUN_WIREGUARD_ADDRESSES"
            tagsManagerUpdateUniversalTag "$full_file_path" "GLUETUN_HEALTH_TARGETS_TAG"  "${CFG_GLUETUN_HEALTH_TARGETS:-mullvad.net:443,eff.org:443}"
            tagsManagerUpdateUniversalTag "$full_file_path" "GLUETUN_HEALTH_ICMP_IPS_TAG" "${CFG_GLUETUN_HEALTH_ICMP_IPS:-9.9.9.9}"
            tagsProcessorGluetunForwardedPorts
        fi

        ###############################################
        # Network mode (gluetun routing)
        ###############################################
        local network_var="CFG_${app_name^^}_NETWORK"
        local network_mode="${!network_var:-default}"
        tagsProcessorNetworkMode "$full_file_path" "$network_mode"
        if [[ "$network_mode" == "gluetun" && "$app_name" != "gluetun" ]]; then
            tagsProcessorGluetunForwardedPorts
        fi

    else
        isNotice "Database not available, unable to setup app."
    fi
}