#!/bin/bash

# Grab parameters with built-in fallbacks
SEARCH_REGEX="${1:-Starlink}"
LIMIT_COUNT="${2:-1}"

# Convert search string to lowercase for the safety pool check
LOWER_SEARCH=$(echo "$SEARCH_REGEX" | tr '[:upper:]' '[:lower:]')

# Define an intelligent data pool cap based on user request
if [[ "$LOWER_SEARCH" == *"starlink"* || "$LOWER_SEARCH" == *"oneweb"* || "$LOWER_SEARCH" == *"|"* ]]; then
    # For specific trackers, fetch a wider baseline pool (at least 20)
    FETCH_LIMIT=$(( LIMIT_COUNT > 20 ? LIMIT_COUNT : 20 ))
else
    # Otherwise, trust the user input directly
    FETCH_LIMIT=$LIMIT_COUNT
fi

# Hard-clamp the final fetch request strictly to 100 (the API's absolute max ceiling)
if [ "$FETCH_LIMIT" -gt 100 ]; then
    FETCH_LIMIT=100
fi

# Fetch the upcoming space manifest using the stable 2.3.0 production API
DATA=$(curl -s "https://ll.thespacedevs.com/2.3.0/launches/upcoming/?limit=${FETCH_LIMIT}")

# Defensive Check: Ensure the API returned a valid JSON payload containing "results"
if ! echo "$DATA" | jq -e '.results' >/dev/null 2>&1; then
    echo "CRITICAL - API Error: Received invalid response or rate limit from server | launch_alert=0"
    exit 2
fi

# Filter the data pool locally using your regex, then slice cleanly to your display limit
LAUNCH_INFO=$(echo "$DATA" | jq -r --arg regex "$SEARCH_REGEX" --argjson limit "$LIMIT_COUNT" '
  .results | 
  map(select(.name | test($regex; "i"))) | 
  .[0:$limit] | 
  .[] | 
  "\(.name) @ \(.net)"')

if [ ! -z "$LAUNCH_INFO" ]; then
    # Output matches cleanly formatted for both CLI tracking and Nagios perf-piping
    echo "OK - Target Approaching: $LAUNCH_INFO" | tr -d "|" | sed '$s/$/ | launch_alert=1/'
    exit 0
else
    echo "OK - No flights matching pattern [$SEARCH_REGEX] found in the upcoming queue | launch_alert=0"
    exit 0
fi
