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

REPO_BASE_URL="${HARRESI_RULES_REPO_BASE_URL:-https://suricata-rules.harresi.es}"
STATE_DIR="${HARRESI_RULES_STATE_DIR:-/var/lib/harresi/rules}"
STATE_FILE="$STATE_DIR/state.json"
UPDATE_CONF="/etc/suricata/update.yaml"
TMP_DIR="${HARRESI_RULES_TMP_DIR:-/tmp/harresi-rules-update}"
SURICATA_COMMAND_SOCKET="/var/run/suricata-command.socket"
LOCAL_RULES_FILE="${HARRESI_LOCAL_RULES_FILE:-/var/lib/suricata/rules/harresi-local.rules}"

mkdir -p "$STATE_DIR" "$TMP_DIR"

usage() {
  cat <<EOF
Uso:
  harresi-rules latest
  harresi-rules list
  harresi-rules check <version|latest>
  harresi-rules status
  harresi-rules install latest
  harresi-rules install <version>
  harresi-rules rollback
  harresi-rules next-sid
  harresi-rules custom-apply <file>
EOF
}

get_current_version() {
  if [ -f "$STATE_FILE" ]; then
    jq -r '.installed_version // "none"' "$STATE_FILE"
  else
    echo "none"
  fi
}

get_previous_version() {
  if [ -f "$STATE_FILE" ]; then
    jq -r '.previous_version // "none"' "$STATE_FILE"
  else
    echo "none"
  fi
}

release_manifest() {
  requested="$1"
  manifest="$TMP_DIR/manifest-check.json"

  if [ "$requested" = "latest" ]; then
    curl --fail --silent --show-error "$REPO_BASE_URL/latest.json" -o "$manifest"
  else
    curl --fail --silent --show-error \
      "$REPO_BASE_URL/releases/$requested/manifest.json" -o "$manifest"
  fi

  version="$(jq -r '.version // empty' "$manifest")"
  artifact="$(jq -r '.artifact // empty' "$manifest")"
  sha512="$(jq -r '.sha512 // empty' "$manifest")"

  [ -n "$version" ] && [ -n "$artifact" ] && [ -n "$sha512" ] || {
    echo "ERROR: manifiesto de reglas inválido."
    exit 1
  }
  printf '%s\n' "$version" "$artifact" "$sha512"
}

