#!/bin/sh

# Copyright (c) 2007 Motorola, Inc. All Rights Reserved.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 2
# as published by the Free Software Foundation.
#
# 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 Street, Fifth Floor, Boston, MA
# 02110-1301, USA.

cross=mipsel-motorola-linux-gnu-

kernel_pre="$1"
initrd_image="$2"
boot_image="$3"
dest=$(mktemp -d /tmp/rd.XXXXXX)

cat > $dest/ld.script.1 << EOF
OUTPUT_ARCH(mips)
SECTIONS
{
  .image : { *(.data) }
}
EOF

cat > $dest/ld.script.2 << EOF
OUTPUT_ARCH(mips)
SECTIONS
{
  .text : { *(.text) }

  /* Make sure the stuff following the text section is aligned the
     same way as it is in the original image.
     This value must match the ld.script in linux/arch/mips! 
  */
  . = ALIGN(8192);

  .reginfo : { *(.reginfo) }
  .bss : { *(.bss) }
  .data : { *(.data) }
}
EOF

start=$(${cross}objdump -h $kernel_pre | grep '\.text' | awk '{print $4}')
oformat=$(${cross}objdump -i | head -2 | grep elf32)

# This script generates an ELF initrdimage from an ELF kernelimage and
# an initrd image.
# Strategy: extract the kernel, append initrd header and initrdimage. 
# Put back in the original image.

# Extract .image section
${cross}objcopy -j .image $kernel_pre $dest/image.seg 2>/dev/null

# Extract everything but the .image section
${cross}objcopy -R .image $kernel_pre $dest/image.seg.noim

# Convert the "packed" kernel to a raw file
${cross}objcopy -O binary $dest/image.seg $dest/image.seg.tmp

# Generate an initrd header (INRD + size of initrd image)
$(dirname $0)/add_initrd_header $dest/image.seg.tmp $initrd_image > $dest/initrd_header

# Concatenate kernel, initrd header and initrd image
cat $dest/image.seg.tmp $dest/initrd_header $initrd_image > $dest/image1

# Generate ELF object with the completed image in an .image section
${cross}ld -T $dest/ld.script.1 -b binary --oformat $oformat $dest/image1 -o $dest/image1.o

# Merge the object with the original image
${cross}ld -T $dest/ld.script.2 -Ttext 0x$start -o $boot_image $dest/image.seg.noim $dest/image1.o

# Clean up
rm -rf $dest
