#!/usr/bin/env bash
# 3ling-info — Pretty banner utk 3x-ui (tanpa Docker), cek nginx via systemctl

set -euo pipefail

# --- Config 3x-ui ---
API_HOST_FILE=/etc/x-ui/api_host
API_PORT_FILE=/etc/x-ui/api_port
WEBBASE_FILE=/etc/x-ui/webbasepath
USER_FILE=/etc/x-ui/username
PASS_FILE=/etc/x-ui/password
DOMAIN=$(cat /etc/x-ui/domain)
WEB=$(cat /etc/x-ui/webbasepath)

# --- Helpers ---
read_file(){ local p="$1" def="${2:-}"; [[ -r "$p" ]] && tr -d '\r' <"$p" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//' || printf %s "$def"; }
norm_basepath(){ local s="${1:-/}"; [[ "$s" != /* ]] && s="/$s"; [[ "$s" != */ ]] && s="$s/"; printf %s "$s"; }
urlencode(){ local i ch out= LC_ALL=C; for ((i=0;i<${#1};i++)); do ch="${1:i:1}"; case "$ch" in [a-zA-Z0-9.~_-]) out+="$ch";; *) printf -v out '%s%%%02X' "$out" "'$ch";; esac; done; printf %s "$out"; }
hbytes(){ awk -v n="${1:-0}" 'function P(x,u){printf "%.1f%s",x,u}
  BEGIN{
    if(n<1024){printf "%.0fB",n; exit}
    n/=1024; if(n<1024){P(n,"KB"); exit}
    n/=1024; if(n<1024){P(n,"MB"); exit}
    n/=1024; if(n<1024){P(n,"GB"); exit}
    n/=1024; P(n,"TB")
  }'
}
pct1(){ awk -v x="${1:-0}" -v y="${2:-0}" 'BEGIN{ if(y==0){print "0.0";exit} printf "%.1f",(x*100.0)/y }'; }
uptime_hms(){ awk -v s="${1:-0}" 'BEGIN{d=int(s/86400);s%=86400;h=int(s/3600);s%=3600;m=int(s/60);s%=60;
  if(d) printf "%dd%02dh%02dm%02ds",d,h,m,s; else if(h) printf "%02dh%02dm%02ds",h,m,s; else printf "%02dm%02ds",m,s }'; }
label3(){ case "${1:-0}" in 1) echo "Okay";; -1) echo "N/A";; *) echo "Not Okay";; esac; }
hr(){ printf '%s\n' "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"; }

# colors
C_RESET=$'\e[0m'; C_CYAN=$'\e[36m'; C_GREEN=$'\e[32m'

login() {
  local base="$1" user="$2" pass="$3" cookie="$4"
  local ue pe; ue="$(urlencode "$user")"; pe="$(urlencode "$pass")"
  curl -sS -c "$cookie" -b "$cookie" -H 'Content-Type: application/x-www-form-urlencoded' \
    -X POST --data "username=$ue&password=$pe&twoFactorCode=" "${base}login" >/dev/null
}

# --- Read config & login ---
host="$(read_file "$API_HOST_FILE" 127.0.0.1)"
port="$(read_file "$API_PORT_FILE" 2053)"
webbase="$(norm_basepath "$(read_file "$WEBBASE_FILE" /)")"
user="$(read_file "$USER_FILE")"
pass="$(read_file "$PASS_FILE")"
BASE="http://${host}:${port}${webbase}"

COOKIE="$(mktemp /tmp/3ling_cookie.XXXXXX)"
trap '[[ -n "${COOKIE:-}" ]] && rm -f "$COOKIE" || true' EXIT
login "$BASE" "$user" "$pass" "$COOKIE" || true

# --- API calls (snapshot #1) ---
status_js_1="$(curl -sS -b "$COOKIE" "${BASE}panel/api/server/status" || true)"
status_ok="$(jq -r '.success' <<<"$status_js_1" 2>/dev/null || echo false)"

panel_ping="$(curl -sS -b "$COOKIE" "${BASE}panel/api/status" || true)"
panel_ok="$(jq -r '(.success // true)' <<<"$panel_ping" 2>/dev/null || echo false)"

# ✅ Xray version: ambil dari status (versi yang sedang dipakai)
xray_ver="$(jq -r '.obj.xray.version // empty' <<<"$status_js_1" 2>/dev/null || true)"
# Fallback (opsional): kalau kosong, ambil entri pertama dari daftar versi tersedia
if [[ -z "${xray_ver:-}" || "$xray_ver" == "null" ]]; then
  xver_list="$(curl -sS -b "$COOKIE" "${BASE}panel/api/server/getXrayVersion" || true)"
  xray_ver="$(jq -r '(.obj // []) | (.[0] // empty)' <<<"$xver_list" 2>/dev/null || true)"
fi

# --- Metrics dari snapshot #1 ---
uptime_s="$(jq -r '.obj.uptime // 0' <<<"$status_js_1" 2>/dev/null || echo 0)"
loads="$(jq -r '.obj.loads | if type=="array" then map(tostring)|join(", ") else "-" end' <<<"$status_js_1" 2>/dev/null || echo "-")"
pub4="$(jq -r '.obj.publicIP.ipv4 // "-" ' <<<"$status_js_1" 2>/dev/null || echo "-")"
pub6="$(jq -r '.obj.publicIP.ipv6 // "-" ' <<<"$status_js_1" 2>/dev/null || echo "-")"
tcp_now="$(jq -r '.obj.tcpCount // 0' <<<"$status_js_1" 2>/dev/null || echo 0)"
udp_now="$(jq -r '.obj.udpCount // 0' <<<"$status_js_1" 2>/dev/null || echo 0)"

cpu_pct_raw="$(jq -r '.obj.cpu // 0' <<<"$status_js_1" 2>/dev/null || echo 0)"
cpu_pct="$(awk -v v="$cpu_pct_raw" 'BEGIN{ if(v<0)v=0; if(v>100)v=100; printf "%.1f", v+0 }')"
cpu_cores="$(jq -r '.obj.cpuCores // .obj.logicalPro // 0' <<<"$status_js_1" 2>/dev/null || echo 0)"
cpu_lp="$(jq -r '.obj.logicalPro // .obj.cpuCores // 0' <<<"$status_js_1" 2>/dev/null || echo 0)"

ram_cur="$(jq -r '.obj.mem.current // 0' <<<"$status_js_1" 2>/dev/null || echo 0)"
ram_tot="$(jq -r '.obj.mem.total   // 0' <<<"$status_js_1" 2>/dev/null || echo 0)"
ram_pct="$(pct1 "$ram_cur" "$ram_tot")"

# --- Snapshot #2 untuk hitung bandwidth speed (delta netTraffic) ---
sleep 1
status_js_2="$(curl -sS -b "$COOKIE" "${BASE}panel/api/server/status" || true)"

# Total akumulatif (pakai snapshot #2 biar paling baru)
nt_sent_2="$(jq -r '.obj.netTraffic.sent // 0' <<<"$status_js_2" 2>/dev/null || echo 0)"
nt_recv_2="$(jq -r '.obj.netTraffic.recv // 0' <<<"$status_js_2" 2>/dev/null || echo 0)"

# Delta dari snapshot #1 -> #2 (bytes per detik)
nt_sent_1="$(jq -r '.obj.netTraffic.sent // 0' <<<"$status_js_1" 2>/dev/null || echo 0)"
nt_recv_1="$(jq -r '.obj.netTraffic.recv // 0' <<<"$status_js_1" 2>/dev/null || echo 0)"

rate_up=$(( nt_sent_2 - nt_sent_1 ))
rate_down=$(( nt_recv_2 - nt_recv_1 ))
(( rate_up < 0 )) && rate_up=0
(( rate_down < 0 )) && rate_down=0

# --- Total Users (non-admin, skip TLS/nTLS, only enabled) ---
inb_raw="$(curl -sS -b "$COOKIE" -H 'Accept: application/json' \
  "${BASE}panel/api/inbounds/list" | jq -c '.obj // .')"

total_users="$(
  jq -r '
    def mj: if type=="string" then (try fromjson catch {}) else . end;
    if type=="array" then .
    elif type=="object" and has("obj") then (.obj // [])
    else [] end
    | [
        .[] 
        | select((.remark // "") as $r | ($r != "TLS" and $r != "nTLS"))
        | (.settings|mj).clients[]?
        | select((.email // "") | test("^admin"; "i") | not)
        | select((.enable // true) == true)
      ]
    | length
  ' <<<"$inb_raw" 2>/dev/null || echo 0
)"

# --- Service checks ---
xray_state_api="$(jq -r '.obj.xray.state // empty' <<<"$status_js_1" 2>/dev/null || true)"
xray_ok=0; [[ "$xray_state_api" == "running" ]] && xray_ok=1
nginx_ok=0
if command -v systemctl >/dev/null 2>&1; then
  systemctl is-active --quiet nginx && nginx_ok=1 || nginx_ok=0
fi

fw_stat=-1
if command -v ufw >/dev/null 2>&1; then
  ufw status | grep -qi "Status: active" && fw_stat=1 || fw_stat=0
elif command -v firewall-cmd >/dev/null 2>&1; then
  firewall-cmd --state >/dev/null 2>&1 && fw_stat=1 || fw_stat=0
fi

panel_stat=0; [[ "$panel_ok" == "true" || "$status_ok" == "true" ]] && panel_stat=1

# --- Output ---
hr; printf "            ${C_CYAN}⇱ Service Information ⇲${C_RESET}\n"; hr
printf "❇️ Xray Core            : %s\n" "$(label3 "$xray_ok")"
printf "❇️ Nginx                : %s\n" "$(label3 "$nginx_ok")"
printf "❇️ Firewall             : %s\n" "$(label3 "$fw_stat")"
printf "❇️ 3x-ui Panel          : %s\n" "$(label3 "$panel_stat")"
printf "❇️ Username Panel       : %s\n" "$(cat /etc/x-ui/username)"
printf "❇️ Password Panel       : %s\n" "$(cat /etc/x-ui/password)"
printf "❇️ WEBUI URL            : %s\n" https://${DOMAIN}${WEB}
hr
printf "SHARING PORT 443 ${C_GREEN}3X-UI VERSION AMAN SEMUA BOSSKUH${C_RESET}\n"
hr

hr; printf "           ${C_CYAN}⇱ 3x-ui System Information ⇲${C_RESET}\n"; hr
printf "❇️  Xray Version             : %s\n" "${xray_ver:-"-"}"
printf "❇️  Memory Usage             : %s / %s (%s%%)\n" "$(hbytes "$ram_cur")" "$(hbytes "$ram_tot")" "$ram_pct"
printf "❇️  CPU Cores                : %s cores (LP: %s)\n" "$cpu_cores" "$cpu_lp"
printf "❇️  CPU Usage                : %s%%\n" "$cpu_pct"
printf "❇️  Total Users              : %s\n" "$total_users"
printf "❇️  Inbound Bandwidth        : %s\n"  "$(hbytes "$nt_recv_2")"
printf "❇️  Outbound Bandwidth       : %s\n"  "$(hbytes "$nt_sent_2")"
printf "❇️  Inbound Bandwidth Speed  : %s/s\n" "$(hbytes "$rate_down")"
printf "❇️  Outbound Bandwidth Speed : %s/s\n" "$(hbytes "$rate_up")"
hr
printf "[INFO] 3x-ui API status  : [%s] API Service %s.\n" \
  "$([[ $panel_stat -eq 1 ]] && echo "OKEY" || echo "ERROR")" \
  "$([[ $panel_stat -eq 1 ]] && echo "AMAN" || echo "TIDAK AMAN")"
hr
printf "Uptime: %s | Load: %s | Public IP: %s / %s | TCP/UDP: %s/%s\n" \
  "$(uptime_hms "$uptime_s")" "$loads" "$pub4" "$pub6" "$tcp_now" "$udp_now"
