#!/bin/bash

# log_generator.sh - A script to send batches of logs to the Seraph agent.
#
# This script sends batches of logs to a specified URL. It can be configured
# to adjust the interval between batches, the size of each batch, and the
# probability of including an error log in a batch.

# --- Configuration ---
URL="http://localhost:8080/logs"
DEFAULT_INTERVAL_SECONDS=20
DEFAULT_BATCH_SIZE=20
DEFAULT_ERROR_CHANCE=3 # 1 in 3 chance of including an error

# --- Command-Line Argument Parsing ---
INTERVAL=${1:-$DEFAULT_INTERVAL_SECONDS}
BATCH_SIZE=${2:-$DEFAULT_BATCH_SIZE}
ERROR_CHANCE=${3:-$DEFAULT_ERROR_CHANCE}

# --- Log Templates ---
INFO_MESSAGES=(
  "service.user_auth: User authentication successful for user_id=123"
  "service.payment_processor: Payment of $59.99 processed for order_id=456"
  "service.api_gateway: GET /api/v1/status responded 200 OK in 55ms"
  "service.data_pipeline: 1500 records successfully ingested from source_s3"
  "service.cache_manager: Cache TTL updated for key 'user:profile:123'"
)
WARN_MESSAGES=(
  "service.api_gateway: High latency detected on endpoint /api/v1/data - 850ms"
  "service.database_proxy: Connection pool nearing capacity. 92% in use."
  "service.feature_flags: Configuration reload took longer than expected (2.5s)"
  "service.disk_monitor: Disk usage on /dev/sda1 has reached 85%."
)
ERROR_MESSAGES=(
  # --- Application Errors ---
  "level=error, component=auth_service, message=TypeError: Cannot read properties of null (reading 'trim')"
  "level=error, component=checkout_api, message=ValueError: Order total cannot be negative."
  "level=error, component=worker_process, message=FATAL: Unhandled promise rejection: Error: Query timed out after 3000ms"
  "level=error, component=report_generator, message=IndexError: list index out of range"
  "level=error, component=user_profile, message=KeyError: 'user_id' not found in request context"

  # --- Infrastructure Errors (On-Prem / Kubernetes) ---
  "level=error, component=kubelet, node=worker-node-7, message=NodeStatusUnknown: Kubelet stopped posting node status."
  "level=error, component=kube-proxy, message=Failed to connect to master: dial tcp 10.0.1.1:443: i/o timeout"
  "level=error, component=etcd, message=etcdserver: request timed out"
  "level=error, component=coredns, message=plugin/loop: Loop detected."
  "level=error, component=nfs_provisioner, message=DiskPressure: cannot mount volume, out of disk space"
  "level=error, component=haproxy_ingress, message=Failed to reload config: invalid backend configuration"

  # --- Cloud Provider Errors (AWS) ---
  "level=error, component=aws_rds, message=RequestLimitExceeded: You have exceeded the maximum number of DB connections."
  "level=error, component=aws_ec2_autoscaler, message=EC2InstanceLaunchError: The requested instance type 't3.large' is not available in the requested availability zone."
  "level=error, component=aws_s3_client, message=AccessDenied: Access Denied when calling the PutObject operation."
  "level=error, component=aws_lambda_function, message=ThrottlingException: Rate exceeded for function 'process-new-image'."

  # --- Cloud Provider Errors (GCP) ---
  "level=error, component=gcp_gke, message=PERMISSION_DENIED: Google Kubernetes Engine API has not been used in project 12345 before or it is disabled."
  "level=error, component=gcp_cloud_sql, message=FATAL:  password authentication failed for user 'admin'"
  "level=error, component=gcp_pubsub_subscriber, message=DeadlineExceeded: The service was unable to fulfill your request. Please try again."

  # --- Cloud Provider Errors (Azure) ---
  "level=error, component=azure_vmss, message=AllocationFailed: The VM size 'Standard_D2s_v3' is currently not available in location 'eastus'."
  "level=error, component=azure_cosmos_db, message=RequestRateTooLarge: The request rate is too large. More details: https://aka.ms/cosmosdb-error-429"
  "level=error, component=azure_aks, message=K8S: server-side apply failed: admission webhook 'validation.gatekeeper.sh' denied the request"
)

# --- Functions ---
function generate_log_line() {
  local log_type=$1
  case $log_type in
    INFO)
      echo "${INFO_MESSAGES[$((RANDOM % ${#INFO_MESSAGES[@]}))]}"
      ;;
    WARN)
      echo "${WARN_MESSAGES[$((RANDOM % ${#WARN_MESSAGES[@]}))]}"
      ;;
    ERROR)
      echo "${ERROR_MESSAGES[$((RANDOM % ${#ERROR_MESSAGES[@]}))]}"
      ;;
  esac
}

# --- Main Loop ---
echo "Starting log generator..."
echo " -> Sending logs to: $URL"
echo " -> Batch size: $BATCH_SIZE"
echo " -> Interval: $INTERVAL seconds"
echo " -> Error chance: 1 in $ERROR_CHANCE"
echo "Press [CTRL+C] to stop."

while true; do
  # Decide if this batch should contain an error
  include_error=false
  if [ $((RANDOM % ERROR_CHANCE)) -eq 0 ]; then
    include_error=true
  fi

  echo "----------------------------------------"
  echo "$(date): Generating a new batch of $BATCH_SIZE logs..."

  if $include_error; then
    echo "  -> This batch will contain an error."
  else
    echo "  -> This batch will be clean."
  fi

  # Generate the batch of logs
  log_batch=""
  error_inserted=false
  for (( i=0; i<$BATCH_SIZE; i++ )); do
    log_line=""
    # If we need to insert an error, do it at a random position
    if $include_error && ! $error_inserted && [ $((RANDOM % (BATCH_SIZE / 2))) -eq 0 ]; then
      log_line=$(generate_log_line "ERROR")
      error_inserted=true
    else
      # Generate a mix of INFO and WARN logs
      if [ $((RANDOM % 4)) -eq 0 ]; then
        log_line=$(generate_log_line "WARN")
      else
        log_line=$(generate_log_line "INFO")
      fi
    fi
    # The current API expects one log per request, so we send them one by one
    echo "  Sending log: $log_line"
    curl -s -X POST -H "Content-Type: text/plain" --data "$log_line" "$URL"
  done

  echo "Batch sent. Waiting for $INTERVAL seconds..."
  sleep $INTERVAL
done
