#!/bin/sh
############
# CHANGELOG
#===========
# 2010/12/07        Thomas CREMEL
#               add a check file system to correct the case of mount readonly
#
# 2011/12/05        Michel SULYAN
#                   crms00349250: UBIFS error on /config partition
#

. /etc/functions
BACKUP_LOGGER="/.chkfs_logger"
DATA_TAR="/tmp/data.tgz"
mountROlist=""
logFolderIsReadonly="false"

log_in_error() {
	if [ "$logFolderIsReadonly" != "false" ] ; then
		echoerror "__chkfs__ : $*"
	else
		echo "$*" >> $BACKUP_LOGGER
	fi
}

save_data_folder() {
	# need to stop the soft that are using the /data 
	## application manager should not be started 
	## otherwise launch /etc/init.d/applicationManager stop 2>/dev/null
	/etc/init.d/log stop
	displaypopup "Trying to correct data disk errors : do not unplug the phone"
	tar cf - /data | gzip -c > $DATA_TAR
	return $?
}
restore_data_folder() {
	if [ "$1" = "0" ] ; then 
		[ -f $DATA_TAR ] && tar xzf $DATA_TAR
	fi
	[ -f $DATA_TAR ] && rm $DATA_TAR
}

checkROmountPoints()
{
	mountlist="/ /config /data"
	mountROlist=""
	logFolderIsReadonly="false";

	for mountpoint in $mountlist ; do
		testfile=$mountpoint"/.touchfile"
		# crms00349250 - remove file first	
		errfile=0
		rm -f $testfile
		# create test file
		/bin/date > $testfile
		sync
		if [ -f $testfile ]; then
			rm -f $testfile
			sync
			if [ -f $testfile ]; then
				# crms00349250 - error on deletion
				errfile=1
			fi
		else
			# crms00349250 - error on creation
			errfile=1
		fi
		# crms00349250 - check error
		if [ "$errfile" = "1" ] ; then 
			echo "checking partition $mountpoint : ERROR"
			# error, add current partition to R0 list
			mountROlist=$mountROlist" "$mountpoint
			res=`df $mountpoint | tail -1 | awk '{print $NF}'`
			if [ "$res" = "$mountpoint" ] ; then
				logFolderIsReadonly="true";
			fi
		else
			echo "checking partition $mountpoint : OK"
		fi
	done
}

start() {
	checkROmountPoints
	if [ "$mountROlist" != "" ] ; then
		if [ -f $sanityflag ] ; then 
			displaypopup "Error while mounting $mountROlist"
			/etc/init.d/sticky start
			/etc/init.d/unlock start
			echo "Error while mounting $mountROlist"
			while true ; do
				echo "Error while mounting $mountROlist with sanity flag activated"
				sleep 10
			done
		else
			log_in_error "Error while mounting $mountROlist"
			displaypopup "Scanning the disk (takes a while) : do not unplug the phone"
			echo "Scanning the disk (takes a while) : do not unplug the phone"
			nanddump -f /dev/null /dev/mtd2 2> /tmp/ndlog
			blocksize=`cut -d',' -f1 /tmp/ndlog | awk '/^Block size/{print $3}'`
			errors=`cat /tmp/ndlog | awk '/uncorrectable/{print $NF}'`
			if [ "$errors" != "" ] ; then
				log_in_error "Error with ECC in $errors"
				displaypopup "Trying to correct ECC errors on disk"
				for error in $errors; do
					blockstart=$(( $error / $blocksize * blocksize ))
					nanddump -o -s $blockstart -l $blocksize -f /tmp/badsector /dev/mtd2
					flash_erase /dev/mtd2 $blockstart 1
					nandwrite -s $blockstart /dev/mtd2 /tmp/badsector
				done
				displaypopup "rebooting in 5 seconds"
				sleep 5
				# reboot avoiding busybox, sync ... that hangs
				# this is a warm reset 
				dbg 0x80000080 2
			else
				# avoid the restore if many reboots were needed.
				/etc/init.d/sticky start  
				
				# go through all the failed mount points.
				for mountpoint in $mountROlist ; do
					displaypopup "trying to correct disk errors"
					case $mountpoint in 
						"/")
							log_in_error "/ read only : need to restore"
							rm /boot/zImage 
						;;
						"/config")
							displaypopup "Trying to correct disk errors : do not unplug the phone"
							cd /
							tar cf /tmp/${mountpoint}.tar $mountpoint
							result=$?
							umount $mountpoint
							/usr/sbin/ubi-wrapper ubiupdatevol ubi0:CONFIG -t
							mount $mountpoint
							if [ "$result" = "0" ] ; then 
								tar xf /tmp/${mountpoint}.tar
							fi
							rm /tmp/${mountpoint}.tar
						;;
						"/data")
							displaypopup "Trying to correct data disk errors : do not unplug the phone"
							cd /
								
							save_data_folder
							result=$?
							umount $mountpoint
							/usr/sbin/ubi-wrapper ubiupdatevol ubi0:DATA -t
							mount $mountpoint
							restore_data_folder $result
							
						;;
					esac
					sync
					reboot
				done
			fi
		fi
	fi
}

storeOldLogsInDefence() {
	if [ -f $BACKUP_LOGGER ]; then
		checkROmountPoints
		if [ "$logFolderIsReadonly" != "false" ] ; then
			while read rep ; do
				log_in_error "$rep"
			done
			rm -f $BACKUP_LOGGER
		fi
	fi
}



case "$0" in
    *chkfs)
		case "$1" in
			start)
				start
			;;
			stop)
			;;
			*)
				echo "usage : $0 start|stop"
			;;
		esac
    ;;
    *restore_chkfs_logs)
        storeOldLogsInDefence
    ;;
esac
