#!/bin/bash

# Copyright (C) 2009-2010 Oracle and/or its affiliates. All rights reserved.
# Author: Tim Abbott
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2.
#
# 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.
#
# Not a Contribution for purposes of the Fedora Project Individual Contributor
# License Agreement
#
# Ksplice modprobe wrapper script to use depmod information for the
# running kernel, including Ksplice updates that have been
# cold-applied.

UPTRACK_IN_USE=/var/run/uptrack

# Don't bother with the uptrack modprobe if uptrack isn't is use.
if ! [ -f "$UPTRACK_IN_USE" ] || ! /bin/grep -sq ^ksplice_ /proc/modules; then
    exec -a modprobe "/sbin/modprobe.ksplice-orig" "$@"
fi

# Args based on module-init-tools 3.6.
get_set_version_arg ()
{
    OPTS=$(PATH=/usr/bin:/bin getopt -q -o 'vVC:o:rknqQsclt:aifbwd:' --long "verbose,version,config:,name:,remove,wait,showconfig,autoclean,quiet,show,dry-run,syslog,type:,list,all,ignore-install,ignore-remove,force,force-vermagic,force-modversion,set-version:,dirname,first-time,dump-modversions,use-blacklist" -- "$@") || return 1
    eval set -- "$OPTS"
    while true; do
	case "$1" in
	    --) shift; break;;
	    --set-version) shift; echo "$1"; shift;;
	    *) shift;;
	esac
    done
}

if [ -n "$(get_set_version_arg $@)" ]; then
    # The user passed --set-version; since presumably they explicitly
    # want to use some version other than that of their running
    # kernel, run modprobe with the user's options

    # TODO?: Check if the version is the same as the running kernel's
    # and if so, s/--set-version `uname -r`/--set-version ksplice-`uname -r`/.
    exec -a modprobe "/sbin/modprobe.ksplice-orig" "$@"
fi

VERARGS=
FAKEVERSION=$(/bin/uname -r).ksplice-updates
FAKEMODDIR="/lib/modules/$FAKEVERSION"
if [ -e "$FAKEMODDIR" ]; then
    # If any Ksplice updates are cold-applied, use them
    VERARGS="--set-version $FAKEVERSION"
fi

exec -a modprobe "/sbin/modprobe.ksplice-orig" $VERARGS "$@"
