#!/usr/bin/env bash
# Read-only fixed routes. Never execute a pager or accept a pathname as root.
set -euo pipefail
export LC_ALL=C
unset PAGER SYSTEMD_PAGER LESSOPEN LESSCLOSE
usage() { echo 'Uso: harresi-diagnostics logs RUTA [1..500] | firewall nat|filter|lists | journal ssh|system [1..500]' >&2; exit 64; }
(( $# >= 2 && $# <= 3 )) || usage
lines="${3:-50}"
[[ "$lines" =~ ^[0-9]+$ && ${#lines} -le 3 ]] && (( 10#$lines >= 1 && 10#$lines <= 500 )) || usage
lines=$(( 10#$lines ))
show_file() {
  local path="$1"
  printf '\n--- %s ---\n' "$path"
  if [[ -r "$path" ]]; then tail -n "$lines" -- "$path"; else echo 'Registro no disponible o todavía no generado.'; fi
}
last_aide_completion() {
  local path=$1
  if [[ -r "$path" ]]; then
    awk '/=== AIDE RUN END / {
      complete=""; ended=""
      for (i=1;i<=NF;i++) {
        if ($i=="completed=yes") complete="yes"
        if ($i ~ /^ended=/) { ended=$i; sub(/^ended=/,"",ended) }
      }
      if (complete=="yes" && ended!="") last=ended
    } END { print last!="" ? last : "no disponible" }' "$path"
  else
    printf 'no disponible\n'
  fi
}
case "$1" in
  logs)
    case "$2" in
      suricata) show_file /var/log/volatile/suricata/eve.json; show_file /var/log/volatile/suricata-mitm/eve.json ;;
      sslproxy-connect) show_file /var/log/volatile/sslproxy/connect.log ;;
      sslproxy-service) show_file /var/log/volatile/sslproxy/service.log ;;
      aide) show_file /var/log/harresi/audit/aide/aide.log ;;
      aide-status)
        printf 'Última operación completada (UTC): %s\n' "$(last_aide_completion /var/log/harresi/audit/aide/aide.log)"
        printf 'Última comprobación completada (UTC): %s\n' "$(last_aide_completion /var/log/harresi/audit/aide/aide.last-check.log)"
        if [[ -s /var/log/harresi/audit/aide/aide.running ]]; then
          echo 'AIDE: comprobación en curso o incompleta; se muestran las últimas fechas completadas.'
        fi
        ;;
      aide-history)
        for path in /var/log/harresi/audit/aide/aide_history.log.1.gz /var/log/harresi/audit/aide/aide_history.log.1 /var/log/harresi/audit/aide/aide_history.log; do
          if [[ "$path" == *.gz && -r "$path" ]]; then
            printf '\n--- %s ---\n' "$path"; gzip -cd -- "$path" | tail -n "$lines"
          elif [[ -r "$path" ]]; then show_file "$path"; fi
        done
        ;;
      alerts) show_file /var/log/harresi/audit/product/ids-ips-events.log ;;
      firewall) show_file /var/log/harresi/audit/product/audit-product.log ;;
      configuration) show_file /var/log/harresi/audit/security/audit-security.log; show_file /var/log/harresi/audit/product/audit-product.log ;;
      audit) show_file /var/log/harresi/audit/auditd/audit.log ;;
      *) usage ;;
    esac
    ;;
  firewall)
    (( $# == 2 )) || usage
    case "$2" in
      nat|filter) iptables -t "$2" -L -n -v --line-numbers ;;
      lists)
        # Chain identifiers come from iptables itself and are individually quoted.
        rules=$(iptables -t filter -S)
        chains=$(printf '%s\n' "$rules" | awk '$1=="-N" && $2 ~ /^HARRESI/ {print $2}')
        [[ -n "$chains" ]] || { echo 'No hay cadenas HARRESI activas.'; exit 0; }
        while IFS= read -r chain; do
          [[ "$chain" =~ ^HARRESI[A-Z0-9_]*$ ]] || continue
          iptables -t filter -L "$chain" -n -v --line-numbers
        done <<< "$chains"
        ;;
      *) usage ;;
    esac
    ;;
  journal)
    case "$2" in
      ssh) journalctl --no-pager -n "$lines" -u ssh.service ;;
      system) journalctl --no-pager -n "$lines" ;;
      *) usage ;;
    esac
    ;;
  *) usage ;;
esac
