#!/bin/sh

PROG="${0##*/}" #program name

exit_handler()
{
	local rc=$?
	trap - EXIT
	rm -rf -- $TEMPFILE
	exit $rc
}

trap exit_handler SIGHUP SIGPIPE SIGINT SIGQUIT SIGTERM EXIT


print_version()
{
	cat <<EOF
$PROG version 0.0.2

Written by Stanislav Ievlev

Copyright (C) 2003-2004 ALT Linux Team
EOF
	exit
}


print_usage()
{
	[ "$1" = 0 ] || exec >&2
	cat <<EOF
Usage: $PROG

update initrd's for all kernel images

Valid options are:
  -h, --help	display help screen
  -v, --version	display version information

Report bugs to <inger@altlinux.org>
EOF
	[ -n "$1" ] && exit "$1" || exit
}


TEMP=`getopt -n $PROG -o h,v,d,p  -l help,version,device,partition -- "$@"` || print_usage
eval set -- "$TEMP"


while :; do
	case "$1" in
		-h|--help) print_usage 0
			;;
		-v|--version) print_version; exit 0
			;;
		--) shift; break
			;;
		*) Fatal "unrecognized option: $1"
			;;
	esac
	shift
done

get_option()
{
    predator-lilo -l $i $1
}

#sure vmlinuz-up symlink exist
if [ ! -L /boot/vmlinuz-up ]; then
    echo "warning:creating vmlinuz-up symlink"
    for i in /boot/vmlinuz-*-std-up-*; do
	ln -sf $i /boot/vmlinuz-up
    done
fi


#calculate initrd commands to run, exclude dups
TEMPFILE=`mktemp -t $PROG.XXXXXX`
(for i in $(predator-lilo -i|grep -v '%global')
do
    if  predator-lilo -n -l $i|grep -qs "initrd"; then
	kerver=$(rpm -qf --qf='%{VERSION}-%{NAME}-%{RELEASE}' \
	    $(realpath $(get_option image)) |sed 's,kernel-image-,,')
	initrd=$(get_option initrd)
	real_initrd="/boot/initrd-$kerver.img"
	echo "/sbin/mkinitrd -f $real_initrd $kerver"
	if [ "$initrd" != "$real_initrd" ]; then
	    echo "/bin/ln -sf $real_initrd $initrd"
	fi
    fi
done |sort -ur )>>$TEMPFILE

echo "commands to execute:"
cat $TEMPFILE

sh  $TEMPFILE

