systemd: Implement the /cfg mount in a generic manner

Our previous method sucked a bit because it relied on hardcoded,
board-specific partition names. It also bypassed systemd's mount
management and used a direct call to mount(1) instead.

So I asked on the systemd mailing list and got an advice to use systemd
generators.

NOTE: Ensure that your build and target trees have been cleared, the
previously-installed cfg-storage.service breaks this one.

Kudos for the sed magic to [1].

[1] https://stackoverflow.com/a/22550640/2245623

Change-Id: I269ce040b2d8ce88083ae0bb667ac12b7a0ee72e
diff --git a/board/czechlight/clearfog/overlay/usr/lib/systemd/system-generators/czehlight-cfg-mount-generator b/board/czechlight/clearfog/overlay/usr/lib/systemd/system-generators/czehlight-cfg-mount-generator
new file mode 100755
index 0000000..3197722
--- /dev/null
+++ b/board/czechlight/clearfog/overlay/usr/lib/systemd/system-generators/czehlight-cfg-mount-generator
@@ -0,0 +1,47 @@
+#!/bin/sh
+
+set -e
+
+if grep -q rauc.slot=A /proc/cmdline; then
+  RAUC_SLOT_NO=0
+  RAUC_SLOT_NAME=A
+elif grep -q rauc.slot=B /proc/cmdline; then
+  RAUC_SLOT_NO=1
+  RAUC_SLOT_NAME=B
+else
+  echo "Cannot determine active RAUC rootfs slot"
+  exit 1
+fi
+
+# sed magic:
+# 1) use `sed -n` so that we only print what's explicitly printed
+# 2) anchor the search between the "[slot.cfg.$RAUC_SLOT_NO]" and any other section
+# 3) look for a line beginning with "device="
+# 4) take stuff which is behind the "="
+# 5) print it
+DEVICE=$(sed -n "/\[slot\.cfg\.${RAUC_SLOT_NO}\]/,/\[.*\]/{/^device=/s/\(.*\)=\(.*\)/\\2/p}" /etc/rauc/system.conf)
+
+if [ x$DEVICE -eq x ]; then
+  echo "Cannot determine device for /cfg from RAUC"
+  exit 1
+fi
+
+if [ ! -b $DEVICE ]; then
+  echo "Device ${DEVICE} is not a block device"
+  exit 1
+fi
+
+cat > $1/cfg.mount <<EOF
+[Unit]
+Description=Persistent config (slot ${RAUC_SLOT_NAME})
+DefaultDependencies=no
+Conflicts=umount.target
+Before=local-fs.target umount.target
+After=swap.target
+
+[Mount]
+What=${DEVICE}
+Where=/cfg
+Type=auto
+Options=relatime,nosuid,nodev
+EOF