#!/bin/bash
#######
## Description: The script determines the number of reboot in a given time period
## Author: Sebastian Klee
## E-Mail: s.klee@timmehosting.de
## Version: 1.2
## Date: 21.01.2025
#######

# Declaration of Arrays and integer variables
declare -a array_reboots_total array_reboots_unintentional
declare -i sum_reboots_total sum_reboots_unintentional

while getopts "c:w:d:" opt; do
  case $opt in
    c)
      # Condition for criticals(Number reboots)
      condition_crit=$OPTARG
      ;;
    w)
      # Condition for warnings(Number reboots)
      condition_warn=$OPTARG
      ;;
    d)
      # Time period to be checked for reboots
      days=$OPTARG
      ;;
    *)
      echo "USAGE: $0 -c condition_crit -w condition_warn -d days"
      exit 3 ;;
  esac
done

if [ -z "$condition_crit" ] || [ -z "$condition_warn" ] || [ -z "$days" ]; then
  echo "USAGE: $0 -c condition_crit -w condition_warn -d days"
  exit 3;
else
  # For loop, repetition depends on the value of the Variable `days`, which contains the time period in days, which we want to check for reboots.
  for (( c=0; c<days; c++ )) do
    # The number of total and unintentional reboots for each day will be written to the corresponding arrays, in addition to that the sum of the total and uintentional reboots is being determined. 
    array_reboots_total[c]=$(awk '$0 ~ /kernel: Command line: BOOT_IMAGE/ {print $0}' /var/log/messages* | awk -v date="$(date -d ''$c' days ago' +'%b %e')" '$0 ~ date {print $0}' | sort | uniq | wc -l)
    sum_reboots_total+=${array_reboots_total[c]}
    array_reboots_unintentional[c]=$(awk '$0 ~ /system.journal corrupted or uncleanly shut down/ {print $0}' /var/log/messages* | awk -v date="$(date -d ''$c' days ago' +'%b %e')" '$0 ~ date {print $0}' | sort | uniq | wc -l)
    sum_reboots_unintentional+=${array_reboots_unintentional[c]}
  done

  # Only for the Output
  if [[ $days -gt 1 ]]; then
    word_days="in den letzten ${days} Tagen:"
  else
    word_days="heute:"
  fi

  # If statement to determine the output and exit code of the script, it compares the sum of the total reboots in the given time period with the values of the conditions.
  if [[ $sum_reboots_total -ge $condition_crit ]]; then
    echo "Reboots ${word_days} ${sum_reboots_total} | Nicht geplante Reboots: ${sum_reboots_unintentional}"
    exit 2
  elif [[ $sum_reboots_total -ge $condition_warn ]]; then
    echo "Reboots ${word_days} ${sum_reboots_total} | Nicht geplante Reboots: ${sum_reboots_unintentional}"
    exit 1
  else
    echo "Reboots ${word_days} ${sum_reboots_total} | Nicht geplante Reboots: ${sum_reboots_unintentional}"
    exit 0
  fi
fi
