#!/bin/sh

# test script for fun: reboot.
# use tool: reboot pstore(pmsg).

# $1 - reboot max-time, default 100.
# $? - 0-OK,!0-ERROR.

# script env.
SCRP_NAME=`basename $0`

# get reboot max-time.
REBOOT_WAIT=3
if [ -z "$1" ]; then
    REBOOT_MAX=100
else
    REBOOT_MAX=$1
fi

# path for pstore.
PSTORE_MNT=/sys/fs/pstore
PSTORE_PMSG=/dev/pmsg0

# auto mount pstore if need.
PstoreMnt=`cat /proc/mounts |grep ^pstore`
if [ -z "${PstoreMnt}" ]; then
	echo mount -t pstore pstore ${PSTORE_MNT}
	#mount -t pstore pstore ${PSTORE_MNT}
	if [ ! $? -eq 0 ]; then
		echo "pstore mount error, ${SCRP_NAME} stop"
		exit 1
	fi
else
	PSTORE_MNT=`echo "$PstoreMnt" |awk '{print $2}'`
fi

# get reboot_cnt from pmsg.
if [ ! -e ${PSTORE_PMSG} ]; then
	echo "no ${PSTORE_PMSG}, ${SCRP_NAME} stop"
	exit 2
fi

# get reboot_cnt from pmsg and test done?
PstorePfile=${PSTORE_MNT}/`ls ${PSTORE_MNT} |grep pmsg-`
if [ -f ${PstorePfile} ]; then
	RebootCnt=`grep "^reboot_cnt=" ${PstorePfile} |awk -F "=" '{print $2}'`
fi
if [ -z "${RebootCnt}" ]; then
	echo "${SCRP_NAME} for ${REBOOT_MAX} starting ..."
	RebootCnt=0
else
	echo "${SCRP_NAME} done ${RebootCnt}/${REBOOT_MAX}."
	if [ ${RebootCnt} -ge ${REBOOT_MAX} ]; then
		echo "${SCRP_NAME} all ${REBOOT_MAX} done"
		echo "${SCRP_NAME} [PASS]"
		exit 0
	fi
fi

# prepare to reboot count+1.
echo "reboot after ${REBOOT_WAIT}s ..."
if read -t ${REBOOT_WAIT} -p " input ENTER to stop: " RebootStop; then
	echo "${SCRP_NAME} stop by hand when ${RebootCnt}"
	if [ ${RebootCnt} -gt 0 ]; then
		echo "${SCRP_NAME} [PASS]"
		exit 0
	else
		echo "${SCRP_NAME} [FAIL]"
		exit 3
	fi
else
	RebootCnt=`expr ${RebootCnt} + 1`
	echo "timeout"
	echo "${SCRP_NAME} for ${RebootCnt} ..."
	echo "reboot_cnt=${RebootCnt}" >${PSTORE_PMSG}
	echo reboot
	reboot
	sleep 10
	echo "${SCRP_NAME} error!"
	exit 4
fi
