openpower-software-manager: Move ubiattach and ubiformat to single script

The service files that manage the pnor ubi volumes and mount points are
starting to get too much logic in them. Create a single shell script
instead of having all the commands and logic in the service files.

Also specify the ubi device number in ubiattach via the -d parameter
so that it matches the pnor mtd device number. In that way we always
know what the ubi device for pnor is, for when the bmc chip is formatted
with ubi we can differentiate them.

Remove the ExecStop entry on the service file, no need to detach the
volume when any service file stops.

Change-Id: Ib41592ea40ef8e58602100bb3ab51c5f4faada18
Signed-off-by: Adriana Kobylak <anoo@us.ibm.com>
diff --git a/meta-openbmc-machines/meta-openpower/common/recipes-phosphor/flash/openpower-software-manager/obmc-flash-bios b/meta-openbmc-machines/meta-openpower/common/recipes-phosphor/flash/openpower-software-manager/obmc-flash-bios
new file mode 100644
index 0000000..acc550b
--- /dev/null
+++ b/meta-openbmc-machines/meta-openpower/common/recipes-phosphor/flash/openpower-software-manager/obmc-flash-bios
@@ -0,0 +1,49 @@
+#!/bin/sh
+
+# Get the mtd device number (mtdX)
+findmtd() {
+  m="$(grep -xl "$1" /sys/class/mtd/*/name)"
+  m="${m%/name}"
+  m="${m##*/}"
+  echo "${m}"
+}
+
+# Attach the pnor mtd device to ubi
+attach_ubi() {
+  pnormtd="$(findmtd pnor)"
+  pnor="${pnormtd#mtd}"
+  pnordev="/dev/mtd${pnor}"
+
+  ubiattach /dev/ubi_ctrl -m "${pnor}" -d "${pnor}"
+  rc=$?
+  if [ ${rc} -ne 0 ]; then
+    # Check the pnor mtd device is formatted as ubi by reading the first 3 byes,
+    # which should be the ascii chars 'UBI'
+    magic="$(hexdump -C -n 3 ${pnordev})"
+    if [[ "${magic}" =~ "UBI" ]]; then
+      # Device already formatted as ubi, ubiattach failed for some other reason
+      return ${rc}
+    else
+      # Format device as ubi
+      echo "Starting ubiformat ${pnordev}"
+      ubiformat "${pnordev}" -y -q
+      # Retry the ubiattach
+      ubiattach /dev/ubi_ctrl -m "${pnor}" -d "${pnor}"
+    fi
+  fi
+}
+
+case "$1" in
+  ubiattach)
+    attach_ubi
+    ;;
+  *)
+    echo "Invalid argument"
+    exit 1
+    ;;
+esac
+rc=$?
+if [ ${rc} -ne 0 ]; then
+  echo "$0: error ${rc}"
+  exit ${rc}
+fi