cleanup: Move em only utils code into em directory

More separation of code for improvement of repository maintainability.

Change-Id: I4e77b472355066483cf646cdcd29e7ed660294a3
Signed-off-by: Christopher Meis <christopher.meis@9elements.com>
diff --git a/src/entity_manager/configuration.cpp b/src/entity_manager/configuration.cpp
index 5663ec8..8646f57 100644
--- a/src/entity_manager/configuration.cpp
+++ b/src/entity_manager/configuration.cpp
@@ -1,7 +1,7 @@
 #include "configuration.hpp"
 
-#include "../utils.hpp"
 #include "perform_probe.hpp"
+#include "utils.hpp"
 
 #include <nlohmann/json.hpp>
 #include <valijson/adapters/nlohmann_json_adapter.hpp>
diff --git a/src/entity_manager/dbus_interface.cpp b/src/entity_manager/dbus_interface.cpp
index f0c904c..5c1788b 100644
--- a/src/entity_manager/dbus_interface.cpp
+++ b/src/entity_manager/dbus_interface.cpp
@@ -1,11 +1,12 @@
 #include "dbus_interface.hpp"
 
-#include "../utils.hpp"
 #include "perform_probe.hpp"
+#include "utils.hpp"
 
 #include <boost/algorithm/string/case_conv.hpp>
 #include <boost/container/flat_map.hpp>
 
+#include <fstream>
 #include <regex>
 #include <string>
 #include <vector>
diff --git a/src/entity_manager/entity_manager.cpp b/src/entity_manager/entity_manager.cpp
index 5aa5380..2b65604 100644
--- a/src/entity_manager/entity_manager.cpp
+++ b/src/entity_manager/entity_manager.cpp
@@ -24,6 +24,7 @@
 #include "overlay.hpp"
 #include "perform_scan.hpp"
 #include "topology.hpp"
+#include "utils.hpp"
 
 #include <boost/algorithm/string/case_conv.hpp>
 #include <boost/algorithm/string/classification.hpp>
@@ -40,14 +41,12 @@
 #include <sdbusplus/asio/connection.hpp>
 #include <sdbusplus/asio/object_server.hpp>
 
-#include <charconv>
 #include <filesystem>
 #include <fstream>
 #include <functional>
 #include <iostream>
 #include <map>
 #include <regex>
-#include <variant>
 constexpr const char* tempConfigDir = "/tmp/configuration/";
 constexpr const char* lastConfiguration = "/tmp/configuration/last.json";
 
@@ -376,7 +375,7 @@
         return;
     }
 
-    if (!isPowerOn() && scannedPowerOff)
+    if (!em_utils::isPowerOn() && scannedPowerOff)
     {
         return;
     }
@@ -389,7 +388,7 @@
                 return;
             }
 
