# keepass_set
# -----------
# Crea o sobreescribe una entry en el KeePassXC database.
# Auto-detecta si existe (edit) o no (add).
#
# REQUIERE:
#   - keepassxc-cli instalado
#   - KEEPASS_DB (env): ruta absoluta al .kdbx
#   - master password en pass o env KEEPASS_PASSWORD
#
# USO (sourced):
#   source keepass_set.sh
#   keepass_set "Servers/prod-mysql" "secret123"
#   keepass_set "Servers/prod-mysql" "secret123" "admin" "https://prod.example.com"

keepass_set() {
    local entry="$1"
    local password="$2"
    local username="${3:-}"
    local url="${4:-}"

    if [ -z "$entry" ] || [ -z "$password" ]; then
        echo "keepass_set: se requieren entry y password" >&2
        return 1
    fi

    local db="${KEEPASS_DB:-}"
    if [ -z "$db" ] || [ ! -f "$db" ]; then
        echo "keepass_set: KEEPASS_DB no valida: $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_set: no master pass" >&2
            return 1
        fi
    fi

    local cmd="add"
    if printf '%s\n' "$master" | keepassxc-cli show -q "$db" "$entry" >/dev/null 2>&1; then
        cmd="edit"
    fi

    local args=(-q -p)
    [ -n "$username" ] && args+=(-u "$username")
    [ -n "$url" ] && args+=(--url "$url")

    printf '%s\n%s\n' "$master" "$password" | keepassxc-cli "$cmd" "${args[@]}" "$db" "$entry" >/dev/null 2>&1
    if [ $? -ne 0 ]; then
        echo "keepass_set: fallo al $cmd '$entry'" >&2
        return 1
    fi
}
