#! /bin/bash
# @author alban
# @since 2019-09-24
# @license GPLv3

# Nagios include for shell
source /usr/lib/nagios/plugins/utils.sh

# Standard help method here
usage() { cat << HEREDOC
-- Alerts when packages haven't been updated after a while.
Usage: $(basename $0) [-a] [-c <crit_days>] [-w <warn_days>]
   -a 		Acknowledges the problem
   warn_days    How many days before the alert becomes a warning? Default: 30
   crit_days    How many days before the alert turns critical? Default: 60
HEREDOC
  exit 1;
}

# Default Values for Critical and Warning in days
CRITICAL=60
WARNING=30

# Handle a tmp file for storing values
TMP_FILE=$(mktemp)
trap "rm $TMP_FILE" EXIT

# Nagios exit helper
nagexit(){ MSG=${1:-OK}; CODE=${2:-0}; echo "$MSG" ; exit $CODE ; }

# Acknowledger
acknowledge(){

  cat << HEREDOC >> /var/log/apt/history.log

Start-Date: $(date "+%Y-%m-%d 01:01:00" )
Commandline: apt fake
Requested-By: root (0)
Upgrade: nothing:amd64 (3.18.3-5)
End-Date: $(date "+%Y-%m-%d 01:01:01")
HEREDOC
  echo "Acknowledged"
  exit
}


# Parse command line
while getopts "ahc:w:" o; do
    case "${o}" in
        a)
            acknowledge
            ;;
        h)
            usage
            ;;
        c)
            CRITICAL=${OPTARG}
            ;;
        w)
            WARNING=${OPTARG}
            ;;
    esac
done
shift $((OPTIND-1))

# Read APT history files
[ -f /var/log/apt/history.log.1.gz ] && CONTENT=$( zcat /var/log/apt/history.log.1 )
[ -f /var/log/apt/history.log ] && CONTENT="$CONTENT\n$(cat /var/log/apt/history.log)"

# Exit early if no content found
[ -z "$CONTENT" ]  && nagexit $STATE_OK "No log file found"

# Search for last upgrade
UPGRADE_DATE=$( date -d "2001-01-01" +%s )
echo "$CONTENT" | while read line ; do

  if [[ $line =~ ^Start-Date || $line =~ End-Date ]]  ; then
    LAST_DATE=$( echo $line | awk '{print $2}' )
    continue
  fi

  if [[ $line =~ ^Upgrade ]] ; then
    UPGRADE_DATE=${LAST_DATE}
    echo $UPGRADE_DATE > $TMP_FILE
    continue
  fi
done

# Get time delta since last upgrade
NOW_TS=$( date +%s )
UPGRADE_DATE_TS=$( date -d "$(cat $TMP_FILE)" +%s )
TIME_DELTA=$(( ( $NOW_TS - $UPGRADE_DATE_TS ) / ( 3600*24 ) ))

# Exit early if OK
[ $TIME_DELTA -lt $WARNING ] && nagexit

# Get packages to update
PACKAGE_COUNT=$(apt list --upgradable | wc -l )
MSG="Need to upgrade. $TIME_DELTA days since last upgrade, $PACKAGE_COUNT packages are waiting for upgrade.
Use $0 -a to acknowledge. "
[ $TIME_DELTA -ge $CRITICAL ] && nagexit "$MSG" $STATE_CRITICAL
[ $TIME_DELTA -ge $WARNING ] && nagexit "$MSG" $STATE_WARNING

#EOF