-            bool powerOff = !isPowerOn();
+            bool powerOff = !em_utils::isPowerOn();
             for (const auto& [name, device] : lastJson.items())
             {
                 pruneDevice(systemConfiguration, powerOff, scannedPowerOff,
@@ -515,7 +514,7 @@
              missingConfigurations]() {
                 // this is something that since ac has been applied to the bmc
                 // we saw, and we no longer see it
-                bool powerOff = !isPowerOn();
+                bool powerOff = !em_utils::isPowerOn();
                 for (const auto& [name, device] :
                      missingConfigurations->items())
                 {
@@ -660,7 +659,7 @@
     });
     dbus_interface::tryIfaceInitialize(entityIface);
 
-    if (fwVersionIsSame())
+    if (em_utils::fwVersionIsSame())
     {
         if (std::filesystem::is_regular_file(
                 configuration::currentConfiguration))
@@ -701,7 +700,7 @@
 
     // some boards only show up after power is on, we want to not say they are
     // removed until the same state happens
-    setupPowerMatch(systemBus);
+    em_utils::setupPowerMatch(systemBus);
 
     io.run();
 
diff --git a/src/entity_manager/expression.cpp b/src/entity_manager/expression.cpp
new file mode 100644
index 0000000..377bdd8
--- /dev/null
+++ b/src/entity_manager/expression.cpp
@@ -0,0 +1,127 @@
+/*
+// Copyright (c) 2017 Intel Corporation
+// Copyright (c) 2022 IBM Corp.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+*/
+
+#include "expression.hpp"
+
+#include <iostream>
+#include <stdexcept>
+
+namespace expression
+{
+std::optional<Operation> parseOperation(std::string& op)
+{
+    if (op == "+")
+    {
+        return Operation::addition;
+    }
+    if (op == "-")
+    {
+        return Operation::subtraction;
+    }
+    if (op == "*")
+    {
+        return Operation::multiplication;
+    }
+    if (op == R"(%)")
+    {
+        return Operation::modulo;
+    }
+    if (op == R"(/)")
+    {
+        return Operation::division;
+    }
+
+    return std::nullopt;
+}
+
+int evaluate(int a, Operation op, int b)
+{
+    switch (op)
+    {
+        case Operation::addition:
+        {
+            return a + b;
+        }
+        case Operation::subtraction:
+        {
+            return a - b;
+        }
+        case Operation::multiplication:
+        {
+            return a * b;
+        }
+        case Operation::division:
+        {
+            if (b == 0)
+            {
+                throw std::runtime_error(
+                    "Math error: Attempted to divide by Zero\n");
+            }
+            return a / b;
+        }
+        case Operation::modulo:
+        {
+            if (b == 0)
+            {
+                throw std::runtime_error(
+                    "Math error: Attempted to divide by Zero\n");
+            }
+            return a % b;
+        }
+
+        default:
+            throw std::invalid_argument("Unrecognised operation");
+    }
+}
+
+int evaluate(int substitute, std::vector<std::string>::iterator curr,
+             std::vector<std::string>::iterator& end)
+{
+    bool isOperator = true;
+    std::optional<Operation> next = Operation::addition;
+
+    for (; curr != end; curr++)
+    {
+        if (isOperator)
+        {
+            next = expression::parseOperation(*curr);
+            if (!next)
+            {
+                break;
+            }
+        }
+        else
+        {
+            try
+            {
+                int constant = std::stoi(*curr);
+                substitute = evaluate(substitute, *next, constant);
+            }
+            catch (const std::invalid_argument&)
+            {
+                std::cerr << "Parameter not supported for templates " << *curr
+                          << "\n";
+                continue;
+            }
+        }
+        isOperator = !isOperator;
+    }
+
+    end = curr;
+    return substitute;
+}
+} // namespace expression
diff --git a/src/entity_manager/expression.hpp b/src/entity_manager/expression.hpp
new file mode 100644
index 0000000..6677b2d
--- /dev/null
+++ b/src/entity_manager/expression.hpp
@@ -0,0 +1,39 @@
+/*
+// Copyright (c) 2017 Intel Corporation
+// Copyright (c) 2022 IBM Corp.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+*/
+
+#pragma once
+
+#include <optional>
+#include <string>
+#include <vector>
+
+namespace expression
+{
+enum class Operation
+{
+    addition,
+    division,
+    multiplication,
+    subtraction,
+    modulo,
+};
+
+std::optional<Operation> parseOperation(const std::string& op);
+int evaluate(int a, Operation op, int b);
+int evaluate(int substitute, std::vector<std::string>::iterator curr,
+             std::vector<std::string>::iterator& end);
+} // namespace expression
diff --git a/src/entity_manager/meson.build b/src/entity_manager/meson.build
index 005a0d0..622cf53 100644
--- a/src/entity_manager/meson.build
+++ b/src/entity_manager/meson.build
@@ -2,12 +2,13 @@
     'entity-manager',
     'entity_manager.cpp',
     'configuration.cpp',
-    '../expression.cpp',
+    'expression.cpp',
     'dbus_interface.cpp',
     'perform_scan.cpp',
     'perform_probe.cpp',
     'overlay.cpp',
     'topology.cpp',
+    'utils.cpp',
     '../utils.cpp',
     cpp_args: cpp_args + ['-DBOOST_ASIO_DISABLE_THREADS'],
     dependencies: [
diff --git a/src/entity_manager/overlay.cpp b/src/entity_manager/overlay.cpp
index 8b52fb9..1a389fb 100644
--- a/src/entity_manager/overlay.cpp
+++ b/src/entity_manager/overlay.cpp
@@ -17,8 +17,8 @@
 
 #include "overlay.hpp"
 
-#include "../utils.hpp"
 #include "devices.hpp"
+#include "utils.hpp"
 
 #include <boost/algorithm/string/predicate.hpp>
 #include <boost/asio/io_context.hpp>
@@ -30,6 +30,7 @@
 #include <phosphor-logging/lg2.hpp>
 
 #include <filesystem>
+#include <fstream>
 #include <iomanip>
 #include <iostream>
 #include <regex>
diff --git a/src/entity_manager/perform_probe.cpp b/src/entity_manager/perform_probe.cpp
index d7dcd8a..24fdd71 100644
--- a/src/entity_manager/perform_probe.cpp
+++ b/src/entity_manager/perform_probe.cpp
@@ -16,12 +16,12 @@
 /// \file perform_probe.cpp
 #include "perform_probe.hpp"
 
-#include "entity_manager.hpp"
 #include "perform_scan.hpp"
 
 #include <boost/algorithm/string/replace.hpp>
 #include <phosphor-logging/lg2.hpp>
 
+#include <iostream>
 #include <regex>
 #include <utility>
 
diff --git a/src/entity_manager/perform_scan.cpp b/src/entity_manager/perform_scan.cpp
index d05312d..167490b 100644
--- a/src/entity_manager/perform_scan.cpp
+++ b/src/entity_manager/perform_scan.cpp
@@ -16,8 +16,8 @@
 /// \file perform_scan.cpp
 #include "perform_scan.hpp"
 
-#include "entity_manager.hpp"
 #include "perform_probe.hpp"
+#include "utils.hpp"
 
 #include <boost/algorithm/string/predicate.hpp>
 #include <boost/asio/steady_timer.hpp>
@@ -26,6 +26,7 @@
 #include <phosphor-logging/lg2.hpp>
 
 #include <charconv>
+#include <iostream>
 
 /* Hacks from splitting entity_manager.cpp */
 // NOLINTBEGIN(cppcoreguidelines-avoid-non-const-global-variables)
@@ -428,8 +429,8 @@
 {
     nlohmann::json copyForName = {{"Name", nameTemplate}};
     nlohmann::json::iterator copyIt = copyForName.begin();
-    std::optional<std::string> replaceVal =
-        templateCharReplace(copyIt, dbusObject, foundDeviceIdx, replaceStr);
+    std::optional<std::string> replaceVal = em_utils::templateCharReplace(
+        copyIt, dbusObject, foundDeviceIdx, replaceStr);
 
     if (!replaceStr && replaceVal)
     {
@@ -438,7 +439,8 @@
             replaceStr = replaceVal;
             copyForName = {{"Name", nameTemplate}};
             copyIt = copyForName.begin();
-            templateCharReplace(copyIt, dbusObject, foundDeviceIdx, replaceStr);
+            em_utils::templateCharReplace(copyIt, dbusObject, foundDeviceIdx,
+                                          replaceStr);
         }
     }
 
@@ -532,8 +534,8 @@
         {
             if (keyPair.key() != "Name")
             {
-                templateCharReplace(keyPair, dbusObject, foundDeviceIdx,
-                                    replaceStr);
+                em_utils::templateCharReplace(keyPair, dbusObject,
+                                              foundDeviceIdx, replaceStr);
             }
         }
 
@@ -553,8 +555,8 @@
             for (auto keyPair = expose.begin(); keyPair != expose.end();
                  keyPair++)
             {
-                templateCharReplace(keyPair, dbusObject, foundDeviceIdx,
-                                    replaceStr);
+                em_utils::templateCharReplace(keyPair, dbusObject,
+                                              foundDeviceIdx, replaceStr);
 
                 applyExposeActions(_systemConfiguration, recordName, expose,
                                    keyPair);
diff --git a/src/entity_manager/utils.cpp b/src/entity_manager/utils.cpp
new file mode 100644
index 0000000..b169bce
--- /dev/null
+++ b/src/entity_manager/utils.cpp
@@ -0,0 +1,270 @@
+#include "utils.hpp"
+
+#include "../variant_visitors.hpp"
+#include "expression.hpp"
+
+#include <boost/algorithm/string/classification.hpp>
+#include <boost/algorithm/string/find.hpp>
+#include <boost/algorithm/string/predicate.hpp>
+#include <boost/algorithm/string/replace.hpp>
+#include <boost/algorithm/string/split.hpp>
+#include <sdbusplus/bus/match.hpp>
+
+#include <fstream>
+#include <iostream>
+
+namespace em_utils
+{
+
+// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
+static bool powerStatusOn = false;
+// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
+static std::unique_ptr<sdbusplus::bus::match_t> powerMatch = nullptr;
+
+constexpr const char* templateChar = "$";
+
+bool isPowerOn()
+{
+    if (!powerMatch)
+    {
+        throw std::runtime_error("Power Match Not Created");
+    }
+    return powerStatusOn;
+}
+
+void setupPowerMatch(const std::shared_ptr<sdbusplus::asio::connection>& conn)
+{
+    powerMatch = std::make_unique<sdbusplus::bus::match_t>(
+        static_cast<sdbusplus::bus_t&>(*conn),
+        "type='signal',interface='" + std::string(properties::interface) +
+            "',path='" + std::string(power::path) + "',arg0='" +
+            std::string(power::interface) + "'",
+        [](sdbusplus::message_t& message) {
+            std::string objectName;
+            boost::container::flat_map<std::string, std::variant<std::string>>
+                values;
+            message.read(objectName, values);
+            auto findState = values.find(power::property);
+            if (findState != values.end())
+            {
+                powerStatusOn = boost::ends_with(
+                    std::get<std::string>(findState->second), "Running");
+            }
+        });
+
+    conn->async_method_call(
+        [](boost::system::error_code ec,
+           const std::variant<std::string>& state) {
+            if (ec)
+            {
+                return;
+            }
+            powerStatusOn =
+                boost::ends_with(std::get<std::string>(state), "Running");
+        },
+        power::busname, power::path, properties::interface, properties::get,
+        power::interface, power::property);
+}
+
+bool fwVersionIsSame()
+{
+    std::ifstream version(versionFile);
+    if (!version.good())
+    {
+        std::cerr << "Can't read " << versionFile << "\n";
+        return false;
+    }
+
+    std::string versionData;
+    std::string line;
+    while (std::getline(version, line))
+    {
+        versionData += line;
+    }
+
+    std::string expectedHash =
+        std::to_string(std::hash<std::string>{}(versionData));
+
+    std::filesystem::create_directory(configurationOutDir);
+    std::ifstream hashFile(versionHashFile);
+    if (hashFile.good())
+    {
+        std::string hashString;
+        hashFile >> hashString;
+
+        if (expectedHash == hashString)
+        {
+            return true;
+        }
+        hashFile.close();
+    }
+
+    std::ofstream output(versionHashFile);
+    output << expectedHash;
+    return false;
+}
+
+// Replaces the template character like the other version of this function,
+// but checks all properties on all interfaces provided to do the substitution
+// with.
+std::optional<std::string> templateCharReplace(
+    nlohmann::json::iterator& keyPair, const DBusObject& object,
+    const size_t index, const std::optional<std::string>& replaceStr)
+{
+    for (const auto& [_, interface] : object)
+    {
+        auto ret = templateCharReplace(keyPair, interface, index, replaceStr);
+        if (ret)
+        {
+            return ret;
+        }
+    }
+    return std::nullopt;
+}
+
+// finds the template character (currently set to $) and replaces the value with
+// the field found in a dbus object i.e. $ADDRESS would get populated with the
+// ADDRESS field from a object on dbus
+std::optional<std::string> templateCharReplace(
+    nlohmann::json::iterator& keyPair, const DBusInterface& interface,
+    const size_t index, const std::optional<std::string>& replaceStr)
+{
+    std::optional<std::string> ret = std::nullopt;
+
+    if (keyPair.value().type() == nlohmann::json::value_t::object ||
+        keyPair.value().type() == nlohmann::json::value_t::array)
+    {
+        for (auto nextLayer = keyPair.value().begin();
+             nextLayer != keyPair.value().end(); nextLayer++)
+        {
+            templateCharReplace(nextLayer, interface, index, replaceStr);
+        }
+        return ret;
+    }
+
+    std::string* strPtr = keyPair.value().get_ptr<std::string*>();
+    if (strPtr == nullptr)
+    {
+        return ret;
+    }
+
+    boost::replace_all(*strPtr, std::string(templateChar) + "index",
+                       std::to_string(index));
+    if (replaceStr)
+    {
+        boost::replace_all(*strPtr, *replaceStr, std::to_string(index));
+    }
+
+    for (const auto& [propName, propValue] : interface)
+    {
+        std::string templateName = templateChar + propName;
+        boost::iterator_range<std::string::const_iterator> find =
+            boost::ifind_first(*strPtr, templateName);
+        if (!find)
+        {
+            continue;
+        }
+
+        size_t start = find.begin() - strPtr->begin();
+
+        // check for additional operations
+        if ((start == 0U) && find.end() == strPtr->end())
+        {
+            std::visit([&](auto&& val) { keyPair.value() = val; }, propValue);
+            return ret;
+        }
+
+        constexpr const std::array<char, 5> mathChars = {'+', '-', '%', '*',
+                                                         '/'};
+        size_t nextItemIdx = start + templateName.size() + 1;
+
+        if (nextItemIdx > strPtr->size() ||
+            std::find(mathChars.begin(), mathChars.end(),
+                      strPtr->at(nextItemIdx)) == mathChars.end())
+        {
+            std::string val = std::visit(VariantToStringVisitor(), propValue);
+            boost::ireplace_all(*strPtr, templateName, val);
+            continue;
+        }
+
+        // save the prefix
+        std::string prefix = strPtr->substr(0, start);
+
+        // operate on the rest
+        std::string end = strPtr->substr(nextItemIdx);
+
+        std::vector<std::string> split;
+        boost::split(split, end, boost::is_any_of(" "));
+
+        // need at least 1 operation and number
+        if (split.size() < 2)
+        {
+            std::cerr << "Syntax error on template replacement of " << *strPtr
+                      << "\n";
+            for (const std::string& data : split)
+            {
+                std::cerr << data << " ";
+            }
+            std::cerr << "\n";
+            continue;
+        }
+
+        // we assume that the replacement is a number, because we can
+        // only do math on numbers.. we might concatenate strings in the
+        // future, but thats later
+        int number = std::visit(VariantToIntVisitor(), propValue);
+        auto exprBegin = split.begin();
+        auto exprEnd = split.end();
+
+        number = expression::evaluate(number, exprBegin, exprEnd);
+
+        std::string replaced(find.begin(), find.end());
+        while (exprBegin != exprEnd)
+        {
+            replaced.append(" ").append(*exprBegin++);
+        }
+        ret = replaced;
+
+        std::string result = prefix + std::to_string(number);
+        while (exprEnd != split.end())
+        {
+            result.append(" ").append(*exprEnd++);
+        }
+        keyPair.value() = result;
+
+        // We probably just invalidated the pointer abovei,
+        // reset and continue to handle multiple templates
+        strPtr = keyPair.value().get_ptr<std::string*>();
+        if (strPtr == nullptr)
+        {
+            break;
+        }
+    }
+
+    strPtr = keyPair.value().get_ptr<std::string*>();
+    if (strPtr == nullptr)
+    {
+        return ret;
+    }
+
+    std::string_view strView = *strPtr;
+    int base = 10;
+    if (boost::starts_with(strView, "0x"))
+    {
+        strView.remove_prefix(2);
+        base = 16;
+    }
+
+    uint64_t temp = 0;
+    const char* strDataEndPtr = strView.data() + strView.size();
+    const std::from_chars_result res =
+        std::from_chars(strView.data(), strDataEndPtr, temp, base);
+    if (res.ec == std::errc{} && res.ptr == strDataEndPtr)
+    {
+        keyPair.value() = temp;
+    }
+
+    return ret;
+}
+
+} // namespace em_utils
diff --git a/src/entity_manager/utils.hpp b/src/entity_manager/utils.hpp
new file mode 100644
index 0000000..ac72c80
--- /dev/null
+++ b/src/entity_manager/utils.hpp
@@ -0,0 +1,50 @@
+#pragma once
+
+#include <boost/asio/io_context.hpp>
+#include <boost/container/flat_map.hpp>
+#include <nlohmann/json.hpp>
+#include <sdbusplus/asio/connection.hpp>
+
+// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
+extern boost::asio::io_context io;
+
+using DBusValueVariant =
+    std::variant<std::string, int64_t, uint64_t, double, int32_t, uint32_t,
+                 int16_t, uint16_t, uint8_t, bool, std::vector<uint8_t>>;
+using DBusInterface = boost::container::flat_map<std::string, DBusValueVariant>;
+using DBusObject = boost::container::flat_map<std::string, DBusInterface>;
+
+constexpr const char* configurationOutDir = "/var/configuration/";
+constexpr const char* versionHashFile = "/var/configuration/version";
+constexpr const char* versionFile = "/etc/os-release";
+
+namespace em_utils
+{
+
+namespace properties
+{
+constexpr const char* interface = "org.freedesktop.DBus.Properties";
+constexpr const char* get = "Get";
+} // namespace properties
+
+namespace power
+{
+const static constexpr char* busname = "xyz.openbmc_project.State.Host";
+const static constexpr char* interface = "xyz.openbmc_project.State.Host";
+const static constexpr char* path = "/xyz/openbmc_project/state/host0";
+const static constexpr char* property = "CurrentHostState";
+} // namespace power
+
+bool isPowerOn();
+void setupPowerMatch(const std::shared_ptr<sdbusplus::asio::connection>& conn);
+bool fwVersionIsSame();
+
+std::optional<std::string> templateCharReplace(
+    nlohmann::json::iterator& keyPair, const DBusObject& object, size_t index,
+    const std::optional<std::string>& replaceStr = std::nullopt);
+
+std::optional<std::string> templateCharReplace(
+    nlohmann::json::iterator& keyPair, const DBusInterface& interface,
+    size_t index, const std::optional<std::string>& replaceStr = std::nullopt);
+
+} // namespace em_utils