#!/bin/bash

IMAGE_URL="http://webcam.intern.yannikenss.de/image.jpg"
TRESHOLD=0.009
HOSTNAME="webcam.intern.yannikenss.de"

while getopts ":i:c:" opt; do
  case $opt in
    i)
      IMAGE_URL="$OPTARG"
      ;;
    c)
      TRESHOLD="$OPTARG"
      ;;
    \?)
      echo "Invalid option: -$OPTARG"
      ;;
  esac
done

OUTPUT="UNKNOWN: Script failed"
EXIT_CODE=3

ping -q -c 2 "$HOSTNAME" > /dev/null
if [[ $? -ne 0 ]]
then
    OUTPUT="UNKNOWN: Webcam down"
    EXIT_CODE=3
    echo "$OUTPUT"
    exit $EXIT_CODE
fi

error_file=$(mktemp)

for i in {1..3}
do
    value=$(convert <(curl -s "$IMAGE_URL" 2>> $error_file ) -colorspace Gray -format "%[fx:image.mean]" info: 2>> $error_file)
    is_dark=$(echo "$value < $TRESHOLD" | bc -l 2>> $error_file)
    
    if [ $is_dark -eq 0 ]
    then
        OUTPUT="OK: Image bright"
        EXIT_CODE=0
    else
        OUTPUT="CRITICAL: Image dark"
        EXIT_CODE=2
        VALUE="|Brightness=$value"
        
        echo "$OUTPUT" "$VALUE"
        cat $error_file
        rm $error_file
        exit $EXIT_CODE
    fi
    sleep 0.5
done
VALUE="|Brightness=$value"

echo "$OUTPUT" "$VALUE"
cat $error_file
rm $error_file
exit $EXIT_CODE
