#!/usr/bin/env bash
set -Eeuo pipefail

PATH="/usr/sbin:/usr/bin:/sbin:/bin"
LOG_DIR="/var/log/security"
LOCK_FILE="/var/lock/security_aide_check.lock"
RETENTION_DAYS="120"
TIMESTAMP="$(date +%Y%m%d-%H%M%S)"
LOG_FILE="${LOG_DIR}/aide-check-${TIMESTAMP}.log"
AIDE_CONFIG=""

if [[ "${EUID}" -ne 0 ]]; then
  echo "ERROR: This script must run as root." >&2
  exit 2
fi

for cmd in aide flock tee find date; do
  if ! command -v "${cmd}" >/dev/null 2>&1; then
    echo "ERROR: Required command not found: ${cmd}" >&2
    exit 2
  fi
done

mkdir -p "${LOG_DIR}" "$(dirname "${LOCK_FILE}")"
touch "${LOG_FILE}"

for candidate in /etc/aide/aide.conf /etc/aide.conf; do
  if [[ -f "${candidate}" ]]; then
    AIDE_CONFIG="${candidate}"
    break
  fi
done

if [[ -z "${AIDE_CONFIG}" ]]; then
  echo "ERROR: AIDE configuration not found at /etc/aide/aide.conf or /etc/aide.conf." | tee -a "${LOG_FILE}"
  exit 2
fi

exec 9>"${LOCK_FILE}"
if ! flock -n 9; then
  echo "INFO: AIDE check already running; exiting."
  exit 0
fi

{
  echo "==== AIDE weekly integrity check started: $(date -Is) ===="
  echo "Log file: ${LOG_FILE}"
  echo "Config file: ${AIDE_CONFIG}"

  # Prune old logs to control disk usage.
  find "${LOG_DIR}" -maxdepth 1 -type f -name 'aide-check-*.log' -mtime +"${RETENTION_DAYS}" -delete || true

  aide --config "${AIDE_CONFIG}" --check
} 2>&1 | tee -a "${LOG_FILE}"

AIDE_RC="${PIPESTATUS[0]}"

case "${AIDE_RC}" in
  0)
    echo "RESULT: AIDE reports no integrity changes."
    ;;
  1)
    echo "RESULT: AIDE detected changes. Review required."
    ;;
  *)
    echo "RESULT: AIDE execution error (exit code ${AIDE_RC})."
    ;;
esac | tee -a "${LOG_FILE}"

echo "==== AIDE weekly integrity check finished: $(date -Is) ====" | tee -a "${LOG_FILE}"

exit "${AIDE_RC}"
