#!/bin/sh

# Copyright (C) 2008, 2016  Martin Michlmayr <tbm@cyrius.com>

# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301,
# USA.

set -e

error() {
	echo "$@"
	exit 1
}


if [ -n "$1" ]; then
	kvers="$1"
else
	kvers=`uname -r`
fi
kfile=/boot/vmlinuz-$kvers
ifile=/boot/initrd.img-$kvers
if [ ! -e $kfile ]; then
	error "Can't find kernel $kfile"
fi
if [ ! -e $ifile ]; then
	error "Can't find ramdisk $kfile"
fi

echo "Generating recovery image $kvers.img"
tmp=$(tempfile)
# Set machine id 1693 (0x069d)
devio > $tmp 'wl 0xe3a01c06,4' 'wl 0xe381109d,4'
cat $kfile >> $tmp
mkimage -A arm -O linux -T kernel -C none -e 0x01600000 -a 0x01600000 -n "Debian kernel $kvers" -d $tmp $tmp.uboot >&2 1>/dev/null
mv $tmp.uboot $kvers.img
filesize=$(wc -c $kvers.img | awk '{print $1}')
pad=$(expr 2097152 - $filesize)
if [ $pad -lt 0 ]; then
	rm -f $tmp $kvers.img
	error "Kernel is too large"
fi
if [ $pad -gt 0 ]; then
	dd if=/dev/zero bs=1 count=$pad 2>/dev/null >> $kvers.img
fi
mkimage -A arm -O linux -T ramdisk -C none -n "Debian ramdisk $kvers" -d $ifile $tmp.uboot >&2 1>/dev/null
cat $tmp.uboot >> $kvers.img
rm -f $tmp $tmp.uboot

