ethernet_interface: Fix u-boot MAC environment variable

Previously, no matter what interface we were changing we would always
set the MAC address for eth0 on the next boot. There is a loose
mapping between ethaddr <-> eth0 and eth1addr <-> eth1 for storing the
MAC address in the u-boot environment.

https://www.denx.de/wiki/view/DULG/UBootEnvVariables

Change-Id: I90f608a876c03e74c32561cf24947cfc44da0e34
Signed-off-by: William A. Kennington III <wak@google.com>
diff --git a/util.cpp b/util.cpp
index b01d644..f1fd4cd 100644
--- a/util.cpp
+++ b/util.cpp
@@ -9,6 +9,8 @@
 #include <sys/wait.h>
 
 #include <algorithm>
+#include <cstdlib>
+#include <cstring>
 #include <experimental/filesystem>
 #include <iostream>
 #include <list>
@@ -382,6 +384,32 @@
     }
 }
 
+std::optional<std::string> interfaceToUbootEthAddr(const char* intf)
+{
+    constexpr char ethPrefix[] = "eth";
+    constexpr size_t ethPrefixLen = sizeof(ethPrefix) - 1;
+    if (strncmp(ethPrefix, intf, ethPrefixLen) != 0)
+    {
+        return std::nullopt;
+    }
+    const auto intfSuffix = intf + ethPrefixLen;
+    if (intfSuffix[0] == '\0')
+    {
+        return std::nullopt;
+    }
+    char* end;
+    unsigned long idx = strtoul(intfSuffix, &end, 10);
+    if (end[0] != '\0')
+    {
+        return std::nullopt;
+    }
+    if (idx == 0)
+    {
+        return "ethaddr";
+    }
+    return "eth" + std::to_string(idx) + "addr";
+}
+
 bool getDHCPValue(const std::string& confDir, const std::string& intf)
 {
     bool dhcp = false;