#!/bin/bash

# Generic per-app config-value tag processor.
#
# Fills #LIBREPORTAL|<APP>_<KEY>_TAG|... tags in an app's compose from the
# matching CFG_<APP>_<KEY> variable. The tag name is derived mechanically from
# the config key (CFG_GITEA_METRICS_TOKEN -> GITEA_METRICS_TOKEN_TAG), so there
# is no hand-maintained list to drift out of sync — any value an app needs in
# its compose just works by adding the CFG_ key plus the matching tag.
#
# This is the single mechanism for getting a .config value (a preserved-across-
# reinstalls secret, a theme, whatever) into a docker-compose.yml. Secrets in
# particular MUST live in the .config (where the deployed copy is preserved)
# and reach the compose via this — never as a bare RANDOMIZED* placeholder in
# the compose, which re-rolls on every reinstall.
#
# tagsManagerUpdateUniversalTag is a no-op when the tag isn't present in the
# file, so iterating every CFG_<APP>_* var is safe. An undefined key (e.g. on
# an older deployed config that predates a newly-added key) simply isn't listed
# by compgen, leaving its tag as the visible placeholder rather than blanking it.
tagsProcessorAppConfigValues()
{
    local full_file_path="$1"
    local app_name="$2"
    [[ -f "$full_file_path" && -n "$app_name" ]] || return 0

    local app_upper="${app_name^^}"
    app_upper="${app_upper//-/_}"

    local var tag_name
    for var in $(compgen -v | grep -E "^CFG_${app_upper}_" 2>/dev/null); do
        tag_name="${var#CFG_}_TAG"
        tagsManagerUpdateUniversalTag "$full_file_path" "$tag_name" "${!var}"
    done
}