check_version() {
  requested="$1"
  check_dir="$TMP_DIR/check-${requested//[^A-Za-z0-9._-]/_}"
  manifest_data="$(release_manifest "$requested")"
  version="$(printf '%s\n' "$manifest_data" | sed -n '1p')"
  artifact="$(printf '%s\n' "$manifest_data" | sed -n '2p')"
  sha512="$(printf '%s\n' "$manifest_data" | sed -n '3p')"
  case "$artifact" in
    ''|*/*)
      echo "ERROR: nombre de artifact inválido en el manifiesto de $version."
      exit 1
      ;;
  esac
  artifact_path="$check_dir/$artifact"
  rules_path="$check_dir/rules/harresi.rules"

  if [[ ! "$sha512" =~ ^[0-9a-fA-F]{128}$ ]]; then
    echo "ERROR: SHA-512 inválido en el manifiesto de $version."
    exit 1
  fi

  rm -rf "$check_dir"
  trap 'rm -rf "$check_dir"' EXIT
  mkdir -p "$check_dir/logs"
  curl --fail --silent --show-error \
    "$REPO_BASE_URL/releases/$version/$artifact" -o "$artifact_path"
  printf '%s  %s\n' "$sha512" "$artifact_path" | sha512sum -c -
  tar -xzf "$artifact_path" -C "$check_dir"
  [ -s "$rules_path" ] || {
    echo "ERROR: el paquete $version no contiene rules/harresi.rules."
    exit 1
  }

  tested=0
  for config in /etc/suricata/suricata_ids.yaml \
                /etc/suricata/suricata_idps.yaml \
                /etc/suricata/suricata_mitm.yaml; do
    [ -f "$config" ] || continue
    echo "Comprobando $version con $(basename "$config")"
    suricata -T -c "$config" -S "$rules_path" -l "$check_dir/logs" >/dev/null
    tested=$((tested + 1))
  done

  [ "$tested" -gt 0 ] || {
    echo "ERROR: no existe ninguna configuración Suricata para validar."
    exit 1
  }
  rm -rf "$check_dir"
  trap - EXIT
  echo "OK: la versión $version es válida y no se instaló."
}

ensure_local_rules_file() {
  install -d -m 0755 "$(dirname "$LOCAL_RULES_FILE")"
  [ -e "$LOCAL_RULES_FILE" ] || install -m 0640 -o root -g root /dev/null "$LOCAL_RULES_FILE"
}

validate_local_rules() {
  test_dir="$TMP_DIR/local-rule-test"
  rm -rf "$test_dir"
  mkdir -p "$test_dir"
  tested=0

  for config in /etc/suricata/suricata_ids.yaml \
                /etc/suricata/suricata_idps.yaml \
                /etc/suricata/suricata_mitm.yaml; do
    [ -f "$config" ] || continue
    suricata -T -c "$config" -l "$test_dir" >/dev/null
    tested=$((tested + 1))
  done

  [ "$tested" -gt 0 ] || {
    echo "ERROR: no existe ninguna configuración Suricata para validar."
    return 1
  }
}

next_sid() {
  ensure_local_rules_file
  max_sid="$(awk '
    match($0, /sid:[[:space:]]*[0-9]+/) {
      sid = substr($0, RSTART, RLENGTH)
      sub(/.*:/, "", sid)
      gsub(/[[:space:]]/, "", sid)
      if (sid ~ /^[0-9]+$/ && sid > max) max = sid
    }
    END { print (max < 9000000 ? 9000000 : max + 1) }
  ' "$LOCAL_RULES_FILE")"
  printf '%s\n' "$max_sid"
}

apply_custom_rules() {
  candidate="$1"
  [ -f "$candidate" ] || {
    echo "ERROR: no existe el fichero de reglas: $candidate"
    exit 1
  }

  ensure_local_rules_file
  backup="$TMP_DIR/harresi-local.rules.backup.$$"
  cp -p "$LOCAL_RULES_FILE" "$backup"
  {
    cat "$candidate"
    printf '\n'
  } >> "$LOCAL_RULES_FILE"
  chmod 0640 "$LOCAL_RULES_FILE"

  if ! validate_local_rules; then
    cp -p "$backup" "$LOCAL_RULES_FILE"
    rm -f "$backup"
    echo "ERROR: las reglas no pasan la validación; no se aplicaron."
    exit 1
  fi
  rm -f "$backup"

  if [ -S "$SURICATA_COMMAND_SOCKET" ]; then
    suricatasc -c ruleset-reload-nonblocking
    echo "OK: reglas personalizadas guardadas y recarga solicitada."
  else
    echo "OK: reglas personalizadas guardadas. Suricata no está activo; se aplicarán al iniciar."
  fi
}

write_update_yaml() {
  url="$1"

  cat > "$UPDATE_CONF" <<EOF
disable-conf: /etc/suricata/disable.conf
enable-conf: /etc/suricata/enable.conf
modify-conf: /etc/suricata/modify.conf
drop-conf: /etc/suricata/drop.conf

ignore:
  - "*deleted.rules"

sources:
  - $url

test-command: /usr/bin/suricata -T -c /etc/suricata/suricata.yaml -S \${OUTPUT_FILENAME} -l /tmp

reload-command: /usr/bin/suricatasc -c ruleset-reload-nonblocking
EOF
}

install_version() {
  requested="$1"

  if [ "$requested" = "latest" ]; then
    manifest_url="$REPO_BASE_URL/latest.json"
    manifest="$TMP_DIR/latest.json"
    curl --fail --silent --show-error "$manifest_url" -o "$manifest"

    version="$(jq -r '.version' "$manifest")"
    artifact="$(jq -r '.artifact' "$manifest")"
  else
    version="$requested"
    manifest_url="$REPO_BASE_URL/releases/$version/manifest.json"
    manifest="$TMP_DIR/manifest-$version.json"
    curl --fail --silent --show-error "$manifest_url" -o "$manifest"

    artifact="$(jq -r '.artifact' "$manifest")"
  fi

  if [ -z "$version" ] || [ "$version" = "null" ]; then
    echo "ERROR: versión inválida."
    exit 1
  fi

  if [ -z "$artifact" ] || [ "$artifact" = "null" ]; then
    echo "ERROR: artifact inválido."
    exit 1
  fi

  url="$REPO_BASE_URL/releases/$version/$artifact"

  echo "Instalando reglas Harresi versión: $version"
  echo "URL: $url"

  current="$(get_current_version)"

  write_update_yaml "$url"

  rm -rf /var/lib/suricata/update/cache/*
  if [ -S "$SURICATA_COMMAND_SOCKET" ]; then
    suricata-update -c "$UPDATE_CONF" --force -v
  else
    echo "Info: Suricata no esta activo; se omite reload de reglas."
    suricata-update -c "$UPDATE_CONF" --force -v --no-reload
  fi

  suricata -T -c /etc/suricata/suricata.yaml -l /tmp

  jq -n \
    --arg installed_version "$version" \
    --arg previous_version "$current" \
    --arg installed_at "$(date -u --iso-8601=seconds)" \
    --arg source "$url" \
    '{
      installed_version: $installed_version,
      previous_version: $previous_version,
      installed_at: $installed_at,
      source: $source
    }' > "$STATE_FILE"

  echo "OK: instalada versión $version"
}

case "${1:-}" in
  latest)
    curl --fail --silent --show-error "$REPO_BASE_URL/latest.json" | jq .
    ;;

  list)
    curl --fail --silent --show-error "$REPO_BASE_URL/releases.txt"
    ;;

  check)
    check_version "${2:-latest}"
    ;;

  status)
    if [ -f "$STATE_FILE" ]; then
      jq . "$STATE_FILE"
    else
      echo "No hay versión registrada."
    fi
    ;;

  install)
    install_version "${2:-latest}"
    ;;

  rollback)
    previous="$(get_previous_version)"
    if [ "$previous" = "none" ] || [ -z "$previous" ]; then
      echo "ERROR: no hay versión anterior registrada."
      exit 1
    fi
    install_version "$previous"
    ;;

  next-sid)
    next_sid
    ;;

  custom-apply)
    apply_custom_rules "${2:?uso: harresi-rules custom-apply <file>}"
    ;;

  *)
    usage
    exit 1
    ;;
esac
