#!/usr/bin/env bash
# Native AIDE bitmasks remain in native_rc; helper exits are disjoint outcomes.
set -u -o pipefail
umask 077
AIDE_CONFIG_DIR="${HARRESI_AIDE_CONFIG_DIR:-/etc/aide}"
AIDE_STATE_DIR="${HARRESI_AIDE_STATE_DIR:-/var/lib/aide}"
LOG_DIR="${HARRESI_AIDE_LOG_DIR:-/var/log/harresi/audit/aide}"
RUN_SOURCE="${HARRESI_AIDE_RUN_SOURCE:-startup}"
EXTRA_RULES_FILE="${HARRESI_AIDE_EXTRA_RULES_FILE:-}"
CATEGORIES=(system security network services)
LAST_LOG="$LOG_DIR/aide.log"
HIST_LOG="$LOG_DIR/aide_history.log"
RUN_STATE="$LOG_DIR/aide.running"
# 0 clean/baseline, 1 differences, 20 error, 21 incomplete, 22 unavailable.
usage() { echo "Uso: $0 [--check|--init-all|--update-all --accept-changes]"; }
operation=check
case "${1:---check}" in
  check|--check) operation=check ;;
  init|--init-all) operation=init ;;
  update|--update-all) operation=update ;;
  --help|-h) usage; exit 0 ;;
  *) usage >&2; exit 64 ;;
