#!/bin/bash
set -euo pipefail

listener_present() {
  # $1 = port (angka), return 0 kalau ada proses listen di port tsb (alamat apa pun)
  local port="$1"
  if command -v ss >/dev/null 2>&1; then
    ss -ltn 2>/dev/null | grep -qE "[:.]${port}[[:space:]]"
  else
    netstat -ltn 2>/dev/null | grep -qE "[:.]${port}[[:space:]]"
  fi
}
# ====== Konfigurasi dasar ======
domain="$(cat /root/domain)"
token="$(jq -r .access_token /root/token.json)"
api_host="127.0.0.1"

get_marzban_api_port() {
  local env_file="/opt/marzban/.env"
  [[ -r "$env_file" ]] || { echo "7879"; return; }
  local port
  port="$(grep -E '^[[:space:]]*UVICORN_PORT[[:space:]]*=' "$env_file" \
           | tail -n1 | sed -E 's/.*=[[:space:]]*["'\'']?([0-9]+).*/\1/')"
  [[ "$port" =~ ^[0-9]+$ ]] && echo "$port" || echo "7879"
}
api_port="$(get_marzban_api_port)"

# ====== Warna & label ======
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[0;33m'
BLUE='\033[0;34m' PURPLE='\033[0;35m'; CYAN='\033[0;36m'; LIGHT='\033[0;37m'; NC='\033[0m'

ERROR="[${RED}ERROR${NC}]"
INFO="[${YELLOW}INFO${NC}]"
OKEY="[${GREEN}OKEY${NC}]"
NOTE="[${BLUE}NOTE${NC}]"

# ====== Versi Marzban (docker image tag → label) ======
versimarzban="$(grep -m1 'image: gozargah/marzban:' /opt/marzban/docker-compose.yml 2>/dev/null | awk -F: '{print $3}' | tr -d '\r')"
case "${versimarzban:-}" in
  latest) versimarzban="latest" ;;
  dev)    versimarzban="dev" ;;
  ""|*)   : ;;
esac

# VAR 2
if [[ $(systemctl status docker | grep -w active | awk '{print $2}' | sed 's/(//g' | sed 's/)//g' | sed 's/ //g') == 'active' ]]; then
    DOCKER="${GREEN}Okay${NC}";
else
    DOCKER="${RED}Not Okay${NC}";
fi
if [[ $(netstat -ntlp | grep -i xray | grep -i :::443 | awk '{print $4}' | cut -d: -f4 | xargs | sed -e 's/ /, /g') == '443' ]]; then
    XRAY="${GREEN}Okay${NC}";
    MARZ_STATUS="SHARING PORT 443 MARZBAN VERSION AMAN SEMUA BOSSKUH"
else
    XRAY="${RED}Not Okay${NC}";
    MARZ_STATUS="ADA ERROR BOSSKUH"
fi
if [[ $(netstat -ntlp | grep -i nginx | grep -i 0.0.0.0:8081 | awk '{print $4}' | cut -d: -f2 | xargs | sed -e 's/ /, /g') == '8081' ]]; then
    NGINX="${GREEN}Okay${NC}";
else
    NGINX="${RED}Not Okay${NC}";
fi
if [[ $(systemctl status ufw | grep -w active | awk '{print $2}' | sed 's/(//g' | sed 's/)//g' | sed 's/ //g') == 'active' ]]; then
    UFW="${GREEN}Okay${NC}";
else
    UFW="${RED}Not Okay${NC}";
fi
if [[ $(netstat -ntlp | grep -i python | grep -i 127.0.0.1:7879 | awk '{print $4}' | cut -d: -f2 | xargs | sed -e 's/ /, /g') == '7879' ]]; then
    MARZ="${GREEN}Okay${NC}";
else
    MARZ="${RED}Not Okay${NC}";
fi

