#!/bin/bash

authAdapter_adguard_setPassword() {
    local user="$1" password="$2"
    user="${user:-${CFG_ADGUARD_ADMIN_USER:-admin}}"
    [[ -z "$password" ]] && password=$(generateRandomPassword)

    local yaml="${containers_dir}adguard/conf/AdGuardHome.yaml"
    [[ ! -f "$yaml" ]] && { isError "AdGuardHome.yaml not found at $yaml."; return 1; }
    if ! command -v htpasswd >/dev/null 2>&1; then
        isError "htpasswd is required to bcrypt the new password."
        return 1
    fi

    local bcrypt
    bcrypt=$(htpasswd -bnBC 10 "" "$password" | tr -d ':\n')
    [[ -z "$bcrypt" ]] && { isError "bcrypt failed."; return 1; }

    # The yaml is owned by the in-container uid, so the rewrite runs in the
    # root-owned appcfg helper (fixed path, validated user + bcrypt).
    if ! runAppCfg adguard-auth "$user" "$bcrypt"; then
        isError "Could not update AdGuardHome.yaml (no users password line, or invalid input)."
        return 1
    fi

    authPersistCfg adguard ADMIN_USER "$user"
    authPersistCfg adguard ADMIN_PASSWORD "$password"
    dockerComposeRestart adguard
    isSuccessful "AdGuard admin set. User: $user — Password: $password"
}
