#!/bin/bash
#######
## Description: The script checks for errors in the "apt update command" and looks for updatable packages
## Author: Sebastian Klee
## E-Mail: s.klee@timmehosting.de
## Version: 1.2
## Date: 11.09.2025
#######

while getopts "n:a:t:s:x:" opt; do
  case $opt in
    n)
      # Condition for if1 from the monitoring.
      condition_update_ready=$OPTARG
      ;;
    a)
      # Check attempt from the monitoring, we need this value for if2
      check_attempt=$OPTARG
      ;;
    t)
      # Service state type from the monitoring, we need this value for if2
      state_type=$OPTARG
      ;;
    s)
      # State from the monitoring, we need this value for if2
      state=$OPTARG
      ;;
    x)
      # Exit-Code for "Hard State" with problems(Status != OK)
      exit_code=$OPTARG
      ;;
    *)
      echo "USAGE: $0 -n condition_update_ready -a check_attempt -t state_type -s state -x exit_code"
      exit 3 ;;
  esac
done

if [ -z "$condition_update_ready" ] || [ -z "$check_attempt" ] || [ -z "$state_type" ] || [ -z "$state" ] || [ -z "$exit_code" ]; then
  echo "USAGE: $0 -n condition_update_ready -a check_attempt -t state_type -s state -x exit_code"
  exit 3;
else
    # Determine if packages are being held back.
    show_hold=$(apt-mark showhold | tr '\n' '|')
    # Determine the number of available updates, but filter out updates that are marked with hold
    number_update_ready=$(apt list --upgradable 2>/dev/null | grep -Pvc "$show_hold^Listing|^icinga2")
    # if1: This if statement checks the number of available Updates, if the number is greater than the condition, the script end with exit code 1, otherwise with exit code 0
    if [[ $number_update_ready -ge $condition_update_ready ]]; then
      # if2: We want a different output for the check result when the check reaches the hard state 
      if { [[ $state_type == "HARD" ]] || [[ $check_attempt -eq 4 ]]; } && [[ $state != "OK" ]]; then
        echo "Warnung: Es stehen bereits seit mehreren Tagen Pakete zur aktualisierung bereit,"
        echo "es gibt Updates fuer ${number_update_ready} Pakete, Server sollte geprueft werden"
        exit "$exit_code"
      else
        echo "Warnung: Fuer ${condition_update_ready} oder mehr Pakete(${number_update_ready}) gibt es Updates."
        exit 1
      fi
    else
      if [[ $number_update_ready -gt 0  ]]; then
        if [[ $number_update_ready -eq 1 ]]; then
          echo "OK: Fuer ${number_update_ready} Paket gibt es Updates."
          exit 0
        else
          echo "OK: Fuer ${number_update_ready} Pakete gibt es Updates."
          exit 0
        fi
      else
        echo "OK: Keine Updates"
        exit 0
      fi
    fi
fi