# ====== Info sistem dari Marzban ======
get_marzban_info() {
  local url="http://${api_host}:${api_port}/api/system"
  local res
  res="$(curl -sS -X GET "$url" -H 'accept: application/json' -H "Authorization: Bearer $token")" || {
    echo -e "${ERROR} Gagal menghubungi API Marzban."; exit 1; }
  marzban_version="$(jq -r '.version' <<<"$res")"
  mem_total="$(jq -r '.mem_total' <<<"$res")"
  mem_used="$(jq -r '.mem_used' <<<"$res")"
  cpu_cores="$(jq -r '.cpu_cores' <<<"$res")"
  cpu_usage="$(jq -r '.cpu_usage' <<<"$res")"
  total_user_api="$(jq -r '.total_user' <<<"$res")"
  users_active_api="$(jq -r '.users_active' <<<"$res")"
  incoming_bandwidth="$(jq -r '.incoming_bandwidth' <<<"$res")"
  outgoing_bandwidth="$(jq -r '.outgoing_bandwidth' <<<"$res")"
  incoming_bandwidth_speed="$(jq -r '.incoming_bandwidth_speed' <<<"$res")"
  outgoing_bandwidth_speed="$(jq -r '.outgoing_bandwidth_speed' <<<"$res")"

  mem_used_human="$(numfmt --to=iec-i --suffix=B "$mem_used")"
  mem_total_human="$(numfmt --to=iec-i --suffix=B "$mem_total")"
  incoming_bandwidth_human="$(numfmt --to=iec-i --suffix=B --format="%.2f" <<<"$incoming_bandwidth")"
  outgoing_bandwidth_human="$(numfmt --to=iec-i --suffix=B --format="%.2f" <<<"$outgoing_bandwidth")"
  incoming_bandwidth_speed_human="$(numfmt --to=iec-i --suffix=Bps --format="%.2f" <<<"$incoming_bandwidth_speed")"
  outgoing_bandwidth_speed_human="$(numfmt --to=iec-i --suffix=Bps --format="%.2f" <<<"$outgoing_bandwidth_speed")"
  online_users_api="$(jq -r '.online_users' <<<"$res")"
}
get_marzban_info

# ====== Xray Core version ======
get_xray_core_version() {
  local url="http://${api_host}:${api_port}/api/core"
  local res; res="$(curl -sS -X GET "$url" -H 'accept: application/json' -H "Authorization: Bearer ${token}")" || true
  jq -r '.version // "Unknown"' <<<"$res"
}
xray_core_version="$(get_xray_core_version)"

# ====== Hitung user (pakai tmpfile; jq→JSON; baca field per-key) ======
tmpdir="$(mktemp -d)"; cleanup() { rm -rf "$tmpdir"; }; trap cleanup EXIT

limit=200; offset=0
count_total=0; count_enabled=0; count_disabled=0; count_expired=0; count_limited=0
count_vmess=0; count_vless=0; count_trojan=0; count_shadowsocks=0

