#!/bin/bash

domain=$(cat /root/domain)
token=$(cat /root/token.json | jq -r .access_token)
api_host="127.0.0.1"
get_marzban_api_port() {
  local env_file="/opt/marzban/.env"
  [[ -r "$env_file" ]] || { echo "7879"; return; }   # fallback opsional

  local port
  port="$(grep -E '^[[:space:]]*UVICORN_PORT[[:space:]]*=' "$env_file" \
           | tail -n1 \
           | sed -E 's/.*=[[:space:]]*["'\'']?([0-9]+).*/\1/')"

  # Validasi angka
  if [[ "$port" =~ ^[0-9]+$ ]]; then
    echo "$port"
  else
    echo "7879"   # fallback opsional lain
  fi
}

api_port="$(get_marzban_api_port)"

# Code for service
export RED='\033[0;31m';
export GREEN='\033[0;32m';
export YELLOW='\033[0;33m';
export BLUE='\033[0;34m';
export PURPLE='\033[0;35m';
export CYAN='\033[0;36m';
export LIGHT='\033[0;37m';
export NC='\033[0m';

# Export Banner Status Information
export ERROR="[${RED}ERROR${NC}]";
export INFO="[${YELLOW}INFO${NC}]";
export OKEY="[${GREEN}OKEY${NC}]";
export PENDING="[${YELLOW}PENDING${NC}]";
export SEND="[${YELLOW}SEND${NC}]";
export RECEIVE="[${YELLOW}RECEIVE${NC}]";

# VAR
versimarzban=$(grep 'image: gozargah/marzban:' /opt/marzban/docker-compose.yml | awk -F: '{print $3}')
  # Replace values and specific version
  case "${versimarzban}" in
    "latest") versimarzban="Stable";;
    "dev") versimarzban="Beta";;
  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

# Function to fetch system information from Marzban API
function get_marzban_info() {

    local marzban_api="http://${api_host}:${api_port}/api/system"
    local marzban_info=$(curl -s -X 'GET' "$marzban_api" -H 'accept: application/json' -H "Authorization: Bearer $token")

    if [[ $? -eq 0 ]]; then
# Parsing Marzban API response
marzban_version=$(echo "$marzban_info" | jq -r '.version')
mem_total=$(echo "$marzban_info" | jq -r '.mem_total')
mem_used=$(echo "$marzban_info" | jq -r '.mem_used')
cpu_cores=$(echo "$marzban_info" | jq -r '.cpu_cores')
cpu_usage=$(echo "$marzban_info" | jq -r '.cpu_usage')
total_user=$(echo "$marzban_info" | jq -r '.total_user')
users_active=$(echo "$marzban_info" | jq -r '.users_active')
incoming_bandwidth=$(echo "$marzban_info" | jq -r '.incoming_bandwidth')
outgoing_bandwidth=$(echo "$marzban_info" | jq -r '.outgoing_bandwidth')
incoming_bandwidth_speed=$(echo "$marzban_info" | jq -r '.incoming_bandwidth_speed')
outgoing_bandwidth_speed=$(echo "$marzban_info" | jq -r '.outgoing_bandwidth_speed')

# Convert values to human-readable format
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")
    else
        echo -e "${ERROR} Failed to fetch Marzban information."
        exit 1
    fi
}
# Usage of the function
get_marzban_info "your_domain_here" "your_token_here"

# Function to get Xray Core version
function get_xray_core_version() {
    xray_core_info=$(curl -s -X 'GET' \
        "http://${api_host}:${api_port}/api/core" \
        -H 'accept: application/json' \
        -H "Authorization: Bearer ${token}"
    )
    xray_core_version=$(echo "$xray_core_info" | jq -r '.version')

    echo "$xray_core_version"
}
# Get Xray Core version
xray_core_version=$(get_xray_core_version "$domain" "$token")

# Output service information
echo ""
echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\033[0m${NC}"
echo -e "\E[44;1;39m            ⇱ Service Information ⇲             \E[0m"
echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\033[0m${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}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\033[0m${NC}"
echo -e "$MARZ_STATUS"
echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\033[0m${NC}"

# Output Marzban information
echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\033[0m${NC}"
echo -e "\E[44;1;39m           ⇱ Marzban System Information ⇲           \E[0m"
echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\033[0m${NC}"
echo -e "❇️ Marzban Version          : ${LIGHT}${marzban_version} \e[94m$versimarzban\e[0m${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 "❇️ Total Users              : ${LIGHT}${users_active}/${total_user}${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}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\033[0m${NC}"
echo -e "${INFO} Marzban API status  : ${OKEY} API Service AMAN.${NC}"
echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\033[0m${NC}"
echo -e ""
