#!/bin/bash

#ignore signal
trap '' 1 2 3 6

TMP_FS=/dev/shm/debian
TMP_P1=/dev/shm/p1
REAL_FS=rfs

GREEN="/sys/class/leds/uc8100me:DIA3"
YELLOW="/sys/class/leds/uc8100me:DIA2"
RED="/sys/class/leds/uc8100me:DIA1"

# Get rootfile system partition from cmdline. e.g. /dev/mmcblk0p2
ROOT_PART=$(cat /proc/cmdline)
ROOT_PART="${ROOT_PART##*root=}"
ROOT_PART="${ROOT_PART%% *}"

# Strip the partition number to fetch sd node e.g. /dev/mmcblk0
SD_NODE="${ROOT_PART%%p2}"

# prepare for default rootfs
/etc/init.d/udev stop
/sbin/mx_uc8100me stop

echo 1 > ${GREEN}/brightness
echo heartbeat > ${YELLOW}/trigger
echo heartbeat > ${RED}/trigger

mkdir -p ${TMP_FS} 2> /dev/null
mkdir -p ${TMP_P1} 2> /dev/null
# mount backup partition to ${TMP_FS}
mount ${SD_NODE}p3 ${TMP_FS} 2> /dev/null
mount ${SD_NODE}p1 ${TMP_P1} 2> /dev/null

# Copy default uImage and device tree into partition 1
rm ${TMP_P1}/uImage
rm ${TMP_P1}/moxa-uc8100-me.dtb
cp -arf ${TMP_FS}/uImage ${TMP_P1}/uImage
cp -arf ${TMP_FS}/moxa-uc8100-me.dtb ${TMP_P1}/moxa-uc8100-me.dtb

# Mount tmp root file system.
mkdir -p ${TMP_FS}/proc/ ${TMP_FS}/sys/ ${TMP_FS}/dev/  ${TMP_FS}/${REAL_FS} 2> /dev/null
mount -t proc proc ${TMP_FS}/proc/
mount -t sysfs sys ${TMP_FS}/sys/
mount -o bind /dev ${TMP_FS}/dev/
mount ${ROOT_PART} ${TMP_FS}/${REAL_FS}

chroot ${TMP_FS} /setdef-chroot  /bin/ash

sync
echo "!!!Now the system is going to reboot. !!!"
/sbin/reboot -d -f -i

