# keepass_get
# -----------
# Lee un atributo de una entry del KeePassXC database.
# Atributo por defecto: Password. Tambien admite UserName, URL, Notes, Title, etc.
#
# REQUIERE:
#   - keepassxc-cli instalado
#   - KEEPASS_DB (env): ruta absoluta al .kdbx
#   - master password en pass: `pass insert meta/keepassxc-master`
#     o env KEEPASS_PASSWORD
#   - override pass entry con KEEPASS_MASTER_ENTRY
#
# USO (sourced):
#   source keepass_get.sh
#   pwd=$(keepass_get "Servers/prod-mysql")
#   user=$(keepass_get "Servers/prod-mysql" UserName)
#   url=$(keepass_get "Servers/prod-mysql" URL)

keepass_get() {
    local entry="$1"
    local attr="${2:-Password}"

    if [ -z "$entry" ]; then
        echo "keepass_get: se requiere path de entry" >&2
        return 1
    fi

    local db="${KEEPASS_DB:-}"
    if [ -z "$db" ]; then
        echo "keepass_get: KEEPASS_DB no definida" >&2
        return 1
    fi
    if [ ! -f "$db" ]; then
        echo "keepass_get: db no existe: $db" >&2
        return 1
    fi

    local master
    if [ -n "${KEEPASS_PASSWORD:-}" ]; then
        master="$KEEPASS_PASSWORD"
    else
        master=$(pass show "${KEEPASS_MASTER_ENTRY:-meta/keepassxc-master}" 2>/dev/null | head -n1)
        if [ -z "$master" ]; then
            echo "keepass_get: no master pass (set KEEPASS_PASSWORD o pass insert ${KEEPASS_MASTER_ENTRY:-meta/keepassxc-master})" >&2
            return 1
        fi
    fi

    local value
    value=$(printf '%s\n' "$master" | keepassxc-cli show -q -s -a "$attr" "$db" "$entry" 2>/dev/null)
    if [ $? -ne 0 ] || [ -z "$value" ]; then
        echo "keepass_get: no se pudo leer '$entry' attr '$attr'" >&2
        return 1
    fi

    printf '%s' "$value"
}
