#!/bin/sh

usage() {
    echo "usage: $0 partial-zimage output-location [initrd-location]"
    exit 0
}

if [ $# -lt 2 ]; then
    usage
fi

ZIMAGE=$1
OUTPUT=$2
INITRD=$3

for file in $ZIMAGE $INITRD; do
    if [ ! -f $file ]; then
        echo "$file does not exist"
	exit 1
    fi
done

if ! touch $OUTPUT; then
    echo "unable to write to $OUTPUT"
    exit 1
fi

for file in zImage.lds /usr/share/ppc64-utils/zImage.lds; do
    if [ -f $file ]; then
        LDS=$file
    fi
done

if [ -z "$LDS" ]; then
    echo "unable to find linker script"
    exit 1
fi

if [ "$INITRD" ]; then
    ZIMAGE=`mktemp /tmp/zimage.XXXXXX` || { echo $"could not make temp file"; exit 1; }
    cp $1 $ZIMAGE
    objcopy $ZIMAGE --add-section=.kernel:initrd=$INITRD --set-section-flags=.kernel:initrd=contents,alloc,load,readonly,data
fi

ld -m elf32ppclinux -Ttext 0x00400000 -e _start -T $LDS -o $OUTPUT $ZIMAGE
/usr/lib/yaboot/addnote $OUTPUT

if [ "$ZIMAGE" != "$1" ]; then
    rm -f $ZIMAGE
fi
