#!/bin/bash
#
# DSS - Service & Port Discovery
# Lists running services, bound ports, and process relationships
#

set -e

# Get listening ports
get_listening_ports() {
  local ports=()

  # Use ss if available, fallback to netstat
  if command -v ss &> /dev/null; then
    while IFS= read -r line; do
      local port=$(echo "$line" | awk '{print $5}' | grep -oE '[0-9]+$')
      local process=$(echo "$line" | awk '{print $7}' | sed 's/users:(("//' | sed 's/",.*//')
      if [[ -n "$port" && "$port" =~ ^[0-9]+$ ]]; then
        ports+=("{\"port\":$port,\"process\":\"$process\",\"state\":\"LISTEN\"}")
      fi
    done < <(ss -tlnp 2>/dev/null | tail -n +2)
  elif command -v netstat &> /dev/null; then
    while IFS= read -r line; do
      local port=$(echo "$line" | awk '{print $4}' | grep -oE '[0-9]+$')
      local process=$(echo "$line" | awk '{print $7}')
      if [[ -n "$port" && "$port" =~ ^[0-9]+$ ]]; then
        ports+=("{\"port\":$port,\"process\":\"$process\",\"state\":\"LISTEN\"}")
      fi
    done < <(netstat -tlnp 2>/dev/null | grep LISTEN)
  fi

  echo "${ports[@]}"
}

# Check common development ports
check_dev_ports() {
  local common_ports=(
    "3000:Node.js/React Dev"
    "3456:DSS Worker"
    "5000:Flask/Python"
    "5173:Vite"
    "8000:Django/FastAPI"
    "8080:Generic HTTP"
    "8888:Jupyter"
    "9000:PHP-FPM"
    "27017:MongoDB"
    "5432:PostgreSQL"
    "3306:MySQL"
    "6379:Redis"
  )

  local status=()

  for entry in "${common_ports[@]}"; do
    local port="${entry%%:*}"
    local name="${entry#*:}"

    if ss -tln 2>/dev/null | grep -q ":$port " || netstat -tln 2>/dev/null | grep -q ":$port "; then
      status+=("{\"port\":$port,\"name\":\"$name\",\"active\":true}")
    fi
  done

  echo "${status[@]}"
}

# Get service health for known ports
check_health() {
  local results=()

  # Check DSS Worker
  if curl -s --connect-timeout 2 "http://localhost:3456/health" > /dev/null 2>&1; then
    local health=$(curl -s "http://localhost:3456/health" 2>/dev/null)
    results+=("{\"service\":\"dss-worker\",\"port\":3456,\"healthy\":true,\"response\":$health}")
  fi

  # Check if port 8000 responds
  if curl -s --connect-timeout 2 "http://localhost:8000" > /dev/null 2>&1; then
    results+=("{\"service\":\"orchestrator\",\"port\":8000,\"healthy\":true}")
  fi

  echo "${results[@]}"
}

# Build output
listening=$(get_listening_ports)
dev_ports=$(check_dev_ports)
health=$(check_health)

listening_json=$(IFS=,; echo "${listening[*]}")
dev_json=$(IFS=,; echo "${dev_ports[*]}")
health_json=$(IFS=,; echo "${health[*]}")

cat <<EOF
{
  "scan_type": "ports",
  "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
  "hostname": "$(hostname)",
  "listening_ports": [${listening_json:-}],
  "dev_services": [${dev_json:-}],
  "health_checks": [${health_json:-}]
}
EOF
