1#!/bin/sh
2
3BLKSZ=65536
4
5[ -f "$1" -a -f "$2" ] || {
6	echo "Usage: $0 <kernel image> <rootfs image> [output file]"
7	exit 1
8}
9
10IMAGE=${3:-openwrt-combined.img}
11
12# Make sure provided images are 64k aligned.
13kern="${IMAGE}.kernel"
14root="${IMAGE}.rootfs"
15dd if="$1" of="$kern" bs=$BLKSZ conv=sync 2>/dev/null
16dd if="$2" of="$root" bs=$BLKSZ conv=sync 2>/dev/null
17
18# Calculate md5sum over combined kernel and rootfs image.
19md5=$(cat "$kern" "$root" | md5sum -)
20
21# Write image header followed by kernel and rootfs image.
22# The header is padded to 64k, format is:
23#  CI               magic word ("Combined Image")
24#  <kernel length>  length of kernel encoded as zero padded 8 digit hex
25#  <rootfs length>  length of rootfs encoded as zero padded 8 digit hex
26#  <md5sum>         checksum of the combined kernel and rootfs image
27( printf "CI%08x%08x%32s" \
28	$(stat -c "%s" "$kern") $(stat -c "%s" "$root") "${md5%% *}" | \
29	dd bs=$BLKSZ conv=sync;
30  cat "$kern" "$root"
31) > ${IMAGE} 2>/dev/null
32
33# Clean up.
34rm -f "$kern" "$root"
35