esac
if [[ "$operation" == update ]]; then
  [[ $# == 2 && "$2" == --accept-changes ]] || {
    echo 'Revise primero --check. La actualización exige --accept-changes y acepta las diferencias como línea base.' >&2
    exit 64
  }
elif (( $# > 1 )); then
  usage >&2; exit 64
fi
install -d -m 0700 -o root -g root "$AIDE_STATE_DIR" || exit 20
install -d -m 0755 -o root -g root "$LOG_DIR" || exit 20
# One writer prevents interleaved history and concurrent baseline replacements.
exec 9>"$AIDE_STATE_DIR/.harresi-aide.lock" || exit 20
if ! flock -n 9; then
  echo 'Comprobación AIDE en curso; vuelva a intentarlo al finalizar.' >&2
  exit 21
fi
work_dir=$(mktemp -d "$AIDE_STATE_DIR/.harresi-aide.XXXXXX") || exit 20
result=$(mktemp "$LOG_DIR/.aide-result.XXXXXX") || { rm -rf -- "$work_dir"; exit 20; }
completed=no
baseline_commit_started=no
baseline_commit_completed=no
started=$(date -u '+%Y-%m-%dT%H:%M:%SZ')
printf 'outcome=running operation=%s started=%s pid=%s\n' "$operation" "$started" "$$" > "$work_dir/running"
chmod 0644 "$work_dir/running"
mv -f -- "$work_dir/running" "$RUN_STATE" || exit 20
cleanup() {
  local pid
  for pid in "${pids[@]:-}"; do [[ -z "$pid" ]] || kill "$pid" 2>/dev/null || true; done
  if [[ "$baseline_commit_started" == yes && "$baseline_commit_completed" != yes ]]; then
    rollback_baselines || true
  fi
  if [[ "$completed" != yes ]]; then
    # Preserve the last completed result after interruption, including SIGKILL.
    printf 'outcome=incomplete operation=%s started=%s\n' "$operation" "$started" > "$RUN_STATE"
    chmod 0644 "$RUN_STATE"
  else
    rm -f -- "$RUN_STATE"
  fi
  rm -f -- "$result"
  rm -rf -- "$work_dir"
}
declare -A pids
trap cleanup EXIT
trap 'exit 21' HUP INT TERM
clear_attributes() {
  command -v chattr >/dev/null 2>&1 && chattr -i "$@" 2>/dev/null || true
}
run_category() {
  local category="$1" config target new_db native_rc generated
  local -a pipeline_status
  config="$AIDE_CONFIG_DIR/aide-$category.conf"
  target="$AIDE_STATE_DIR/aide-$category.db"
  new_db="$work_dir/aide-$category.db.new"
  if [[ ! -f "$config" ]]; then
    echo "No existe la configuración de categoría: $config"; return 20
  fi
  if [[ "$operation" == check || "$operation" == update ]]; then
    if [[ ! -s "$target" ]]; then
      echo "Línea base no disponible: $category; inicialice explícitamente antes de verificar."; return 22
    fi
  elif [[ -e "$target" || -e "$target.gz" ]]; then
    echo "La categoría $category ya tiene línea base; use actualización con aceptación explícita."; return 20
  fi
  # Stage generated databases away from the live baseline. Extra image rules
  # are appended only from the explicit root-controlled installation path.
  sed -E "s#^[[:space:]]*database_(out|new)[[:space:]]*=.*#database_\1=file:$new_db#" "$config" > "$work_dir/$category.conf" || return 20
  if [[ -n "$EXTRA_RULES_FILE" ]]; then
    [[ -f "$EXTRA_RULES_FILE" ]] || { echo 'Reglas AIDE adicionales no disponibles.'; return 20; }
    cat "$EXTRA_RULES_FILE" >> "$work_dir/$category.conf" || return 20
  fi
  echo "Categoría: $category; operación: $operation"
  # Bound captured diagnostic output while draining the producer. Keep its
  # actual status: a successful truncating consumer cannot hide an AIDE error.
  aide --config="$work_dir/$category.conf" "--$operation" 2>&1 | awk '
    { bytes+=length($0)+1; if (bytes<=4194304) print; else truncated=1 }
    END { if (truncated) print "[AIDE] Detalle limitado a 4 MiB por categoría; el resultado nativo se conserva." }
  '
  pipeline_status=("${PIPESTATUS[@]}")
  native_rc=${pipeline_status[0]}
  printf '%s\n' "$native_rc" > "$work_dir/$category.native_rc" || return 20
  if (( pipeline_status[1] != 0 )); then
    echo 'No se pudo capturar el detalle AIDE; ejecución sin resultado completo.'
    return 20
  fi
  if [[ "$operation" == check ]]; then
    (( native_rc <= 7 )) || return 20
    (( native_rc == 0 )) && return 0
    return 1
  fi
  # Init has no difference bitmask; update has the same 0..7 mask as check.
  if [[ "$operation" == init ]]; then
    (( native_rc == 0 )) || return 20
  else
    (( native_rc <= 7 )) || return 20
  fi
  generated=""
  for candidate in "$new_db" "$new_db.gz" "$new_db.db" "$new_db.db.gz"; do
    if [[ -s "$candidate" ]]; then generated="$candidate"; break; fi
  done
  [[ -n "$generated" ]] || { echo 'AIDE no generó una base válida.'; return 20; }
  if [[ "$generated" == *.gz ]]; then
    gzip -dc -- "$generated" > "$work_dir/$category.ready" || return 20
  else
    cp -- "$generated" "$work_dir/$category.ready" || return 20
  fi
  [[ -s "$work_dir/$category.ready" ]] || return 20
  chmod 0600 "$work_dir/$category.ready" || return 20
  return 0
}
rollback_baselines() {
  local category target failed=no
  for category in "${CATEGORIES[@]}"; do
    target="$AIDE_STATE_DIR/aide-$category.db"
    clear_attributes "$target"
    if [[ -e "$work_dir/$category.previous" ]]; then
      if ! mv -f -- "$work_dir/$category.previous" "$target"; then
        echo "ERROR: restaure manualmente $target desde $AIDE_STATE_DIR/baseline.previous" >&2
        failed=yes
      fi
    elif [[ "$operation" == init ]]; then
      rm -f -- "$target" || failed=yes
    fi
  done
  [[ "$failed" == no ]]
}
commit_baselines() {
  local category target failed=no
  local backup_dir="$AIDE_STATE_DIR/baseline.previous"
  install -d -m 0700 -o root -g root "$backup_dir" || return 20
  # Back up every existing DB before replacing any. Roll back all replacements
  # if an installation fails; readers and other writers use the same lock.
  for category in "${CATEGORIES[@]}"; do
    target="$AIDE_STATE_DIR/aide-$category.db"
    if [[ -e "$target" ]]; then
      cp -p -- "$target" "$work_dir/$category.previous" || return 20
      cp -p -- "$target" "$backup_dir/aide-$category.db" || return 20
    fi
  done
  baseline_commit_started=yes
  for category in "${CATEGORIES[@]}"; do
    target="$AIDE_STATE_DIR/aide-$category.db"
    clear_attributes "$target"
    if ! mv -f -- "$work_dir/$category.ready" "$target"; then failed=yes; break; fi
  done
  if [[ "$failed" == yes ]]; then
    rollback_baselines
    return 20
  fi
  baseline_commit_completed=yes
  for category in "${CATEGORIES[@]}"; do
    target="$AIDE_STATE_DIR/aide-$category.db"
    command -v chattr >/dev/null 2>&1 && chattr +i "$target" 2>/dev/null || true
  done
}
rc=0
outcome=clean
{
  printf '=== AIDE RUN START started=%s source=%s operation=%s ===\n' "$started" "$RUN_SOURCE" "$operation"
  if ! command -v aide >/dev/null 2>&1; then
    echo 'AIDE no está instalado; comprobación no disponible.'
    rc=22; outcome=unavailable
    for category in "${CATEGORIES[@]}"; do
      printf '=== AIDE CATEGORY END category=%s operation=%s outcome=unavailable native_rc=none ===\n' "$category" "$operation"
    done
  else
    for category in "${CATEGORIES[@]}"; do
      run_category "$category" > "$work_dir/$category.log" 2>&1 &
      pids["$category"]=$!
    done
    for category in "${CATEGORIES[@]}"; do
      if wait "${pids[$category]}"; then category_rc=0; else category_rc=$?; fi
      unset 'pids[$category]'
      if ! cat "$work_dir/$category.log"; then category_rc=20; fi
      native_rc=$(cat "$work_dir/$category.native_rc" 2>/dev/null || echo none)
      case "$category_rc" in
        0) if [[ "$operation" == check ]]; then category_outcome=clean; else category_outcome=staged; fi ;;
        1) category_outcome=differences; if (( rc == 0 )); then rc=1; outcome=differences; fi ;;
        22) category_outcome=unavailable; if (( rc != 20 )); then rc=22; outcome=unavailable; fi ;;
        *) category_outcome=error; rc=20; outcome=error ;;
      esac
      printf '=== AIDE CATEGORY END category=%s operation=%s outcome=%s native_rc=%s ===\n' "$category" "$operation" "$category_outcome" "$native_rc"
    done
    if [[ "$operation" != check && "$rc" == 0 ]]; then
      if commit_baselines; then
        if [[ "$operation" == init ]]; then outcome=baseline_initialized; else outcome=baseline_updated; fi
        echo 'Líneas base instaladas; esta operación no acredita integridad verificada.'
      else
        rc=20; outcome=error; echo 'Error al instalar líneas base; se ha intentado restaurar la base anterior.'
      fi
    fi
  fi
  ended=$(date -u '+%Y-%m-%dT%H:%M:%SZ')
  printf '=== AIDE RUN END completed=yes ended=%s operation=%s outcome=%s rc=%s categories=4 ===\n' "$ended" "$operation" "$outcome" "$rc"
} > "$result" 2>&1
# History is independently rotated; atomic rename keeps latest nonempty.
chmod 0644 "$result" || exit 20
cat "$result" >> "$HIST_LOG" || exit 20
chmod 0644 "$HIST_LOG" || exit 20
if [[ "$operation" == check ]]; then
  cp -- "$result" "$LOG_DIR/.aide-last-check.$$" && chmod 0644 "$LOG_DIR/.aide-last-check.$$" && mv -f -- "$LOG_DIR/.aide-last-check.$$" "$LOG_DIR/aide.last-check.log" || exit 20
fi
mv -f -- "$result" "$LAST_LOG" || exit 20
completed=yes
cat "$LAST_LOG"
exit "$rc"
