BMC: Update u-boot environment variable based on lowest priority

- If a BMC is set to the lowest priority then update the u-boot
  environment variables so that that system boots from that version
  on the next reboot.

Resolves openbmc/openbmc#2284

Change-Id: If0b67b07496f602fa06607bd0685d6394cb8d9fd
Signed-off-by: Saqib Khan <khansa@us.ibm.com>
diff --git a/activation.cpp b/activation.cpp
index 9d2ba4a..d7f9e24 100644
--- a/activation.cpp
+++ b/activation.cpp
@@ -2,6 +2,8 @@
 #include "item_updater.hpp"
 #include "config.h"
 #include "serialize.hpp"
+#include <phosphor-logging/log.hpp>
+
 
 namespace phosphor
 {
@@ -12,6 +14,8 @@
 
 namespace softwareServer = sdbusplus::xyz::openbmc_project::Software::server;
 
+using namespace phosphor::logging;
+
 void Activation::subscribeToSystemdSignals()
 {
     auto method = this->bus.new_method_call(SYSTEMD_BUSNAME,
@@ -149,11 +153,41 @@
 
 uint8_t RedundancyPriority::priority(uint8_t value)
 {
-    parent.parent.freePriority(value);
+    parent.parent.freePriority(value, parent.versionId);
     storeToFile(parent.versionId, value);
+
+    if(parent.parent.isLowestPriority(value))
+    {
+        parent.updateUbootEnvVars();
+    }
+
     return softwareServer::RedundancyPriority::priority(value);
 }
 
+// TODO: openbmc/openbmc#2369 Add recovery policy to updateubootvars
+//       unit template.
+// TODO: openbmc/openbmc#2370 Call StartUnit synchronously to handle
+//       Errors more gracefully.
+void Activation::updateUbootEnvVars()
+{
+    auto method = bus.new_method_call(
+            SYSTEMD_BUSNAME,
+            SYSTEMD_PATH,
+            SYSTEMD_INTERFACE,
+            "StartUnit");
+    auto updateEnvVarsFile = "obmc-flash-bmc-updateubootvars@" + versionId +
+            ".service";
+    method.append(updateEnvVarsFile, "replace");
+    auto result = bus.call(method);
+
+    //Check that the bus call didn't result in an error
+    if (result.is_method_error())
+    {
+        log<level::ERR>("Failed to update u-boot env variables",
+                        entry(" %s", SYSTEMD_INTERFACE));
+    }
+}
+
 void Activation::unitStateChange(sdbusplus::message::message& msg)
 {
     if (softwareServer::Activation::activation() !=