# sementara matikan -e di blok ini agar tidak exit kalau ada edge-case parsing
set +e
while :; do
  page_json="${tmpdir}/users_${offset}.json"
  curl -sS -G "http://${api_host}:${api_port}/api/users" \
    --data-urlencode "offset=${offset}" \
    --data-urlencode "limit=${limit}" \
    -H 'accept: application/json' \
    -H "Authorization: Bearer ${token}" > "$page_json"

  arr_json="${tmpdir}/arr_${offset}.json"
  jq '.users // .' "$page_json" > "$arr_json"
  if [[ $? -ne 0 ]]; then echo "[]" > "$arr_json"; fi

  n_in_page="$(jq 'length' "$arr_json" 2>/dev/null)"; rc=$?
  if [[ $rc -ne 0 || -z "$n_in_page" ]]; then n_in_page=0; fi
  if [[ "$n_in_page" -eq 0 ]]; then break; fi

  # keluarkan JSON ringkas per halaman
  stat_json="${tmpdir}/stat_${offset}.json"
  jq '
    reduce .[] as $u (
      {vmess:0,vless:0,trojan:0,shadowsocks:0,active:0,disabled:0,expired:0,limited:0,total:0};
      .total += 1
      | (if ($u.proxies // {} | has("vmess")) then .vmess += 1 else . end)
      | (if ($u.proxies // {} | has("vless")) then .vless += 1 else . end)
      | (if ($u.proxies // {} | has("trojan")) then .trojan += 1 else . end)
      | (if ($u.proxies // {} | has("shadowsocks")) then .shadowsocks += 1 else . end)
      | (if $u.status=="active"   then .active   += 1
         elif $u.status=="disabled" then .disabled += 1
         elif $u.status=="expired"  then .expired  += 1
         elif $u.status=="limited"  then .limited  += 1
         else . end)
    )
  ' "$arr_json" > "$stat_json"

  # baca tiap field aman (default 0)
  t="$(jq -r '.total        // 0' "$stat_json" 2>/dev/null)"; [[ -z "$t" ]] && t=0
  a="$(jq -r '.active       // 0' "$stat_json" 2>/dev/null)"; [[ -z "$a" ]] && a=0
  d="$(jq -r '.disabled     // 0' "$stat_json" 2>/dev/null)"; [[ -z "$d" ]] && d=0
  e="$(jq -r '.expired      // 0' "$stat_json" 2>/dev/null)"; [[ -z "$e" ]] && e=0
  l="$(jq -r '.limited      // 0' "$stat_json" 2>/dev/null)"; [[ -z "$l" ]] && l=0
  vm="$(jq -r '.vmess       // 0' "$stat_json" 2>/dev/null)"; [[ -z "$vm" ]] && vm=0
  vl="$(jq -r '.vless       // 0' "$stat_json" 2>/dev/null)"; [[ -z "$vl" ]] && vl=0
  tr="$(jq -r '.trojan      // 0' "$stat_json" 2>/dev/null)"; [[ -z "$tr" ]] && tr=0
  ss="$(jq -r '.shadowsocks // 0' "$stat_json" 2>/dev/null)"; [[ -z "$ss" ]] && ss=0

  # paksa base10 (hindari leading zero dianggap oktal oleh bash lama)
  ((count_total+=10#$t))
  ((count_enabled+=10#$a))
  ((count_disabled+=10#$d))
  ((count_expired+=10#$e))
  ((count_limited+=10#$l))
  ((count_vmess+=10#$vm))
  ((count_vless+=10#$vl))
  ((count_trojan+=10#$tr))
  ((count_shadowsocks+=10#$ss))

  [[ "$n_in_page" -lt "$limit" ]] && break
  offset=$((offset + limit))
done
set -e
# sentinel debug (kalau perlu)
# echo "[DEBUG] agg OK: total=$count_total active=$count_enabled disabled=$count_disabled expired=$count_expired limited=$count_limited | vm=$count_vmess vl=$count_vless tr=$count_trojan ss=$count_shadowsocks" >&2

# ====== OUTPUT ======
echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "\E[44;1;39m            ⇱ Service Information ⇲             \E[0m"
echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "❇️ Docker Container     : $DOCKER"
echo -e "❇️ Xray Core            : $XRAY"
echo -e "❇️ Nginx                : $NGINX"
echo -e "❇️ Firewall             : $UFW"
echo -e "❇️ Marzban Panel        : $MARZ"
echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "$MARZ_STATUS"
echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "\E[44;1;39m        ⇱ Marzban System Information ⇲          \E[0m"
echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "❇️ Marzban Version          : ${LIGHT}${marzban_version}${NC} ${BLUE}${versimarzban}${NC}"
echo -e "❇️ XrayCore Version         : ${LIGHT}${xray_core_version}${NC}"
echo -e "❇️ Memory Usage             : ${LIGHT}${mem_used_human}/${mem_total_human}${NC}"
echo -e "❇️ CPU Cores                : ${LIGHT}${cpu_cores} cores${NC}"
echo -e "❇️ CPU Usage                : ${LIGHT}${cpu_usage}%${NC}"
echo -e "❇️ Inbound Bandwidth        : ${LIGHT}${incoming_bandwidth_human}${NC}"
echo -e "❇️ Outbound Bandwidth       : ${LIGHT}${outgoing_bandwidth_human}${NC}"
echo -e "❇️ Inbound Bandwidth Speed  : ${LIGHT}${incoming_bandwidth_speed_human}${NC}"
echo -e "❇️ Outbound Bandwidth Speed : ${LIGHT}${outgoing_bandwidth_speed_human}${NC}"
echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "\E[44;1;39m        ⇱ Users per Protocol & Status ⇲         \E[0m"
echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "📦 Total Users   : ${LIGHT}${count_total}${NC}"
echo -e "  • VMess        : ${LIGHT}${count_vmess}${NC}"
echo -e "  • VLess        : ${LIGHT}${count_vless}${NC}"
echo -e "  • Trojan       : ${LIGHT}${count_trojan}${NC}"
echo -e "  • Shadowsocks  : ${LIGHT}${count_shadowsocks}${NC}"
echo -e ""
echo -e "🧩 Status breakdown:"
echo -e "  • Enabled/Active : ${GREEN}${count_enabled}${NC}"
echo -e "  • Disabled       : ${YELLOW}${count_disabled}${NC}"
echo -e "  • Expired        : ${RED}${count_expired}${NC}"
echo -e "  • Limited        : ${PURPLE}${count_limited}${NC}"
echo -e "  • Users Online   : ${GREEN}${online_users_api}${NC}"
echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${INFO} Marzban API status : ${OKEY} API Service AMAN.${NC}"
echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
