#!/bin/bash

fail() {
	psplash-write "MSG ERROR Failed to restore device"

	exorint_led_fail

	while (true); do
		dbus-send --system --print-reply --dest=com.exor.EPAD "/Buzzer" com.exor.EPAD.Buzzer.beep int32:440 int32:200 &>/dev/null; sleep 3
	done
}

zeroFree() {
	local device=$1
	local prog=0

	while read line; do

		value="$( echo $line | sed 's:\([0-9]\+\).*:\1:' )"

		if [ $value -gt $(( $prog + 5 )) ]; then
			prog=$value
			psplash-write "PROGRESS $prog"
		fi

	done < <( ( zerofree -v $device 2>&1 1>/dev/null || fail ) | tr $'\x0d' $'\n' )

}

# Kill all processes locking the device	and unmount it
# $1 - device to unmount
forceUmount () {

	for mnt in $( mount | grep "^$1" | awk '{ print $3 }' ); do

		# Kill locking processes
		fuser -km $mnt
		sleep 1

		umount -R $mnt
		if [ $? -ne 0 ]; then
			umount -lR $mnt || fail
		fi

	done

	echo V > /dev/watchdog
}

. /etc/default/rcS
. /etc/profile
. /etc/exorint.funcs

APP_DATA_FILES="package.info rootfs.ext4.verity rootfs.ext4.verity.env rootfs.ext4.verity.env.sign"

exorint_led_running

# Make sure the launcher does not reboot the device
dbus-send --print-reply --system --dest=com.exor.JMLauncher '/' com.exor.JMLauncher.quitAll boolean:true

forceUmount "$DATAPARTITION"

# Restart xpslash on a different TMPDIR to make sure we have exclusive control
export DISPLAY=:0
export TMPDIR=/tmp/.psplash

killall xsplash; sleep 1
xsplash --no-taptap &
sleep 2

psplash-write "MSG Restoring device to defaults
This operation could take few minutes, please wait..."

# Clean up all secrets except public factory entries
dbus-send --print-reply --system --dest=com.exor.EPAD "/Security" com.exor.EPAD.Security.removeAllSecrets

DATATMP=/mnt/data-tmp
mkdir $DATATMP
mount $DATAPARTITION $DATATMP || exit 1

if [ "$SECURE_BOOT" = "no" ]; then
	# Delete everything
	rm -rf $( find $DATATMP -maxdepth 1 -mindepth 1 ) || fail
	sync

	umount $DATATMP
	# Use zerofree to limit the amount of write operations. It should only write non zero blocks
	zeroFree $DATAPARTITION

	# Force reformat at next boot
	dd of=$DATAPARTITION if=/dev/zero bs=1M count=1
else
	# Delete everything except the hmi folder
	rm -rf $( find $DATATMP -maxdepth 1 -mindepth 1 -not -name "hmi" ) || fail

	echo Done deleting

	HMIDIR="${DATATMP}/hmi"
	HMITMPDIR="${DATATMP}/hmi-tmp"

	if [ ! -f ${HMIDIR}/jmlauncher.xml ]; then
		rm -rf $HMIDIR
	else
		# Remove everything except applications
		appFolders="$( cat ${HMIDIR}/jmlauncher.xml | sed -n 's:<installationFolder>\(.*\)</installationFolder>:\1:p' )"
		mkdir $HMITMPDIR
		for app in $appFolders; do
			[ -d ${HMIDIR}/$app ] || continue
			mkdir ${HMITMPDIR}/$app
			for file in $APP_DATA_FILES; do
				[ -e ${HMIDIR}/$app/$file ] || continue
				mv ${HMIDIR}/$app/$file ${HMITMPDIR}/$app
			done
		done

		mv ${HMIDIR}/jmlauncher.xml ${HMITMPDIR}
		rm -rf ${HMIDIR} || fail
		mv ${HMITMPDIR} ${HMIDIR}
	fi

	echo Done migrating hmi

	sync
	umount $DATATMP
	zeroFree $DATAPARTITION
fi

#BSP-7021 reset secondary data partition
if [ -e $DATA2PARTITION ]; then
	echo Formatting secondary data partition
	forceUmount "$DATA2PARTITION"
	mke2fs -m 1 -T ext4 -L "data2" $DATA2PARTITION
	zeroFree $DATA2PARTITION
	[ ! -e $DATA2MNT ] && mkdir -p $DATA2MNT
	mount -t ext4 $DATA2PARTITION $DATA2MNT
	sync
fi

# Delete etc partition
forceUmount $ETCPARTITION

SECTOR_SIZE="$( cat /sys/block/mmcblk1/queue/hw_sector_size )"
ETC_SIZE="$( cat /sys/block/mmcblk1/$( basename ${ETCPARTITION} )/size )"
dd if=/dev/zero of=$ETCPARTITION bs=$SECTOR_SIZE count=$(( $ETC_SIZE / $SECTOR_SIZE)) || fail

rotation=0
[ -e $FACTORYMNT/etc/rotation ] && rotation="$(cat $FACTORYMNT/etc/rotation)"

# Remove factory setting and passwords
mount -o remount,rw $FACTORYMNT

# Preserve touch calibration
if [ "$rotation" = "0" -a -e $FACTORYMNT/etc/pointercal.xinput ]; then
	mkdir -p $FACTORYMNT/etc.tmp
	mv $FACTORYMNT/etc/pointercal.xinput $FACTORYMNT/etc.tmp
fi

if [ -e $FACTORYMNT/etc/udev/rules.d/touch_calibration.rules ]; then
	mkdir -p $FACTORYMNT/etc.tmp/udev/rules.d
	mv $FACTORYMNT/etc/udev/rules.d/touch_calibration.rules $FACTORYMNT/etc.tmp/udev/rules.d
fi

rm -rf $FACTORYMNT/etc
rm -rf $FACTORYMNT/shadow*
rm -rf $FACTORYMNT/group
rm -rf $FACTORYMNT/passwd
rm -rf $FACTORYMNT/roles
rm -rf $FACTORYMNT/userroles

[ -d $FACTORYMNT/etc.tmp ] && mv $FACTORYMNT/etc.tmp $FACTORYMNT/etc

mount -o remount,ro $FACTORYMNT

zerofree $FACTORYPARTITION || fail

sync

psplash-write "PROGRESS 100"; sleep 1
psplash-write "MSG Device restored successfully
Rebooting..."

exorint_led_success

dbus-send --system --print-reply --dest=com.exor.EPAD "/Buzzer" com.exor.EPAD.Buzzer.beep int32:440 int32:100; sleep 1;
dbus-send --system --print-reply --dest=com.exor.EPAD "/Buzzer" com.exor.EPAD.Buzzer.beep int32:440 int32:100; sleep 1;
dbus-send --system --print-reply --dest=com.exor.EPAD "/Buzzer" com.exor.EPAD.Buzzer.beep int32:440 int32:100; sleep 1;

reboot -f
