# keepass_generate
# ----------------
# Genera un password aleatorio, lo almacena en una entry nueva del KeePassXC database
# y lo imprime a stdout.
#
# REQUIERE:
#   - keepassxc-cli instalado
#   - KEEPASS_DB (env): ruta absoluta al .kdbx
#   - master password en pass o env KEEPASS_PASSWORD
#
# USO (sourced):
#   source keepass_generate.sh
#   pwd=$(keepass_generate "Servers/new-server")
#   pwd=$(keepass_generate "Servers/new-server" 32)
#   pwd=$(keepass_generate "Servers/new-server" 32 "admin" "https://new.example.com")

keepass_generate() {
    local entry="$1"
    local length="${2:-24}"
    local username="${3:-}"
    local url="${4:-}"

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

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

    local pwd
    pwd=$(keepassxc-cli generate -L "$length" -l -U -n -s 2>/dev/null)
    if [ -z "$pwd" ]; then
        echo "keepass_generate: fallo al generar password" >&2
        return 1
    fi

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

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

    printf '%s' "$pwd"
}
