Add kernel image update service

Change-Id: I851f0053dd125674545b6be2c67c2ba49db0ac3c
diff --git a/debian/control b/debian/control
index e10903c..2dab338 100644
--- a/debian/control
+++ b/debian/control
@@ -5,8 +5,8 @@
     boot-keys,
     cpio,
     debhelper (>= 10),
-    debhelper,
     device-tree-compiler,
+    dh-systemd,
     gcc-aarch64-linux-gnu,
     gcc-arm-linux-gnueabihf,
     liblz4-tool,
diff --git a/debian/linux-image-4.4.22-mtk.install b/debian/linux-image-4.4.22-mtk.install
new file mode 100644
index 0000000..dc766ec
--- /dev/null
+++ b/debian/linux-image-4.4.22-mtk.install
@@ -0,0 +1 @@
+debian/usr /
diff --git a/debian/linux-mtk.service b/debian/linux-mtk.service
new file mode 100644
index 0000000..b5e09c7
--- /dev/null
+++ b/debian/linux-mtk.service
@@ -0,0 +1,8 @@
+[Unit]
+Description=linux-mtk install service
+
+[Service]
+ExecStart=/usr/bin/install-linux-mtk.sh
+
+[Install]
+WantedBy=multi-user.target
diff --git a/debian/rules b/debian/rules
index bac2d19..96c7a01 100755
--- a/debian/rules
+++ b/debian/rules
@@ -21,7 +21,7 @@
 DESTDIR_KBUILD := $(CURDIR)/debian/linux-kbuild-$(VERSION)
 
 %:
-	dh $@
+	dh $@ --with=systemd
 
 override_dh_auto_clean:
 	true
@@ -64,3 +64,9 @@
 
 	install -d $(DESTDIR_HEADERS)/lib/modules/$(VERSION)
 	ln -s /usr/src/linux-headers-$(VERSION) $(DESTDIR_HEADERS)/lib/modules/$(VERSION)/build
+
+override_dh_systemd_enable:
+	dh_systemd_enable --name=linux-mtk
+
+override_dh_sytemd_start:
+	dh_systemd_start --restart-after-upgrade linux-mtk
diff --git a/debian/usr/bin/install-linux-mtk.sh b/debian/usr/bin/install-linux-mtk.sh
new file mode 100755
index 0000000..857fef3
--- /dev/null
+++ b/debian/usr/bin/install-linux-mtk.sh
@@ -0,0 +1,42 @@
+#!/bin/bash
+
+BOOT_PART=mmcblk0p2
+
+BOOT_PACKAGE=/boot/boot.img
+BOOT_PACKAGE_SIZE=$(stat -c%s ${BOOT_PACKAGE})
+
+function check_emmc_matches {
+  local BOOT_CURRENT=$(mktemp)
+  dd if=/dev/${BOOT_PART} of=${BOOT_CURRENT} \
+    count=${BOOT_PACKAGE_SIZE} \
+    bs=512 \
+    iflag=count_bytes
+  diff ${BOOT_CURRENT} ${BOOT_PACKAGE}
+  local DIFF_RETURN_CODE=$?
+  rm ${BOOT_CURRENT}
+  return ${DIFF_RETURN_CODE}
+}
+
+# Check if the image on eMMC is the same as from the package
+check_emmc_matches
+
+if [[ $? -eq 0 ]]; then
+  exit 0
+fi
+
+UPDATE_SUCCESS=false
+# Write the boot image into the block device
+for i in `seq 1 5`
+do
+  dd if=${BOOT_PACKAGE} of=/dev/${BOOT_PART} bs=512
+  check_emmc_matches
+  if [[ $? -eq 0 ]]; then
+    UPDATE_SUCCESS=true
+    break
+  fi
+done
+
+if [[ "${UPDATE_SUCCESS}" != true ]]; then
+  echo "Failed to update Linux! Rebooting is unsafe!"
+  exit 1
+fi