#!/bin/bash
#
# Initialization
#
name=""
c=30.0
w=25.0
n="temperature"
d="/dev/ttyS0"

config="/etc/check_mk/temper_local.cfg"

declare -a states=("OK" "WARNING" "CRITICAL" "UNKNOWN")

if [ -f "$config" ] ; then
        . $config
fi

if [ -z "$name" ] ; then
        exit 0
fi

# get arguments
while getopts d:c:w:n:h OPT; do
        case "$OPT" in
                d)
                        d=$OPTARG
                ;;
                c)
                        c=$OPTARG
                ;;
                w)
                        w=$OPTARG
                ;;
                n)
                        n=$OPTARG
                ;;
                h)
                        h=1
                ;;
        esac
done

# help
if [ -z "$d" -o "$h" ] ; then
        echo "Usage: $0 -d device [-c critical] [-w warning] [-n name]"
        echo -e " -d device\n\tpath to device with temperature [default:/dev/ttyS0]"
        echo -e " -c critical\n\tcritical temperature [default: 30.0]"
        echo -e " -w warning\n\twarning temperature [default: 25.0]"
        echo -e " -n name\n\tname of returned value [default: temperature]"

        exit 3
fi

# get temperature, remove unwanted charackters, aligment
value=`head -n 1 $d`

if [ -z "$value" ] ; then
        RETVAL=3
        echo "$RETVAL temp_$name $n=0 ${states[$RETVAL]} $n=0 ($w;$c)"
        exit $RETVAL
fi

value=`echo $value | perl -pe 's/[^\d-.\n]//g'`
value=`echo "$value + 0" | bc`

# compare
RETVAL=0;
if [ $(bc <<< "$value <= $w") -eq 0 ]; then
        RETVAL=1
fi
if [ $(bc <<< "$value <= $c") -eq 0 ]; then
        RETVAL=2
fi
if [ "x$value" == "x" ]; then
    RETVAL=3
	echo "$RETVAL temp_$name $n=0 ${states[$RETVAL]} $n=0 ($w;$c)"
	exit $RETVAL
fi

echo "$RETVAL temp_$name $n=$value ${states[$RETVAL]} $n=$value ($w;$c)"
exit $RETVAL
