Refactor : Add a helper function findIndexForFRU to
addFruObjectToDbus

Refactoring addFruObjectToDbus function and created a new helper
function findIndexForFRU. Moved this function to fru_utils.cpp
as it is common for all fru-device deamons and avoid code
duplication.

This patch is created based on suggestion on the below patch.
https://gerrit.openbmc.org/c/openbmc/entity-manager/+/51555

TESTED : Built Facebook YosemiteV2 images and loaded
on the target hardware. Verified all the fru's read and write.

Signed-off-by: Kumar Thangavel <thangavel.k@hcl.com>
Change-Id: I2c9b3eb0dfb6050217c3ad459932cda59deea8c8
diff --git a/src/fru_utils.cpp b/src/fru_utils.cpp
index bfcbdba..25cd37e 100644
--- a/src/fru_utils.cpp
+++ b/src/fru_utils.cpp
@@ -941,3 +941,49 @@
 
     return true;
 }
+
+// Get all device dbus path and match path with product name using
+// regular expression and find the device index for all devices.
+
+std::optional<int> findIndexForFRU(
+    boost::container::flat_map<
+        std::pair<size_t, size_t>,
+        std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
+    std::string& productName)
+{
+
+    int highest = -1;
+    bool found = false;
+
+    for (auto const& busIface : dbusInterfaceMap)
+    {
+        std::string path = busIface.second->get_object_path();
+        if (std::regex_match(path, std::regex(productName + "(_\\d+|)$")))
+        {
+
+            // Check if the match named has extra information.
+            found = true;
+            std::smatch baseMatch;
+
+            bool match = std::regex_match(path, baseMatch,
+                                          std::regex(productName + "_(\\d+)$"));
+            if (match)
+            {
+                if (baseMatch.size() == 2)
+                {
+                    std::ssub_match baseSubMatch = baseMatch[1];
+                    std::string base = baseSubMatch.str();
+
+                    int value = std::stoi(base);
+                    highest = (value > highest) ? value : highest;
+                }
+            }
+        }
+    } // end searching objects
+
+    if (!found)
+    {
+        return std::nullopt;
+    }
+    return highest;
+}