#!/bin/bash
clear
ipsaya=$(wget -qO- ipinfo.io/ip)
data_server=$(curl -v --insecure --silent https://google.com/ 2>&1 | grep Date | sed -e 's/< Date: //')
date_list=$(date +"%Y-%m-%d" -d "$data_server")
data_ip="https://raw.githubusercontent.com/RozTun/permission/main/ip"
ISP=$(cat /etc/xray/isp)
CITY=$(cat /etc/xray/city)
PUB=$(cat /etc/slowdns/server.pub)
NS=$(cat /etc/xray/dns)
domain=$(cat /etc/xray/domain)
checking_sc() {
  useexp=$(wget -qO- $data_ip | grep $ipsaya | awk '{print $3}')
  if [[ $date_list < $useexp ]]; then
    echo -ne
  else
    echo -e "${OR}────────────────────────────────────────────${NC}"
    echo -e "\033[42m          HUNTERTUNNEL AUTOSCRIPT          ${NC}"
    echo -e "${OR}────────────────────────────────────────────${NC}"
    echo -e ""
    echo -e "            ${RED}PERMISSION DENIED !${NC}"
    echo -e "   \033[0;33mYour VPS${NC} $ipsaya \033[0;33mHas been Banned${NC}"
    echo -e "     \033[0;33mBuy access permissions for scripts${NC}"
    echo -e "             \033[0;33mContact Admin :${NC}"
    echo -e "      ${Green}WhatsApp${NC} wa.me/6285759375937"
    echo -e "         \033[0;36mTelegram${NC} t.me/RozTun"
    echo -e "${OR}────────────────────────────────────────────${NC}"
    exit
  fi
}
checking_sc
clear

# Variables
green="\e[38;5;82m"
red="\e[38;5;196m"
neutral="\e[0m"
orange="\e[38;5;130m"
blue="\e[38;5;39m"
yellow="\e[38;5;226m"
purple="\e[38;5;141m"
bold_white="\e[1;37m"
reset="\e[0m"
g="\033[1;93m"
gb="\e[92;1m"
b="\033[0;36m"
p="\033[0m"
r="\033[0;31m"
y="\033[0;33m"

# Function to print rainbow text
        print_rainbow() {
            local text="$1"
            local length=${#text}
            local start_color=(0 5 0)
            local mid_color=(0 200 0)
            local end_color=(0 5 0)

            for ((i = 0; i < length; i++)); do
                local progress=$((i * 100 / (length - 1)))

                if [ $progress -lt 50 ]; then
                    local factor=$((progress * 2))
                    r=$(( (start_color[0] * (100 - factor) + mid_color[0] * factor) / 100 ))
                    g=$(( (start_color[1] * (100 - factor) + mid_color[1] * factor) / 100 ))
                    b=$(( (start_color[2] * (100 - factor) + mid_color[2] * factor) / 100 ))
                else
                    local factor=$(((progress - 50) * 2))
                    r=$(( (mid_color[0] * (100 - factor) + end_color[0] * factor) / 100 ))
                    g=$(( (mid_color[1] * (100 - factor) + end_color[1] * factor) / 100 ))
                    b=$(( (mid_color[2] * (100 - factor) + end_color[2] * factor) / 100 ))
                fi

                printf "\e[38;2;%d;%d;%dm%s" "$r" "$g" "$b" "${text:$i:1}"
            done
            echo -e "$reset" # Reset color at the end
        }
        
        


print_rainbo() {
    local text="$1"
    local length=${#text}
    local start_color=(255 255 0) # yellow
    local mid_color=(0 255 0)     # green
    local end_color=(255 255 0)   # yellow

    for ((i = 0; i < length; i++)); do
        local progress=$((i * 100 / (length - 1)))

        if [ $progress -lt 50 ]; then
            local factor=$((progress * 2))
            r=$((start_color[0] * (100 - factor) / 100 + mid_color[0] * factor / 100))
            g=$((start_color[1] * (100 - factor) / 100 + mid_color[1] * factor / 100))
            b=$((start_color[2] * (100 - factor) / 100 + mid_color[2] * factor / 100))
        else
            local factor=$(((progress - 50) * 2))
            r=$((mid_color[0] * (100 - factor) / 100 + end_color[0] * factor / 100))
            g=$((mid_color[1] * (100 - factor) / 100 + end_color[1] * factor / 100))
            b=$((mid_color[2] * (100 - factor) / 100 + end_color[2] * factor / 100))
        fi

        printf "\e[38;2;%d;%d;%dm%s" "$r" "$g" "$b" "${text:$i:1}"
    done
    echo -e "$reset"
}
        
function con() {
    local -i bytes=$1;
    if [[ $bytes -lt 1024 ]]; then
        echo "${bytes}B"
    elif [[ $bytes -lt 1048576 ]]; then
        echo "$(( (bytes + 1023)/1024 ))KB"
    elif [[ $bytes -lt 1073741824 ]]; then
        echo "$(( (bytes + 1048575)/1048576 ))MB"
    else
        echo "$(( (bytes + 1073741823)/1073741824 ))GB"
    fi
}


# function to convert bytes to a more readable format
convert_size() {
    local -i bytes=$1
    if [[ $bytes -lt 1024 ]]; then
        echo "${bytes}B"
    elif [[ $bytes -lt 1048576 ]]; then
        echo "$(((bytes + 1023) / 1024))KB"
    elif [[ $bytes -lt 1073741824 ]]; then
        echo "$(((bytes + 1048575) / 1048576))MB"
    else
        echo "$(((bytes + 1073741823) / 1073741824))GB"
    fi
}

checkvmess() {
g="\033[1;93m"
gb="\e[92;1m"
b="\033[0;36m"
p="\033[0m"
r="\033[0;31m"
y="\033[0;33m"

# Fungsi untuk menampilkan garis atas
clear
function line_atas() {
  echo -e " ${orange}┌──────────────────────────────────────────┐${p}"
}

# Fungsi untuk menampilkan garis bawah
function line_bawah() {
  echo -e " ${orange}└──────────────────────────────────────────┘${p}"
}

# Fungsi untuk menampilkan garis tengah
function line_tengah() {
  echo -e "   ${orange}────────────────────────────────────────${p}"
}

# Mengecek dan membuat direktori jika belum ada
    echo ""
    # Direktori untuk IP limit dan kuota akun VMess
    dir="/etc/biji/limit/vmess/ip"
    dir1="/etc/limit/vmess"
    [[ ! -d "$dir" ]] && mkdir -p "$dir"
    [[ ! -d "$dir1" ]] && mkdir -p "$dir1"

    # Mendapatkan daftar akun VMess dari config.json
    data5=( $(grep '###' /etc/xray/config.json | cut -d ' ' -f 2 | sort -u) )

    for akun in "${data5[@]}"; do
        [[ ! -e /etc/biji/limit/vmess/ip/$akun ]] && echo "2" > /etc/biji/limit/vmess/ip/$akun
        [[ ! -e /etc/vmess/$akun ]] && echo "107374182400" > /etc/vmess/$akun
        [[ ! -e /etc/limit/vmess/$akun ]] && echo "0" > /etc/limit/vmess/$akun
    done >/dev/null 2>&1

    clear
    # Membersihkan file sementara
    > /tmp/other.txt
    > /tmp/ipvmess.txt

    # Mendapatkan daftar akun VMess dari file config.json
    data=( $(cat /etc/xray/config.json | grep '###' | cut -d ' ' -f 2 | sort | uniq) )

    # Menampilkan banner
    line_atas
    echo -e " ${green}      Check Login Xray/Vmess Account            ${p}"
    line_bawah
    line_atas
    echo -e " ${green}    Username      ${orange}|${green}  Quota  ${orange}|${green}  IP Address${p}"
    line_tengah

    for akun in "${data[@]}"; do
        if [[ -z "$akun" ]]; then
            akun="tidakada"
        fi
        echo -n > /tmp/ipvmess.txt
        data2=( `cat /var/log/xray/access.log | tail -n 500 | awk -F "from " '{print $2}' | grep email | grep "accepted tcp" | cut -d: -f1| cut -d[ -f2 | sort | uniq`);
        for ip in "${data2[@]}"; do
            jum=$(cat /var/log/xray/access.log | grep -wE "$akun" | tail -n 500 | awk -F "from " '{print $2}'| sed 's/tcp://g' | cut -d ":" -f 1 | grep -w "$ip" | sort | uniq)
            if [[ "$jum" = "$ip" ]]; then
                echo "$jum" >> /tmp/ipvmess.txt
            else
                echo "$ip" >> /tmp/other.txt
            fi
            jum2=$(cat /tmp/ipvmess.txt)
            sed -i "/$jum2/d" /tmp/other.txt > /dev/null 2>&1
        done
        jum=$(cat /tmp/ipvmess.txt)
        if [[ -z "$jum" ]]; then
            echo > /dev/null
        else
            iplimit=$(cat /etc/biji/limit/vmess/ip/${akun})
            jum2=$(cat /tmp/ipvmess.txt | wc -l)
            byte=$(cat /etc/vmess/${akun})
            lim=$(con ${byte})
            wey=$(cat /etc/limit/vmess/${akun})

            # Jika kuota maksimum adalah 0, tandai sebagai Unlimited
            if [[ $wey -eq 0 ]]; then
                gb="Unlimited (unl)"
            else
                gb=$(con ${wey})
            fi

            lastlogin=$(cat /var/log/xray/access.log | grep -wE "$akun" | tail -n 500 | cut -d " " -f 2 | tail -1)

            # Menampilkan informasi akun dalam format yang diinginkan
            printf "    %-13s - %-9s - %-6s\n" "${akun}" "${gb}/${lim}" "$jum2/$iplimit IP"

            # Membersihkan file sementara
            rm -f /tmp/ipvmess.txt
        fi
    done
    line_bawah
    # Membersihkan file sementara
    rm -f /tmp/other.txt
}

dellvmess() {
    clear
    CONFIG_FILE="/etc/xray/config.json"

    # Periksa jumlah akun
    NUMBER_OF_CLIENTS=$(grep -c -E "^### " "$CONFIG_FILE")
    if [[ $NUMBER_OF_CLIENTS -eq 0 ]]; then
        echo -e "${orange}─────────────────────────────────────────${neutral}"
        echo -e "   ${green}.::::. HAPUS AKUN VMESS .::::.${neutral}"
        echo -e "${orange}─────────────────────────────────────────${neutral}"
        echo -e "${red}Tidak ada akun VMess yang bisa dihapus!${neutral}"
        echo -e "${orange}─────────────────────────────────────────${neutral}"
        exit 1
    fi

    # Tampilkan daftar akun
    echo -e "${orange}─────────────────────────────────────────${neutral}"
    echo -e "    ${green}.::::. HAPUS AKUN VMESS .::::.${neutral}"
    echo -e "${orange}─────────────────────────────────────────${neutral}"
    echo -e "${yellow} No   Username   Expired${neutral}"
    echo -e "${orange}─────────────────────────────────────────${neutral}"
    grep -E "^### " "$CONFIG_FILE" | cut -d ' ' -f 2-3 | sort | uniq | nl -w2 -s'. '

    # Input pengguna
    echo -e "${orange}─────────────────────────────────────────${neutral}"
    read -rp "Masukkan nomor atau username: " input

    if [[ $input =~ ^[0-9]+$ ]]; then
        # Input berupa angka
        user=$(grep -E "^### " "$CONFIG_FILE" | cut -d ' ' -f 2 | sort | uniq | awk 'NR=='$input)
        exp=$(grep -E "^### " "$CONFIG_FILE" | cut -d ' ' -f 3 | sort | uniq | awk 'NR=='$input)
    else
        # Input berupa username
        user=$input
        exp=$(grep -wE "^### $user" "$CONFIG_FILE" | awk '{print $3}')
    fi

    # Validasi input
    if [[ -z $user || -z $exp ]]; then
        echo -e "${red}Akun tidak ditemukan!${neutral}"
        echo -e "${orange}─────────────────────────────────────────${neutral}"
        exit 1
    fi

    # Hapus dari file konfigurasi
    sed -i "/^### $user $exp/,/^},{/d" "$CONFIG_FILE"

    # Hapus dari database
    if grep -qE "^### $user $exp" /etc/vmess/.vmess.db; then
        echo "Menghapus entri dari database..."
        sed -i "/^### $user $exp.*/d" /etc/vmess/.vmess.db
        echo "Entri berhasil dihapus dari database."
    else
        echo "Entri tidak ditemukan di database."
    fi

    # Hapus file terkait
    rm -rf /etc/vmess/$user
    rm -rf /etc/biji/limit/vmess/ip/$user
    rm -f "/etc/xray/log-create-${user}.log"
    rm -f "/etc/xray/${user}-non.json"
    rm -f "/etc/xray/${user}-tls.json"
    rm -f "/etc/xray/${user}-grpc.json"
    rm -f "/etc/xray/${user}-hu.json"

    # Restart layanan Xray
    systemctl restart xray > /dev/null 2>&1

    # Tampilkan pesan sukses
    clear
    echo -e "${green}┌─────────────────────────────────────────┐${neutral}"
    echo -e "${green}│    AKUN VMESS BERHASIL DIHAPUS          │${neutral}"
    echo -e "${green}└─────────────────────────────────────────┘${neutral}"
    echo -e "Username     : ${green}$user${neutral}"
    echo -e "Akun telah dihapus secara permanen."
    echo ""
    read -n 1 -s -r -p "Tekan sembarang tombol untuk kembali"
    dumpt
}

renewvmess() {
    clear
    CONFIG_FILE="/etc/xray/config.json"

    # Check number of accounts
    NUMBER_OF_CLIENTS=$(grep -c -E "^### " "$CONFIG_FILE")
    if [[ $NUMBER_OF_CLIENTS -eq 0 ]]; then
        echo -e "${orange}─────────────────────────────────────────${neutral}"
        echo -e "   ${green}.::::. RENEW VMESS ACCOUNT .::::.${neutral}"
        echo -e "${orange}─────────────────────────────────────────${neutral}"
        echo -e "${red}No VMess accounts available to renew!${neutral}"
        echo -e "${orange}─────────────────────────────────────────${neutral}"
        exit 1
    fi

    # Display the list of accounts
    echo -e "${orange}─────────────────────────────────────────${neutral}"
    echo -e "    ${green}.::::. RENEW VMESS ACCOUNT .::::.${neutral}"
    echo -e "${orange}─────────────────────────────────────────${neutral}"
    printf "%-4s %-15s %-15s %-10s\n" "No" "Username" "Expired" "Limit.quota"
    echo -e "${orange}─────────────────────────────────────────${neutral}"

    declare -A users
    i=1
    while read -r line; do
        user=$(echo "$line" | cut -d ' ' -f 2)
        exp=$(echo "$line" | cut -d ' ' -f 3)
        if [[ -z "${users[$user]}" ]]; then
            quota_file="/etc/vmess/$user"
            if [[ -f $quota_file ]]; then
                quota=$(cat "$quota_file")
                quota=$((quota / (1024 * 1024 * 1024))) # Convert bytes to GB
            else
                quota="0"
            fi
            if [[ $quota -eq 0 ]]; then
                quota_display="unl"
            else
                quota_display="${quota} gb"
            fi
            users["$user"]="$i"
            printf "%-4s %-15s %-15s %-10s\n" "$i." "$user" "$exp" "$quota_display"
            ((i++))
        fi
    done < <(grep -E "^### " "$CONFIG_FILE")

    echo -e "${orange}─────────────────────────────────────────${neutral}"
    read -rp "Input number or Username: " input

    # Determine user from input
    if [[ $input =~ ^[0-9]+$ ]]; then
        user=$(grep -E "^### " "$CONFIG_FILE" | awk 'NR=='$input'{print $2}')
        exp=$(grep -E "^### " "$CONFIG_FILE" | awk 'NR=='$input'{print $3}')
    else
        user=$input
        exp=$(grep -wE "^### $user" "$CONFIG_FILE" | awk '{print $3}')
    fi

    if [[ -z $user || -z $exp ]]; then
        echo -e "${red}User not found!${neutral}"
        echo -e "${orange}─────────────────────────────────────────${neutral}"
        return
    fi

    # Input new expiration
    read -rp "Expired (days): " masaaktif
    if [[ -z "$masaaktif" || "$masaaktif" -eq 0 ]]; then
        echo -e "${red}Error: Expired days cannot be 0!${neutral}"
        return
    fi

    # Get existing quota from database
    quota_file="/etc/vmess/$user"
    if [[ -f $quota_file ]]; then
        quota=$(cat "$quota_file")
        quota_display=$((quota / (1024 * 1024 * 1024))) # Convert bytes to GB
    else
        quota="0"
    fi

    # Multiply the quota by a factor (e.g., 2)
    if [[ $quota -ne 0 ]]; then
        quota=$((quota * 2)) # Multiply by 2
        quota_display=$((quota / (1024 * 1024 * 1024))) # Convert bytes to GB
    fi

    if [[ $quota -eq 0 ]]; then
        quota_display="unl"
    else
        quota_display="${quota_display} gb"
    fi

    # Save the new quota
    echo "$quota" > /etc/vmess/$user

    # Calculate new expiration date
    exp4=$(date -d "$exp +$masaaktif days" +"%Y-%m-%d")

    # Update configuration
    sed -i "/### $user/c\### $user $exp4" "$CONFIG_FILE"
    sed -i "/### $user/c\### $user $exp4" /etc/vmess/.vmess.db

    # Restart service
    systemctl restart xray > /dev/null 2>&1

    # Success message
    clear
    echo -e "${orange}─────────────────────────────────────────${neutral}"
    echo -e "${green} Successfully Renewed VMess Account${neutral}"
    echo ""
    echo -e "${yellow} Client Name   : $user${neutral}"
    echo -e "${yellow} Expired On    : $exp4${neutral}"
    echo -e "${yellow} User Quota    : $quota_display${neutral}"
    echo -e "${orange}─────────────────────────────────────────${neutral}"
}


vmess_members() {
    clear
    echo -e "${orange}─────────────────────────────────────────${neutral}"
    echo -e "      ${green}.::::. VMESS MEMBERS .::::.${neutral}"
    echo -e "${orange}─────────────────────────────────────────${neutral}"

    # Cek apakah file konfigurasi Xray ada
    if [ ! -e "/etc/xray/config.json" ]; then
        echo -e "   ${red}No VMESS accounts registered.${neutral}"
        echo -e "${orange}─────────────────────────────────────────${neutral}"
        echo -e "   Press enter to return to the menu"
        read
        display_vmess_menu
    fi

    echo -e " List of VMESS Accounts:"
    echo "┌──┬────────────┬──────┬──────┬───┬──────┐"
    echo "│no│ username   │ exp  │quota │ip │usage │"
    echo "├──┼────────────┼──────┼──────┼───┼──────┤"

    # Array asosiatif untuk menyimpan nama pengguna unik
    declare -A users

    # Membaca informasi pengguna dari file konfigurasi Xray
    while read -r line; do
        user=$(echo "$line" | awk '{print $2}')
        exp=$(echo "$line" | awk '{print $3}')

        # Tambahkan hanya jika user belum ada di array
        users["$user"]="$exp"
    done < <(grep -E "^### " "/etc/xray/config.json")

    # Variabel untuk nomor
    no=1

    # Loop melalui array untuk menampilkan data
    for user in "${!users[@]}"; do
        exp="${users[$user]}"

        # Hitung sisa hari masa berlaku
        current_timestamp=$(date +%s)
        exp_timestamp=$(date -d "$exp" +%s)
        days_left=$(( (exp_timestamp - current_timestamp) / 86400 ))
        if [ $days_left -lt 0 ]; then
            days_left=0
        fi
        exp="${days_left}d"

        # Path file terkait pengguna
        quota_file="/etc/vmess/${user}"
        ip_limit_file="/etc/biji/limit/vmess/ip/${user}"
        usage_file="/etc/limit/vmess/${user}"

        # Kuota
        if [ -f "$quota_file" ]; then
            quota=$(cat "$quota_file")
            if [[ "$quota" != "0" && "$quota" != "" ]]; then
                quota=$(con "$quota")
            else
                quota="Unltd"
            fi
        else
            quota="Unltd"
        fi

        # IP Limit
        if [ -f "$ip_limit_file" ]; then
            ip_limit=$(cat "$ip_limit_file")
            if [[ "$ip_limit" == "0" || "$ip_limit" == "" ]]; then
                ip_limit="Unltd"
            fi
        else
            ip_limit="Unltd"
        fi

        # Usage
        if [ -f "$usage_file" ]; then
            usage=$(cat "$usage_file")
            if [[ "$usage" != "0" && "$usage" != "" ]]; then
                usage=$(con "$usage")
            else
                usage="0GB"
            fi
        else
            usage="0GB"
        fi

        # Cetak tabel
        printf "│%-2s│%-12s│%-6s│%-6s│%-3s│%-6s│\n" "$no" "$user" "$exp" "$quota" "$ip_limit" "$usage"
        no=$((no + 1))
    done

    echo "└──┴────────────┴──────┴──────┴───┴──────┘"
    echo -e "   Press enter to return to menu"
    read
    display_vmess_menu
}


# Function to display VMESS account details
function vmess_details() {
    clear
    echo -e "${orange}┌──────────────────────────────────────┐${neutral}"
    echo -e "${orange}│     ${green} X-RAY VMESS ACCOUNT DETAILS${neutral}     ${orange}│${neutral}"
    echo -e "${orange}└──────────────────────────────────────┘${neutral}"
    echo -e "${orange}┌──────────────────────────────────────┐${neutral}"

    # Count the number of clients
    NUMBER_OF_CLIENTS=$(grep -E "^### " "/etc/xray/config.json" | sort -u | wc -l)
    if [[ ${NUMBER_OF_CLIENTS} == '0' ]]; then
        echo -e "${orange}│${neutral}         No registered clients!       ${orange}│${neutral}"
        echo -e "${orange}└──────────────────────────────────────┘${neutral}"
        exit 0
    fi

    echo -e "${orange}│ ${green}NO  USERNAME        EXPIRY DATE"
    echo -e "${orange}│ ${neutral}----------------------------------"

    # Display the clients
    grep -E "^### " "/etc/xray/config.json" | cut -d ' ' -f 2-3 | sort -u | awk '{printf "%-3s %-15s %s\n", NR")", $1, $2}' | while read -r line; do
        echo -e "${orange}│ ${neutral}$line"
    done

    echo -e "${orange}└──────────────────────────────────────┘${neutral}"
    print_rainbow "─────────────────────────────────────────"

    # Reset variables
    CLIENT_NUMBER=0
    username=""

    # Prompt user to select a client
    until [[ ${CLIENT_NUMBER} -ge 1 && ${CLIENT_NUMBER} -le ${NUMBER_OF_CLIENTS} ]]; do
        if [[ ${NUMBER_OF_CLIENTS} == '1' ]]; then
            read -rp "Select client number [1]: " CLIENT_NUMBER
        else
            read -rp "Select client number [1-${NUMBER_OF_CLIENTS}]: " CLIENT_NUMBER
        fi

        # Handle non-numeric input
        if ! [[ ${CLIENT_NUMBER} =~ ^[0-9]+$ ]]; then
            echo "Error: Please enter a valid number."
            CLIENT_NUMBER=0
        fi
    done

    username=$(grep -E "^### " "/etc/xray/config.json" | cut -d ' ' -f 2 | sort -u | sed -n "${CLIENT_NUMBER}"p)
    clear

    # Check for log file
    log_file="/etc/xray/log-create-${username}.log"
    if [[ -f "${log_file}" ]]; then
        cat "${log_file}"
    else
        echo "  Log file not found for user: ${username}."
    fi
    
    print_rainbow "───────────────────────────"
    read -n 1 -s -r -p "Press any key to return to the menu"
    display_vmess_menu
}

change_vmess_limit() {
    clear
    echo -e "${orange}─────────────────────────────────────────${neutral}"
    echo -e "    ${green}.::::. CHANGE VMESS LIMIT .::::.${neutral}"
    echo -e "${orange}─────────────────────────────────────────${neutral}"

    if [ ! -e "/etc/xray/config.json" ]; then
        echo -e "   ${red}No VMESS accounts registered.${neutral}"
        echo -e "${orange}─────────────────────────────────────────${neutral}"
        echo -e "   Press enter to return to the menu"
        read
        display_vmess_menu
    fi

    echo -e "   List of VMESS Accounts:"
    echo -e "${orange}─────────────────────────────────────────${neutral}"
    account_count=$(grep -cE "^### " "/etc/xray/config.json")
    if [ "$account_count" -eq 0 ]; then
        echo -e "   ${red}No active VMESS accounts.${neutral}"
        echo -e "${orange}─────────────────────────────────────────${neutral}"
        echo -e "   Press enter to return to the menu"
        read
        display_vmess_menu
    fi

    echo "┌────┬────────────────────┬─────────────┐"
    echo "│ no │ username           │     exp     │"
    echo "├────┼────────────────────┼─────────────┤"

    # Declare an array to store usernames
    declare -a usernames
    idx=0

    # Read the accounts from config file and populate the array
    while IFS= read -r line; do
        username=$(echo "$line" | awk '{print $2}')
        expiration=$(echo "$line" | awk '{print $3}')
        
        # Convert expiration date to timestamp
        exp_timestamp=$(date -d "$expiration" +%s)
        current_timestamp=$(date +%s)
        days_left=$(( (exp_timestamp - current_timestamp) / 86400 ))
        
        if [ "$days_left" -lt 0 ]; then
            days_left=0
        fi

        # Store username in the array if not already present
        if [[ ! " ${usernames[*]} " =~ " ${username} " ]]; then
            usernames[idx]="$username"
            printf "│ %-2d │ %-18s │ %-11s │\n" "$((idx + 1))" "$username" "$days_left days"
            idx=$((idx + 1))
        fi
    done < <(grep -E "^### " "/etc/xray/config.json")

    echo "└────┴────────────────────┴─────────────┘"

    echo -e "${orange}─────────────────────────────────────────${neutral}"
    read -p "   Select the account number : " account_number

    # Check if input is a number
    if ! [[ "$account_number" =~ ^[0-9]+$ ]]; then
        echo -e "   ${red}Error: Input must be a number.${neutral}"
        echo -e "   Press enter to return to the menu"
        read
        display_vmess_menu
    fi

    # Check if account number is valid
    if [ "$account_number" -lt 1 ] || [ "$account_number" -gt "$idx" ]; then
        echo -e "   ${red}Error: Invalid account number.${neutral}"
        echo -e "   Press enter to return to the menu"
        read
        display_vmess_menu
    fi

    username=${usernames[$((account_number - 1))]}

    if [ -z "$username" ]; then
        echo -e "   ${red}Invalid account number.${neutral}"
        echo -e "   Press enter to return to menu"
        read
        display_vmess_menu
    fi

    echo -e "Changing limit for account: ${green}$username${neutral}"
    read -p "Enter new quota limit (in GB, 0 for unlimited): " new_quota
    read -p "Enter new IP limit (0 for unlimited): " new_ip_limit

    # Validate input
    if ! [[ "$new_quota" =~ ^[0-9]+$ ]]; then
        echo -e "${red}Error: Quota limit must be a number.${neutral}"
        echo -e "   Press enter to return to the menu"
        read
        display_vmess_menu
    fi

    if ! [[ "$new_ip_limit" =~ ^[0-9]+$ ]]; then
        echo -e "${red}Error: IP limit must be a number.${neutral}"
        echo -e "   Press enter to return to the menu"
        read
        display_vmess_menu
    fi

    # Convert quota to bytes
    new_quota_bytes=$((new_quota * 1024 * 1024 * 1024))

    # Update quota and IP limit files
    echo "${new_quota_bytes}" >"/etc/vmess/${username}"
    echo "${new_ip_limit}" >"/etc/biji/limit/vmess/ip/${username}"

    # Check if update was successful
    if [ $? -eq 0 ]; then
        echo -e "${green}Limit for account $username successfully changed.${neutral}"
        echo -e "New quota: ${new_quota} GB"
        echo -e "New IP limit: ${new_ip_limit}"
    else
        echo -e "${red}Failed to change limit for account $username.${neutral}"
        echo -e "Please ensure you have sufficient permissions and try again."
    fi

    echo -e "${orange}─────────────────────────────────────────${neutral}"
    echo -e "   Press enter to return to menu"
    read
    display_vmess_menu
}

function trial_vmess() {
ISP=$(cat /etc/xray/isp)
CITY=$(cat /etc/xray/city)
PUB=$(cat /etc/slowdns/server.pub)
NS=$(cat /etc/xray/dns)
domain=$(cat /etc/xray/domain)

clear
print_rainbo "┌─────────────────────────────────────────┐"
print_rainbo "│   .::.  Script by HunterTunnel  .::.    │"
print_rainbo "│     Input xray/vmess account deps       │"
print_rainbo "│            Enter User Data              │"
print_rainbo "└─────────────────────────────────────────┘"

echo -e ""
echo -e "${yellow}Example: 1m for 1 minutes, 1d for 1 days ${NC}"
echo -e " "
read -p "Input Time Duration: " duration

# Validasi durasi
unit=${duration: -1}  
value=${duration%?}   

if [[ ! $value =~ ^[0-9]+$ ]]; then
    echo "Invalid input! Format harus angka diikuti huruf 'm' atau 'd'."
    exit 1
fi

# Menentukan durasi
if [[ $unit == "m" || $unit == "M" ]]; then
    pup=$value
    exp="$value minutes"  # Durasi deskriptif
    exp_date=$(date -d "$pup minutes" +"%Y-%m-%d %H:%M:%S")
elif [[ $unit == "d" || $unit == "D" ]]; then
    pup=$((value * 1440))
    exp="$value days"  # Durasi deskriptif
    exp_date=$(date -d "$value days" +"%Y-%m-%d")
else
    echo "Invalid format! Gunakan 'm' untuk menit atau 'd' untuk hari."
    exit 1
fi

uuid=$(cat /proc/sys/kernel/random/uuid)
user="TrialHT-$(tr -dc A-Za-z0-9 </dev/urandom | head -c4)"
domain=$(cat /etc/xray/domain)

sed -i '/#vmess$/a\### '"$user $exp_date"'\
},{"id": "'""$uuid""'","alterId": '"0"',"email": "'""$user""'"' /etc/xray/config.json
sed -i '/#vmessgrpc$/a\### '"$user $exp_date"'\
},{"id": "'""$uuid""'","alterId": '"0"',"email": "'""$user""'"' /etc/xray/config.json

echo "sed -i '/\"id\": \".*\",.*\"email\": \"${user}\"/d' /etc/xray/config.json && \
rm -f /etc/xray/log-create-${user}.log /etc/xray/$user-tls.json /etc/xray/$user-non.json /etc/xray/$user-grpc.json /etc/xray/$user-hu.json /etc/vmess/${user} /etc/biji/limit/vmess/ip/${user} && \
sed -i '/$user/d' /etc/xray/config.json && \
sed -i '/### $user/d' /etc/vmess/.vmess.db && \
systemctl restart xray" | at now + $pup minutes

cat >/etc/xray/$user-tls.json <<EOF
      {
      "v": "2",
      "ps": "$user",
      "add": "${domain}",
      "port": "443",
      "id": "${uuid}",
      "aid": "0",
      "net": "ws",
      "path": "/vmess",
      "type": "none",
      "host": "${domain}",
      "tls": "tls"
}
EOF
cat >/etc/xray/$user-non.json <<EOF
      {
      "v": "2",
      "ps": "$user",
      "add": "${domain}",
      "port": "80",
      "id": "${uuid}",
      "aid": "0",
      "net": "ws",
      "path": "/vmess",
      "type": "none",
      "host": "${domain}",
      "tls": "none"
}
EOF
cat >/etc/xray/$user-grpc.json <<EOF
      {
      "v": "2",
      "ps": "$user",
      "add": "${domain}",
      "port": "443",
      "id": "${uuid}",
      "aid": "0",
      "net": "grpc",
      "path": "vmess-grpc",
      "type": "none",
      "host": "${domain}",
      "tls": "tls"
}
EOF

cat >/etc/xray/$user-hu.json <<EOF
      {
      "v": "2",
      "ps": "$user",
      "add": "${domain}",
      "port": "443",
      "id": "${uuid}",
      "aid": "0",
      "net": "httpupgrade",
      "path": "/vmess-hu",
      "type": "none",
      "host": "${domain}",
      "tls": "tls"
}
EOF

vmesslink1="vmess://$(base64 -w 0 /etc/xray/$user-tls.json)"
vmesslink2="vmess://$(base64 -w 0 /etc/xray/$user-non.json)"
vmesslink3="vmess://$(base64 -w 0 /etc/xray/$user-grpc.json)"
vmesslink4="vmess://$(base64 -w 0 /etc/xray/$user-hu.json)"

if [ ! -e /etc/vmess ]; then
  mkdir -p /etc/vmess
fi

if [[ $iplimit -gt 0 ]]; then
mkdir -p /etc/biji/limit/vmess/ip
echo -e "$iplimit" > /etc/biji/limit/vmess/ip/$user
else
echo > /dev/null
fi

if [ -z ${Quota} ]; then
  Quota="0"
fi

c=$(echo "${Quota}" | sed 's/[^0-9]*//g')
d=$((${c} * 1024 * 1024 * 1024))

if [[ ${c} != "0" ]]; then
  echo "${d}" >/etc/vmess/${user}
fi
DATADB=$(cat /etc/vmess/.vmess.db | grep "^###" | grep -w "${user}" | awk '{print $2}')
if [[ "${DATADB}" != '' ]]; then
  sed -i "/\b${vmess}\b/d" /etc/vmess/.vmess.db
fi
echo "### ${user} ${Quota} ${iplimit} ${timer}" >>/etc/vmess/.vmess.db

# Save original log
{
print_rainbo "───────────────────────────"
print_rainbo "    Xray/Vmess Account    "
print_rainbo "───────────────────────────"
echo -e "Remarks      : ${user}"
echo -e "User Ip      : ${iplimit} IP"
echo -e "User Quota   : ${Quota} GB"
echo -e "Host Server  : ${domain}"
echo -e "Host XrayDNS : ${NS}"
echo -e "Location     : $CITY"
echo -e "Port TLS     : 443"
echo -e "Port non TLS : 80, 8080"
echo -e "Port DNS     : 443, 53"
echo -e "Port GRPC    : 443"
echo -e "AlterId      : 0"
echo -e "Security     : auto"
echo -e "Network      : WS or gRPC"
echo -e "Path         : /vmess "
echo -e "ServiceName  : vmess-grpc"
echo -e "User ID      : ${uuid}"
echo -e "Public Key   : ${PUB}"
print_rainbo "───────────────────────────"
echo -e "TLS Link    : ${vmesslink1}"
print_rainbo "───────────────────────────"
echo -e "NTLS Link   : ${vmesslink2}"
print_rainbo "───────────────────────────"
echo -e "GRPC Link   : ${vmesslink3}"
print_rainbo "───────────────────────────"
echo -e "HU Link     : ${vmesslink4}"
print_rainbo "───────────────────────────"
echo -e "Expires date : $exp"
print_rainbo "───────────────────────────"
echo -e ""    
} >> /etc/xray/log-create-${user}.log

systemctl restart xray

# Output informasi akun
clear -x
print_rainbo "───────────────────────────"
print_rainbo "       Xray/Vmess Account     "
print_rainbo "───────────────────────────"
echo -e "Description : ${user}"
echo -e "Host Server : ${domain}"
echo -e "Host XrayDNS: ${NS}"
echo -e "Location    : $CITY"
echo -e "TLS Port    : 443"
echo -e "Non-TLS Port: 80, 8080"
echo -e "DNS Port    : 443, 53"
echo -e "GRPC Port   : 443"
echo -e "AlterId     : 0"
echo -e "Security    : auto"
echo -e "Network     : WS or gRPC"
echo -e "Path        : /vmess"
echo -e "ServiceName : vmess-grpc"
echo -e "User ID     : ${uuid}"
echo -e "Public Key  : ${PUB}"
print_rainbo "───────────────────────────"
echo -e "TLS Link   : ${vmesslink1}"
print_rainbo "───────────────────────────"
echo -e "NTLS Link  : ${vmesslink2}"
print_rainbo "───────────────────────────"
echo -e "GRPC Link  : ${vmesslink3}"
print_rainbo "───────────────────────────"
echo -e "HU Link    : ${vmesslink4}"
print_rainbo "───────────────────────────"
echo -e "Duration      : ${exp}"
print_rainbo "───────────────────────────"
echo -e ""
read -n 1 -s -r -p "Enter Back To Menu"
display_vmess_menu
}

add_vmess() {
ISP=$(cat /etc/xray/isp)
CITY=$(cat /etc/xray/city)
PUB=$(cat /etc/slowdns/server.pub)
NS=$(cat /etc/xray/dns)
domain=$(cat /etc/xray/domain)
clear
# User data input
print_rainbo "┌─────────────────────────────────────────┐"
print_rainbo "│            ENTER USER DATA              │"
print_rainbo "└─────────────────────────────────────────┘"
while true; do
    read -p "   Name: " user
    if [[ ${#user} -lt 3 || ! "$user" =~ ^[a-zA-Z0-9_-]+$ ]]; then
        printf "\033[1A\033[0J"
        echo -e "${red}   Username cannot be empty${reset}"
        continue
    fi
    if grep -q "^### $user " /etc/xray/config.json; then
        random_number=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 5)
        user="${random_number}${user}"
        echo -e "${yellow}   Username already exists. New username used: $user${reset}"
        break
    else
        break
    fi
done
echo ""
printf "\033[10A\033[0J"
print_rainbo "┌─────────────────────────────────────────┐"
print_rainbo "│  .::.  Script by HunterTunnel  .::.     │"
print_rainbo "│     Input xray/vmess account deps       │"
print_rainbo "│      Set Quota/IP Limit for Account     │"
print_rainbo "│            0 For Unlimited              │"
print_rainbo "└─────────────────────────────────────────┘"
echo "   Username : $user"
    uuid=$(cat /proc/sys/kernel/random/uuid)

    until [[ $Quota =~ ^[0-9]+$ ]]; do
        read -p "   Limit User (GB): " Quota
    done

    until [[ $iplimit =~ ^[0-9]+$ ]]; do
        mkdir -p /etc/biji/limit/vmess/ip
        read -p "   Limit User (IP): " iplimit
    done
    
    until [[ $masaaktif =~ ^[0-9]+$ ]]; do
        read -p "   Expired (days): " masaaktif
    done

exp=$(date -d "$masaaktif days" +"%Y-%m-%d")
sed -i '/#vmess$/a\### '"$user $exp"'\
},{"id": "'""$uuid""'","alterId": '"0"',"email": "'""$user""'"' /etc/xray/config.json
exp=$(date -d "$masaaktif days" +"%Y-%m-%d")
sed -i '/#vmessgrpc$/a\### '"$user $exp"'\
},{"id": "'""$uuid""'","alterId": '"0"',"email": "'""$user""'"' /etc/xray/config.json

cat >/etc/xray/$user-tls.json <<EOF
      {
      "v": "2",
      "ps": "$user",
      "add": "${domain}",
      "port": "443",
      "id": "${uuid}",
      "aid": "0",
      "net": "ws",
      "path": "/vmess",
      "type": "none",
      "host": "${domain}",
      "tls": "tls"
}
EOF
cat >/etc/xray/$user-non.json <<EOF
      {
      "v": "2",
      "ps": "$user",
      "add": "${domain}",
      "port": "80",
      "id": "${uuid}",
      "aid": "0",
      "net": "ws",
      "path": "/vmess",
      "type": "none",
      "host": "${domain}",
      "tls": "none"
}
EOF
cat >/etc/xray/$user-grpc.json <<EOF
      {
      "v": "2",
      "ps": "$user",
      "add": "${domain}",
      "port": "443",
      "id": "${uuid}",
      "aid": "0",
      "net": "grpc",
      "path": "vmess-grpc",
      "type": "none",
      "host": "${domain}",
      "tls": "tls"
}
EOF

cat >/etc/xray/$user-hu.json <<EOF
      {
      "v": "2",
      "ps": "$user",
      "add": "${domain}",
      "port": "443",
      "id": "${uuid}",
      "aid": "0",
      "net": "httpupgrade",
      "path": "/vmess-hu",
      "type": "none",
      "host": "${domain}",
      "tls": "tls"
}
EOF

vmesslink1="vmess://$(base64 -w 0 /etc/xray/$user-tls.json)"
vmesslink2="vmess://$(base64 -w 0 /etc/xray/$user-non.json)"
vmesslink3="vmess://$(base64 -w 0 /etc/xray/$user-grpc.json)"
vmesslink4="vmess://$(base64 -w 0 /etc/xray/$user-hu.json)"

if [ ! -e /etc/vmess ]; then
  mkdir -p /etc/vmess
fi
if [ -z ${iplimit} ]; then
  iplimit="0"
fi
if [ -z ${Quota} ]; then
  Quota="0"
fi
c=$(echo "${Quota}" | sed 's/[^0-9]*//g')
d=$((${c} * 1024 * 1024 * 1024))
if [[ ${c} != "0" ]]; then
  echo "${d}" >/etc/vmess/${user}
  echo "${iplimit}" >/etc/biji/limit/vmess/ip/$user
fi
DATADB=$(cat /etc/vmess/.vmess.db | grep "^###" | grep -w "${user}" | awk '{print $2}')
if [[ "${DATADB}" != '' ]]; then
  sed -i "/\b${user}\b/d" /etc/vmess/.vmess.db
fi
echo "### ${user} ${exp} ${uuid} ${Quota} ${iplimit}" >>/etc/vmess/.vmess.db

# Save original log
{
print_rainbo "───────────────────────────"
print_rainbo "    Xray/Vmess Account    "
print_rainbo "───────────────────────────"
echo -e "Remarks      : ${user}"
echo -e "User Ip      : ${iplimit} IP"
echo -e "User Quota   : ${Quota} GB"
echo -e "Host Server  : ${domain}"
echo -e "Host XrayDNS : ${NS}"
echo -e "Location     : $CITY"
echo -e "Port TLS     : 443"
echo -e "Port non TLS : 80, 8080"
echo -e "Port DNS     : 443, 53"
echo -e "Port GRPC    : 443"
echo -e "AlterId      : 0"
echo -e "Security     : auto"
echo -e "Network      : WS or gRPC"
echo -e "Path         : /vmess "
echo -e "ServiceName  : vmess-grpc"
echo -e "User ID      : ${uuid}"
echo -e "Public Key   : ${PUB}"
print_rainbo "───────────────────────────"
echo -e "TLS Link    : ${vmesslink1}"
print_rainbo "───────────────────────────"
echo -e "NTLS Link   : ${vmesslink2}"
print_rainbo "───────────────────────────"
echo -e "GRPC Link   : ${vmesslink3}"
print_rainbo "───────────────────────────"
echo -e "HU Link     : ${vmesslink4}"
print_rainbo "───────────────────────────"
echo -e "Expires date : $exp"
print_rainbo "───────────────────────────"
echo -e ""    
} >> /etc/xray/log-create-${user}.log
systemctl restart xray

# Display account information
clear -x
print_rainbo "───────────────────────────"
print_rainbo "    Xray/Vmess Account    "
print_rainbo "───────────────────────────"
echo -e "Remarks      : ${user}"
echo -e "User Ip      : ${iplimit} IP"
echo -e "User Quota   : ${Quota} GB"
echo -e "Host Server  : ${domain}"
echo -e "Host XrayDNS : ${NS}"
echo -e "Location     : $CITY"
echo -e "Port TLS     : 443"
echo -e "Port non TLS : 80, 8080"
echo -e "Port DNS     : 443, 53"
echo -e "Port GRPC    : 443"
echo -e "AlterId      : 0"
echo -e "Security     : auto"
echo -e "Network      : WS or gRPC"
echo -e "Path         : /vmess "
echo -e "ServiceName  : vmess-grpc"
echo -e "User ID      : ${uuid}"
echo -e "Public Key   : ${PUB}"
print_rainbo "───────────────────────────"
echo -e "TLS Link    : ${vmesslink1}"
print_rainbo "───────────────────────────"
echo -e "NTLS Link   : ${vmesslink2}"
print_rainbo "───────────────────────────"
echo -e "GRPC Link   : ${vmesslink3}"
print_rainbo "───────────────────────────"
echo -e "HU Link     : ${vmesslink4}"
print_rainbo "───────────────────────────"
echo -e "Expires date : $exp"
print_rainbo "───────────────────────────"
echo -e ""
}

display_vmess_menu() {
    clear
    echo -e "${orange}─────────────────────────────────────────${neutral}"
    echo -e "       ${green}.::::. VMESS MANAGER .::::.${neutral}"
    echo -e "${orange}─────────────────────────────────────────${neutral}"
    echo -e "    ${green}1.${neutral} Create Vmess Account"
    echo -e "    ${green}2.${neutral} Delete Vmess Account"
    echo -e "    ${green}3.${neutral} Renew Vmess Account"
    echo -e "    ${green}4.${neutral} Check Vmess Login Account"
    echo -e "    ${green}5.${neutral} List Vmess Members"
    echo -e "    ${green}6.${neutral} Change Vmess Account Limit"
    echo -e "    ${green}7.${neutral} View Vmess Account Details"
    echo -e "    ${green}8.${neutral} Create Trial Vmess Account"
    echo -e "    ${green}x.${neutral} Exit Vmess Manager"
    echo -e "${orange}─────────────────────────────────────────${neutral}"
    print_rainbow "─────────────────────────────────────────"
    read -p " Enter your choice or 'x' to quit: " vmess_choice

    case $vmess_choice in
    1) add_vmess ;;
    2) dellvmess ;;
    3) renewvmess ;;
    4) checkvmess ;;
    5) vmess_members ;;
    6) change_vmess_limit ;;
    7) vmess_details ;;
    8) trial_vmess ;;
    x | X)
        echo -e ""
        echo -e "   ${green}Thank you for using our service.${neutral}"
        exit 0
        ;;
    *)
        echo -e "   ${red}Invalid choice. Please try again.${neutral}"
        sleep 2
        display_vmess_menu
        ;;
    esac
}

# Call function to display menu
display_vmess_menu
