#!/bin/bash
#
# upd-bootimage
#
# Copyright (C) 2007  Red Hat, 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 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, see <http://www.gnu.org/licenses/>.
#

if [ -z "$1" ]; then
    echo "$0: <image> <binary> [<initrdpath>]"
    exit 1
fi

if [ ! -f $1 ]; then
    echo "$1 doesn't exist"
    exit 1
fi

MNTPOINT=/tmp/updboottree.$$
INITRD=/tmp/updboottree.$$.initrd
LOOPMNT=/tmp/updboottree.$$.initrdmnt

rm -rf $MNTPOINT $LOOPMNT
mkdir $MNTPOINT $LOOPMNT
mount -t vfat -o loop $1 $MNTPOINT

gunzip < $MNTPOINT/initrd.img > $INITRD

mount -o loop $INITRD $LOOPMNT

FROM=$2
TO=$FROM
if [ $(echo $FROM | cut -d- -f1) = loader ]; then
    TO=loader
fi

if [ ! -x $LOOPMNT/sbin/$TO ]; then
    echo "$LOOPMNT/sbin/$TO doesn't exist"
else
    cp $FROM $FROM.foo
    strip $FROM.foo
    install $FROM.foo $LOOPMNT/sbin/$TO
    rm -f $FROM.foo
fi

umount $LOOPMNT
gzip -9 < $INITRD > $INITRD.new
cp $INITRD.new $MNTPOINT/initrd.img
if [ -f $MNTPOINT/efi/boot/initrd.img ]; then
    cp $INITRD.new $MNTPOINT/efi/boot/initrd.img
fi
umount $MNTPOINT

if [ -n "$3" -a -f "$3" ]; then
    echo "Replacing $3"
    cp -f $INITRD.new $3
fi

rm -rf $MNTPOINT $LOOPMNT $INITRD $INITRD.new
