#!/bin/bash
# Copyright (C) 2019 MBARI

#
# This script will copy an uImage kernel file to a raw NAND flash device using
# flashcp. Flashcp is part of mtd-utils and needs to be installed on the target.
# 

infile=${1}
mtd_dev=${2}
force=${3}

if [[ "${1}" = "help" || "${1}" = "-help" || "${1}" = "--help" || "${1}" = "h" || "${1}" = "?" ]]; then
	echo "Usage: $0 <image_file> <flash_device> (force)"
	exit 2
fi

if [[ -z ${1} || -z ${2} ]]; then
	echo "Usage: $0 <image_file> <flash_device> (force)"
	exit 2
fi
if [[ ! -f ${infile} ]]; then
	echo "Kernel image file ${infile} not found."
	exit 2
fi

if [[ ! -c ${mtd_dev} ]]; then
	echo "$mtd_dev is not a valid flash device."
	exit 2
fi

echo -n -e "\nLRAUV Kernel Image Installer\n\n"
echo "Trying to install image file ${infile}."

# check if header includes uImage magic
magic="0x$( hexdump ${infile} -e '/1 "%02X"' -n 4 )"
ui_magic="0x27051956"

if [[ ${magic} -ne ${ui_magic} ]]; then
	echo "Image file does not appear to be a valid uImage!"
	echo "Use '${0} ${1} ${2} force' to override."
	if [[ -z ${force} ]]; then
		exit 1
	fi
fi

infile_size=$(stat --printf="%s" ${infile})
page_size=$(getconf PAGESIZE)
tmp_file=${infile}.tmp.$(date +"%s")
# don't mess with original file, create temp file for padding and cp operation
cp ${infile} ${tmp_file}
if [[ $? -ne 0 ]]; then
	echo "Error creating tmp file, exiting."
	exit 1
fi

# flashcp can only copy files which are page size aligned in size, so check if
# the file is aligned or add padding if needed
if [[ $(( ${infile_size} % ${page_size} )) -ne 0 ]]; then
	echo "File size of ${infile_size} is not page aligned, calculate padding ..."
	padded_size=$(( (${infile_size} / ${page_size} + 1) * ${page_size} ))
	padding=$(( ${padded_size} - ${infile_size} ))
	echo "Padding ${padding} bytes to ${padded_size} bytes."

	# using seq since bash 2.05 on LRAUV doesn't have builtin ranges
	for i in $( seq ${padding} ); do
		echo -n -e "\xff" >> ${tmp_file}
	done
fi

echo "Writing image to ${mtd_dev} ..."
flashcp -v ${tmp_file} ${mtd_dev}
if [[ $? -eq 0 ]]; then
	echo -n -e "\nKernel image successfully written to ${mtd_dev}.\n\n"
else
	echo -n -e "\nCould not write kernel image!\n\n"
fi

rm ${tmp_file}
