classes-systemd: Add format strings to unit files

Add functionality for enabling python str.format()ing
of systemd unit files.

Add a variable name to SYSTEMD_SUBSTITUTIONS_${unit}
and its value will be substituted into any matching
python string {format}'s in the unit file during install.

Preconfigured variables:
  base_bindir -> ${base_bindir}
  bindir -> ${bindir}
  sbindir -> ${sbindir}
  DEFAULT_INSTALL_TARGET -> 'obmc-standby.target'

Change-Id: Ife5003e1fc6766bf148a80663c35ab50c6002d26
Signed-off-by: Brad Bishop <bradleyb@fuzziesquirrel.com
diff --git a/classes/obmc-phosphor-systemd.bbclass b/classes/obmc-phosphor-systemd.bbclass
index dba39d3..0aa5493 100644
--- a/classes/obmc-phosphor-systemd.bbclass
+++ b/classes/obmc-phosphor-systemd.bbclass
@@ -13,11 +13,21 @@
 # INHIBIT_SYSTEMD_RESTART_POLICY_${unit}
 #    Inhibit the warning that is displayed if a service unit without a
 #    restart policy is detected.
+#
+# SYSTEMD_SUBSTITUTIONS_${unit}
+#    Variables in this list will be substituted in the specified unit
+#    file during install (if bitbake finds python {format} strings
+#    in the unit file itself).  List entries take the form:
+#      VAR:VALUE
+#    where {VAR} is the format string bitbake should look for in the
+#    unit file and VALUE is the value to substitute.
+
 
 inherit obmc-phosphor-utils
 inherit systemd
 
 _INSTALL_SD_UNITS=""
+SYSTEMD_DEFAULT_TARGET ?= "obmc-standby.target"
 
 
 def systemd_is_service(unit):
@@ -59,6 +69,14 @@
             % (d.getVar('systemd_system_unitdir', True), unit))
         set_append(d, '_INSTALL_SD_UNITS', unit)
 
+        for x in [
+                'base_bindir',
+                'bindir',
+                'sbindir',
+                'SYSTEMD_DEFAULT_TARGET' ]:
+            set_append(d, 'SYSTEMD_SUBSTITUTIONS_%s' % unit,
+                '%s:%s' % (x, d.getVar(x, True)))
+
 
     pn = d.getVar('PN', True)
     if d.getVar('SYSTEMD_SERVICE_%s' % pn, True) is None:
@@ -71,6 +89,27 @@
 }
 
 
+python systemd_do_postinst() {
+    for unit in listvar_to_list(d, '_INSTALL_SD_UNITS'):
+        subs = dict([ x.split(':') for x in
+            listvar_to_list(d, 'SYSTEMD_SUBSTITUTIONS_%s' % unit)])
+        if not subs:
+            continue
+
+        path = d.getVar('D', True)
+        path += d.getVar('systemd_system_unitdir', True)
+        path += '/%s' % unit
+        with open(path, 'r') as fd:
+            content = fd.read()
+        with open(path, 'w+') as fd:
+            try:
+                fd.write(content.format(**subs))
+            except KeyError as e:
+                bb.fatal('No substitution found for %s in '
+                    'unit file \'%s\'' % (e, unit))
+}
+
+
 do_install_append() {
         # install systemd service/socket/template files
         [ -z "${_INSTALL_SD_UNITS}" ] || \
@@ -84,3 +123,6 @@
                         ${D}${systemd_system_unitdir}/$s
         done
 }
+
+
+do_install[postfuncs] += "systemd_do_postinst"