#!/bin/bash

# Check NAND for bit errors.  mtd1 is the boot partition.
# Logs the errors with syslog, and writes to
# /var/config/ecclog
# If there is an ECC error, Micron recommends re-writing
# the block with the error.
# The boot block is guaranteed 1 bit ECC for 1000 writes.
# The boot block is 128KB.
# Exit status of 1 means that the bootstrap partition is in
# need of a re-write.

logfile="/var/config/ecclog"
result=0
errors=0

devs=$(cat /proc/mtd | grep '^mtd[^:]*:' | sed 's/:.*//')

for d in ${devs} ; do
	if [[ $d == mtd0 ]] ; then
		continue
	fi
        mapfile -t alldumpbits < <( /usr/sbin/nanddump -f /dev/null /dev/${d} 2>&1 | fgrep 'ECC:' )
	for dumpbits in "${alldumpbits[@]}" ; do
	    if (( ${#dumpbits} > 0 )) ; then
		echo "$(printf '%(%s)T\n' -1): ${d}: $dumpbits" | tee -a ${logfile} | logger -t 'chkmtd'
		((errors++))
		if [[ ${d} == mtd1 ]] ; then
			result=1
		fi
	    fi
	done
done
if ((errors == 0)) ; then
	echo "$(printf '%(%s)T\n' -1): No partition has an ECC error" | tee -a ${logfile} | logger -t 'chkmtd'
fi
if ((result == 1)) ; then
	echo "$(printf '%(%s)T\n' -1): Boot partition has an ECC error, and device may not boot again" | tee -a ${logfile} | logger -t 'chkmtd'
fi


exit ${result}
