#!/system/bin/sh
INACTIVE_SYSTEM_BANK=`busybox mount | busybox grep "/shadow_system" | busybox sed -e "s/\/dev\/block\/mmcblk0p\(.\).*/\1/"`
SYSTEM_A=5
SYSTEM_B=6

image_location=$1
image_location=${image_location%???}gz

failureFound=0
#BANK A -> 1-uboot / 3-boot / 5-system / 10-vendor / 7-recovery
#BANK B -> 2-uboot / 4-boot / 6-system / 11-vendor / 7-recovery

if [ $INACTIVE_SYSTEM_BANK = $SYSTEM_A ]; then #inactive bank is A
        shadowVendor=10
else
        shadowVendor=11
fi

echo "Flashing vendor image on shadow bank ($shadowVendor) starts:" >> /var/log/upgrade.txt

if [[ ! -f $image_location ]]; then
		echo "...: $image_location not found!" >> /var/log/upgrade.txt
		/system/bin/msg2plalog "vendor image not found! error: $?" platform; failureFound=1;
fi

umount /dev/block/mmcblk0p$shadowVendor
if [ $? -ne 0 ]; then
	/system/bin/msg2plalog "unmount 1 vendor failed!" platform
	failureFound=1
	echo "vendor image fail in command 1" >> /var/log/upgrade.txt
fi
 
mount -t ext4 -o rw /dev/block/mmcblk0p$shadowVendor /shadow_vendor
if [ $? -ne 0 ]; then
	/system/bin/msg2plalog "mount shadow_vendor as RW failed error: $?" platform
	failureFound=1
	echo "vendor image fail in command 2" >> /var/log/upgrade.txt
fi

umount /dev/block/mmcblk0p$shadowVendor
if [ $? -ne 0 ]; then
	/system/bin/msg2plalog "unmount 2 vendor failed!" platform
	failureFound=1
	echo "vendor image fail in command 3" >> /var/log/upgrade.txt
fi

gunzip -c $image_location | busybox dd of=/dev/block/mmcblk0p$shadowVendor bs=2M
if [ $? -ne 0 ]; then
	/system/bin/msg2plalog "dd vendor failed! error: $?" platform
	failureFound=1
	echo "vendor image fail in command 4" >> /var/log/upgrade.txt
fi

#e2fsck -p -f /dev/block/mmcblk0p$shadowVendor
#if [ $? -ne 0 ]; then
#	/system/bin/msg2plalog "e2fsck of vendor failed! error: $?" platform
#	failureFound=1
#	echo "vendor image fail in command 5" >> /var/log/upgrade.txt
#fi

resize2fs /dev/block/mmcblk0p$shadowVendor
if [ $? -ne 0 ]; then
	/system/bin/msg2plalog "resizefs vendor failed! error: $?" platform
	failureFound=1
	echo "vendor image fail in command 6" >> /var/log/upgrade.txt
fi

mount -t ext4 -o ro /dev/block/mmcblk0p$shadowVendor /shadow_vendor
if [ $? -ne 0 ]; then
	/system/bin/msg2plalog "mount shadow_vendor as RO failed! error: $?" platform
	failureFound=1 echo "vendor image fail in command 7" >> /var/log/upgrade.txt
fi

if [ failureFound -eq 0 ]; then
       echo "Flashing vendor image on shadow bank passed!" >> /var/log/upgrade.txt
       /system/bin/msg2plalog "Flashing vendor image on shadow bank passed!" platform
else
      echo "Flashing vendor image on shadow bank failed!" >> /var/log/upgrade.txt
      /system/bin/msg2plalog "Flashing vendor image on shadow bank failed!" platform
      touch /var/log/upgrade_fail
fi

echo '-------------------------------------------------------' >> /var/log/upgrade.txt

