#!/system/bin/sh

# camera_update.sh
#
# return:
#   0 success
#   1 fail
#   2 fail, but should reboot for retry
#

UPDATE_FAIL_PATH="/fotadelta/camera_fw_fail"
UPDATE_RETRY_PATH_1="/fotadelta/camera_fw_retry.1"
UPDATE_RETRY_PATH_2="/fotadelta/camera_fw_retry.2"

# Do update firmware
RETRY_REMAIN=2
while :
do
    /system/bin/venus8_fwwrite -n /system/etc/firmware/CHP1.upd
    RESULT=$?
    if [ ${RESULT} -eq 0 ] ; then
        echo "$0: Update has succeeded."
        /system/bin/rm "${UPDATE_RETRY_PATH_1}" "${UPDATE_RETRY_PATH_2}"
        return 0
    fi

    if [ ${RETRY_REMAIN} -eq 0 ] ; then
        break
    fi

    echo "$0: Retry remain: ${RETRY_REMAIN}."
    RETRY_REMAIN=$(( ${RETRY_REMAIN} - 1 ))
done

# Check the retry history previous boot
if [ -f "${UPDATE_RETRY_PATH_2}" ] ; then
    echo "$0: Update has failed."
    /system/bin/rm "${UPDATE_RETRY_PATH_1}" "${UPDATE_RETRY_PATH_2}"
    date > "${UPDATE_FAIL_PATH}"
    return 1
elif [ -f "${UPDATE_RETRY_PATH_1}" ] ; then
    echo "$0: Creating retry history 2."
    date > "${UPDATE_RETRY_PATH_2}"
else
    echo "$0: Creating retry history 1."
    date > "${UPDATE_RETRY_PATH_1}"
fi

RESULT=$?
if [ ${RESULT} -ne 0 ] ; then
    echo "$0: Cannot create retry history. Give up updating camera firmware. errno=${RESULT}"
    /system/bin/rm "${UPDATE_RETRY_PATH_1}" "${UPDATE_RETRY_PATH_2}"
    date > "${UPDATE_FAIL_PATH}"
    return 1
fi

echo "$0: reboot for retry"
return 2
