#!/bin/bash
#
# Download the latest driver for a given kernel.
#
# This script determines whether a system uses ULN, then calls the
# appropriate underlying program.
#
# Because it attempts to be generic and usable for more than one driver,
# it gets the driver name from $(basename $0).
#

# Force LC_ALL=C
export LC_ALL=C
 
# Detected distribution vendor
VENDOR=rhel6

USAGE="[-n] [-d] [<kernel_version> ...]"

DRIVER="$(basename $0 | sed -e 's/-update-driver$//')"

exec 3>/dev/null

help=
verbose=
version=
usage=
dry_run=
download_only=
kernel_versions=
while case "$#" in 0) break ;; esac
do
    case "$1" in
    -n|--dry-run)
        dry_run=--dry-run
        ;;
    -d|--download-only)
        download_only=--download-only
        ;;
    -v|--verbose)
        verbose=-v
        exec 3>&2
        ;;
    -V|--version)
        version=t
        ;;
    -h|--help)
        help=t
        ;;
    -*)
        usage=t
        ;;
    *)
        kernel_versions="$kernel_versions $1"
        ;;
    esac
    shift
done

#
# Some basic functions
#
error()
{
    if [ $# -gt 0 ]
    then
        echo >&2 "$@"
    fi
}

die()
{
    error "$@"
    exit 1
}

usage()
{
    die "Usage: $(basename $0) $USAGE"
}


version()
{
    die "$0 version 2.1.8"
}


if [ "$help" = "t" -o "$usage" = "t" ]
then
    usage
fi

if [ "$version" = "t" ]
then
    version
fi


#
# Now let's actually do something
#


#
# If no kernel versions were specified, let's do the currently running
# kernel.
#
if [ -z "$kernel_versions" ]
then
    kernel_versions="$(uname -r)"
fi

: check_yum_config
# On systems using yum, check to see if it is configured for ULN.
check_yum_config()
{
    return 1
}

: check_up2date_config
# On systems using up2date, check to see if it is configured for ULN.
check_up2date_config()
{
    grep "^[ 	]*up2date[ 	][ 	]**default" /etc/sysconfig/rhn/sources >/dev/null 2>&1
    [ $? != 0 ] && return 1

    server_url="$(awk '/^serverURL=/{sub(/^serverURL=/, ""); print}' /etc/sysconfig/rhn/up2date)"
    [ "$server_url" = "https://linux-update.oracle.com/XMLRPC" ] || return 1

    return 0
}

: check_up2date_live
# See if up2date can contact the ULN server
check_up2date_live()
{
    channel="$(up2date --show-channels 2>/dev/null | awk '/^el/{print; exit 0;}')"
    [ $? != 0 ] && return 1

    case "$channel" in
    el*)
        return 0
        ;;
    *)
        ;;
    esac

    return 1
}

: has_uln
# Check to see if a system is using the Unbreakable Linux Network
has_uln()
{
    if check_yum_config
    then
        return 0
    elif check_up2date_config
    then
        check_up2date_live && return 0
    fi

    return 1
}

if has_uln
then
    update_driver="${DRIVER}-update-driver-uln"
else
    update_driver="${DRIVER}-update-driver-otn"
fi

for k in $kernel_versions
do
    "$update_driver" $download_only $dry_run $verbose "$k"
done

exit 0
