#!/bin/sh
#
# Upgradeable packages detector plugin for monitoring
# Written by groente <groente@puscii.nl>
#
# Usage: ./check_upgradeable.sh
#
# Description:
#
# This plugin will use apt-show-versions to scan for upgradeable packages.
#
# Output:
# 
# This plugin will return:
# - CRITICAL if dependencies are missing
# - WARNING if upgradeable packages are found
# - OK if no upgradeable packages are found
#
# Usage:
#
#   check_upgradeable -c
#

# Paths to commands used in this script.  These
# may have to be modified to match your system setup.

PATH="@TRUSTED_PATH@"
export PATH
PROGNAME=`basename $0`
PROGPATH=`echo $0 | sed -e 's,[\\/][^\\/][^\\/]*$,,'`
REVISION="0.1"

. $PROGPATH/utils.sh

print_usage() {
    echo "Usage: $PROGNAME"
    echo "Usage: $PROGNAME --help"
    echo "Usage: $PROGNAME --version"
}

print_help() {
    print_revision $PROGNAME $REVISION
    echo ""
    print_usage
    echo ""
    echo "Check upgradeable packages for monitoring"
    echo ""
    support
}

# Make sure the correct number of command line
# arguments have been supplied

if [ $# -lt 1 ]; then
    print_usage
    exit $STATE_UNKNOWN
fi

# Grab the command line arguments

exitstatus=$STATE_WARNING #default
while test -n "$1"; do
    case "$1" in
        --help)
            print_help
            exit $STATE_OK
            ;;
        -h)
            print_help
            exit $STATE_OK
            ;;
        --version)
            print_revision $PROGNAME $REVISION
            exit $STATE_OK
            ;;
        -V)
            print_revision $PROGNAME $REVISION
            exit $STATE_OK
            ;;
        -x)
            exitstatus=$2
            shift
            ;;
        --exitstatus)
            exitstatus=$2
            shift
            ;;
	-c)
	    ;;
        *)
            echo "Unknown argument: $1"
            print_usage
            exit $STATE_UNKNOWN
            ;;
    esac
    shift
done

if ! [ -f /usr/bin/apt-show-versions ]; then
    echo "Dependency apt-show-versions not found!"
    exit $STATE_CRITICAL
fi

upgradeables=$(for i in `apt-show-versions |grep upgradeable |sed -e 's/:.*//'`;do echo -n "$i ";done)

if [ "$upgradeables" = "" ]; then
    echo "No upgradeable packages, all is good."
    exitstatus=$STATE_OK
else
    echo "The following packages are upgradeable: $upgradeables"
    exitstatus=$STATE_WARNING
fi

exit $exitstatus
