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

PID_DIR="${PID_DIR:-/var/run/dubbo-dev-proxy}"
MAP_FILE="${MAP_FILE:-/opt/dubbo-dev-proxy/dubbo-proxy.map}"

printf "%-8s %-28s %-8s %-18s %s\n" "PORT" "POD_LABEL" "PID" "TARGET" "STATUS"
printf "%-8s %-28s %-8s %-18s %s\n" "----" "---------" "---" "------" "------"

while IFS= read -r line || [[ -n "$line" ]]; do
  [[ -z "$line" || "$line" =~ ^[[:space:]]*# ]] && continue
  IFS='|' read -r port pod_label target_port <<< "$line"
  pid_file="${PID_DIR}/${port}.pid"
  pid="-"
  status="stopped"
  target="-"
  if [[ -f "$pid_file" ]]; then
    pid="$(cat "$pid_file" 2>/dev/null || echo -)"
    if [[ -n "$pid" ]] && kill -0 "$pid" 2>/dev/null; then
      status="running"
      target="$(ss -lntp 2>/dev/null | awk -v p=":${port} " '$0 ~ p {print}' | head -1 || true)"
      [[ -z "$target" ]] && target="listen :${port}"
    fi
  fi
  printf "%-8s %-28s %-8s %-18s %s\n" "$port" "$pod_label" "$pid" "$target" "$status"
done < "$MAP_FILE"
