#!/bin/bash

# Universal user/credential adapter for app tools.
#
# Each app declares an auth profile in its config:
#   CFG_<APP>_AUTH_PROFILE = single_password | user_password | multi_user | none
#
# And implements adapter functions in containers/<app>/scripts/<app>_auth.sh:
#   authAdapter_<app>_setPassword "$user" "$password"
#   authAdapter_<app>_createUser  "$user" "$password" "$email" "$isAdmin"
#   authAdapter_<app>_listUsers
#
# Tool wrappers call authAdapterCall <app> <method> <args...>. The
# dispatcher checks the function exists, runs it, and refreshes apps.json
# via webuiPatchAppConfigJson so new admin creds surface in the WebUI.

authAdapterCanDo() {
    local app="$1" method="$2"
    declare -F "authAdapter_${app}_${method}" >/dev/null 2>&1
}

authAdapterCall() {
    local app="$1" method="$2"
    shift 2
    local fn="authAdapter_${app}_${method}"
    if ! declare -F "$fn" >/dev/null 2>&1; then
        isError "Auth adapter for '$app' does not implement '$method'."
        return 1
    fi
    "$fn" "$@"
    local rc=$?
    if (( rc == 0 )) && declare -F webuiPatchAppConfigJson >/dev/null 2>&1; then
        webuiPatchAppConfigJson "$app" >/dev/null 2>&1 || true
    fi
    return $rc
}

# Persist a value to CFG_<APP>_<KEY> in the per-app config file.
authPersistCfg() {
    local app="$1" key="$2" value="$3"
    local cfg="${containers_dir}${app}/${app}.config"
    [[ ! -f "$cfg" ]] && cfg="${install_containers_dir}/${app}/${app}.config"
    [[ ! -f "$cfg" ]] && return 1
    updateConfigOption "CFG_${app^^}_${key}" "$value" "$cfg"
}

# Read a tool-modal arg (pipe-encoded) and unescape pipes.
authToolArg() {
    local v
    v=$(toolArgsGet "$1" "$2") || true
    printf '%s' "${v//%7C/|}"
}
