#!/bin/bash

# Plugin Return Codes
# 0 = Ok
# 1 = Warning
# 2 = Critical
# 3 = Unknown

PrinterName="${1:-*}" # as returned by "ink", "*" for one/first printer
WarnLevel="${2:-10}"
CriticalLevel="${3:-5}"

for p in /dev/usb/lp*; do
  if [ ${p} = '/dev/usb/lp*' ]; then
    echo "No printers or printers offline."
    exit 0 # OK: Inkjets aren't present all the time.
  fi
  if [ ! -r ${p} ]; then
    echo "Can't access printer ${p} (nagios user not in group lp?)."
    exit 3 # Unknown: Configuration error.
  fi
  InkLevel=$(/usr/bin/ink -d ${p})
  if [ "${InkLevel/*${PrinterName}*/}" ]; then
    continue
  fi
  echo "${InkLevel}" | grep "%$" | \
  {
    RetVal=0
    RetLev=""
    RetMsg=""
    while read Color Level; do
      Color=${Color%%:}
      Level=${Level%%\%}
      if [ "${Level}" -le "${CriticalLevel}" -a ${RetVal} -lt 2 ]; then
        RetMsg="${RetMsg}${RetMsg:+;}Ink Cartridge ${Color} (almost) empty!"
        RetVal=2
      elif [ "${Level}" -le "${WarnLevel}" -a ${RetVal} -lt 1 ]; then
        RetMsg="${RetMsg}${RetMsg:+;}Ink low in Cartridge ${Color}!"
        RetVal=1
      fi
      RetLev="${RetLev}${RetLev:+;}${Color}=${Level}%"
    done
    echo "${RetMsg:-Ok} (${RetLev})"
    exit $RetVal
  }
  exit $?
done

echo "Printer ${PrinterName} not present or offline."
exit 0
