#!/bin/sh

#
# the purpose of this script is to take a system inventory list and 
# search the repository using yum or up2date to find the correct 
# package list to install
#

detect_up2date(){
    if [ -x /usr/bin/up2date ];then
        return 0
    fi
    return 1
}

detect_yum(){
    if [ -x /usr/bin/yum ]; then
        return 0
    fi
    return 1
}

escape_parens(){
    line=$1
    line=${line/(/\\(}
    line=${line/)/\\)}
    echo $line
}

yum_extract_package_name(){
    local record_start=0
    while read line
    do
        if [ $record_start -eq 0 ]; then
            if [ -z "$line" ];then
                record_start=1
            fi
        fi
    
        if [ $record_start -eq 1 -a -n "$line" ]; then
            echo $line | cut -d' ' -f1
            record_start=0
        fi
    done
}

do_resolve_one_yum(){
    package=$1
    package=$(escape_parens $package)
    yum -C provides $package | yum_extract_package_name | sort | uniq
}

get_yum_packages(){
    echo "Setting up yum cache..."
    yum makecache > /dev/null 2>&1
    echo "Getting yum package list. This may take a long time."

    local TEMPFILE=$(mktemp /tmp/inventory-$$-XXXXXX)
    if [ $? -ne 0 ]; then
        echo "Could not create secure temporary file, cannot continue."
        exit 1
    fi
    trap "rm -f $TEMPFILE" QUIT EXIT TERM HUP
    inventory_system |
    while read line
    do
        echo -n "  Looking for inventory item: $line"
        count=0
        for i in $(do_resolve_one_yum $line)
        do
            echo "$i" >> $TEMPFILE
            count=$(( $count + 1 ))
        done
        echo "   done. Found $count packages for this item."
    done
    echo "Done getting packages."
    echo "Full package list: $(cat $TEMPFILE)"
    echo
    YUM_PACKAGE_FILE=$TEMPFILE
    trap "" QUIT EXIT TERM HUP
}

get_up2date_packages(){
    echo "Getting up2date package list. This may take a long time."
    echo
}

ask_install_yum_packages(){
    YUM_PACKAGES=$*
    echo 
    echo 
    echo "Recommend installing these packages via yum:" 
    for i in $YUM_PACKAGES
    do
        echo "    PACKAGE: $i" 
    done
    echo
    read -p "Would you like to install these packages now? (y/n): " -e ANSWER 
    if [ "$ANSWER" = "y" -o "$ANSWER" = "Y" ]; then
        echo "Ok. Installing packages now..."
        echo "Performing: yum install $YUM_PACKAGES"
        yum install $YUM_PACKAGES
    fi
    echo 
}

main() {
    if detect_yum; then
        get_yum_packages
    fi
    if detect_up2date; then
        get_up2date_packages
    fi

    if [ -n "$YUM_PACKAGE_FILE" ]; then
        YUM_PACKAGES=$(cat $YUM_PACKAGE_FILE | sort |uniq)
        rm $YUM_PACKAGE_FILE
        ask_install_yum_packages $YUM_PACKAGES
    fi
}

main $*
