#!/bin/sh
#
# take a boot directory with kernel + initrd and create a new one
# with a new kernel + initrd
# Usage: ./upd-kernel <olddir> <newdir> <newkernelrpm>
#
# Copyright (C) 2007-2015  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/>.
#

OLDDIR=`readlink -f $1`
NEWDIR=$2
KRPM=`readlink -f $3`

NEWVER=$(rpm -qp --provides $KRPM | awk -F ' = ' '/kernel-uname-r/ { print $2; }')

if [ -z "$OLDDIR" -o -z "$NEWDIR" -o -z "$KRPM" ]; then
  echo "Usage: $0 <olddir> <newdir> <newkernelrpm>"
  exit 1
fi

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

if [ -d $NEWDIR ]; then
    NEWDIR=`readlink -f $NEWDIR`
else
    NEWDIR=`readlink -f .`/$NEWDIR
    mkdir $NEWDIR
fi

WORKDIR=$(/bin/mktemp -d /tmp/kernrpm.XXXXXX)

pushd $WORKDIR > /dev/null

# explode the rpm
mkdir rpm
pushd rpm > /dev/null
rpm2cpio $KRPM | cpio -id --quiet
popd > /dev/null

# explode the initrd
mkdir initrd
pushd initrd > /dev/null
xzcat $OLDDIR/initrd.img | cpio -id --quiet

# delete the old module dir
for oldmoddir in $(find lib/modules/ -type f -name 'modules.dep' -exec dirname {} \; ) ; do
    rm -rf $oldmoddir
done

for mod in $(find lib/modules/ -type f -name '*.ko' -exec basename {} \; | sort | uniq) ; do
    for path in $(find $WORKDIR/rpm/lib/modules/$NEWVER/ -name ${mod}); do
        dest=${path##$WORKDIR/rpm/}
        mkdir -p $(dirname $dest)
        cp -p $path $dest
    done
done

cp -p $WORKDIR/rpm/lib/modules/$NEWVER/modules.order lib/modules/$NEWVER
cp -p $WORKDIR/rpm/lib/modules/$NEWVER/modules.builtin lib/modules/$NEWVER

/sbin/depmod -a -b . $NEWVER
rm -f lib/modules/$NEWVER/modules.*map

find . | cpio --quiet -c -o | xz --format=lzma -9 > $NEWDIR/initrd.img
popd > /dev/null

cp $WORKDIR/rpm/boot/vmlinuz-* $NEWDIR/vmlinuz
popd > /dev/null
rm -rf $WORKDIR
