#!/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"

# 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
}

checktrojan() {
echo ""
    echo -ne "\e[33mChecking Trojan Account\e[0m"
    for i in {1..2}; do
        for j in ⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏; do
            echo -ne "\r\e[33mChecking trojan Account $j\e[0m"
            sleep 0.1
        done
    done
    echo -ne "\r\e[33mTrojan Account Check Successful!    \e[0m\n"
    sleep 1
    clear
    
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
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 trojan
    dir="/etc/biji/limit/trojan/ip"
    dir1="/etc/limit/trojan"
    [[ ! -d "$dir" ]] && mkdir -p "$dir"
    [[ ! -d "$dir1" ]] && mkdir -p "$dir1"

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

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

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

    # Mendapatkan daftar akun trojan 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/trojan 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/iptrojan.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/iptrojan.txt
            else
                echo "$ip" >> /tmp/other.txt
            fi
            jum2=$(cat /tmp/iptrojan.txt)
            sed -i "/$jum2/d" /tmp/other.txt > /dev/null 2>&1
        done
        jum=$(cat /tmp/iptrojan.txt)
        if [[ -z "$jum" ]]; then
            echo > /dev/null
        else
            iplimit=$(cat /etc/biji/limit/trojan/ip/${akun})
            jum2=$(cat /tmp/iptrojan.txt | wc -l)
            byte=$(cat /etc/trojan/${akun})
            lim=$(con ${byte})
            wey=$(cat /etc/limit/trojan/${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/iptrojan.txt
        fi
    done
    line_bawah
    # Membersihkan file sementara
    rm -f /tmp/other.txt
}

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
}

delltrojan() {
    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}.::::. DELETE TROJAN ACCOUNT .::::.${neutral}"
        echo -e "${orange}─────────────────────────────────────────${neutral}"
        echo -e "${red}No trojan accounts available to delete!${neutral}"
        echo -e "${orange}─────────────────────────────────────────${neutral}"
        exit 1
    fi

    # Display the list of accounts (unique entries only)
    echo -e "${orange}─────────────────────────────────────────${neutral}"
    echo -e "    ${green}.::::. DELETE TROJAN ACCOUNT .::::.${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 user
    echo -e "${orange}─────────────────────────────────────────${neutral}"
    read -rp "Enter a number or username: " input

    if [[ $input =~ ^[0-9]+$ ]]; then
        # Input is a number
        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 is a username
        user=$input
        exp=$(grep -wE "^#! $user" "$CONFIG_FILE" | awk '{print $3}')
    fi

    # Validate input
    if [[ -z $user || -z $exp ]]; then
        echo -e "${red}Account not found!${neutral}"
        echo -e "${orange}─────────────────────────────────────────${neutral}"
        exit 1
    fi

    # Remove all occurrences of the account from configuration
    sed -i "/^#! $user $exp/,/^},{/d" "$CONFIG_FILE"
    sed -i "/^### $user $exp/d" /etc/trojan/.trojan.db

    # Double-check for duplicate entries and remove them
    while grep -qE "^#! $user " "$CONFIG_FILE"; do
        sed -i "/^#! $user /,/^},{/d" "$CONFIG_FILE"
    done

    # Remove additional files related to the account
    rm -rf /etc/trojan/$user
    rm -rf /etc/biji/limit/trojan/ip/$user
    rm -rf /var/www/html/trojan-$user.txt
    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"    

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

    # Confirm deletion
    clear
    print_rainbo "┌─────────────────────────────────────────┐"
    print_rainbo "│    TROJAN ACCOUNT DELETED SUCCESSFULLY   │"
    print_rainbo "└─────────────────────────────────────────┘"
    echo -e "Username     : ${green}$user${reset}"
    echo -e "Account has been permanently deleted"
    echo ""
    read -n 1 -s -r -p "Press any key to back"
    dumpt
}

renewtrojan() {
    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 TROJAN ACCOUNT .::::.${neutral}"
        echo -e "${orange}─────────────────────────────────────────${neutral}"
        echo -e "${red}No trojan 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 TROJAN 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/trojan/$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 and limits
    read -rp "Expired (days): " masaaktif
    if [[ -z "$masaaktif" || "$masaaktif" -eq 0 ]]; then
        echo -e "${red}Error: Expired days cannot be 0!${neutral}"
        return
    fi

    read -rp "Limit User (GB): " Quota

    # Convert quota to bytes and save
    if [[ -z $Quota ]]; then
        Quota="0"
    fi
    if [[ $Quota -eq 0 ]]; then
        quota_display="unl"
        d=0
    else
        quota_display="${Quota} GB"
        c=$(echo "$Quota" | sed 's/[^0-9]*//g')
        d=$((c * 1024 * 1024 * 1024))
    fi
    mkdir -p /etc/trojan
    echo "$d" > /etc/trojan/$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/trojan/.trojan.db

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

    # Success message
    clear
    echo -e "${orange}─────────────────────────────────────────${neutral}"
    echo -e "${green} Successfully Renewed Trojan 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}"
}

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

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

    echo -e " List of trojan 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/trojan/${user}"
        ip_limit_file="/etc/biji/limit/trojan/ip/${user}"
        usage_file="/etc/limit/trojan/${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_trojan_menu
}


# Function to display trojan account details
function trojan_details() {
    clear
    echo -e "${orange}┌──────────────────────────────────────┐${neutral}"
    echo -e "${orange}│    ${green} X-RAY TROJAN 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_trojan_menu
}

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

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

    echo -e "   List of trojan Accounts:"
    echo -e "${orange}─────────────────────────────────────────${neutral}"
    account_count=$(grep -cE "^#! " "/etc/xray/config.json")
    if [ "$account_count" -eq 0 ]; then
        echo -e "   ${red}No active trojan accounts.${neutral}"
        echo -e "${orange}─────────────────────────────────────────${neutral}"
        echo -e "   Press enter to return to the menu"
        read
        display_trojan_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_trojan_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_trojan_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_trojan_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_trojan_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_trojan_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/trojan/${username}"
    echo "${new_ip_limit}" >"/etc/biji/limit/trojan/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_trojan_menu
}

add_trojan() {
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)

# Animasi Loading
echo ""
echo -ne "${yellow}Preparing Premium Account${reset}"
for i in {1..2}; do
    for j in ⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏; do
        echo -ne "\r${yellow}Preparing Premium Account $j${reset}"
        sleep 0.1
    done
done
echo -ne "\r${yellow}Premium Account Ready to be created!${reset}\n"
sleep 1
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/trojan 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 [[ $masaaktif =~ ^[0-9]+$ ]]; do
        read -p "   Expired (days): " masaaktif
    done

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

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

exp=$(date -d "$masaaktif days" +"%Y-%m-%d")
sed -i '/#trojanws$/a\#! '"$user $exp"'\
},{"password": "'""$uuid""'","email": "'""$user""'"' /etc/xray/config.json
sed -i '/#trojangrpc$/a\#! '"$user $exp"'\
},{"password": "'""$uuid""'","email": "'""$user""'"' /etc/xray/config.json

trojanlink="trojan://${uuid}@${domain}:443?path=%2Ftrojan-ws&security=tls&host=${domain}&type=ws&sni=${domain}#${user}"
trojanlink1="trojan://${uuid}@${domain}:443?mode=gun&security=tls&type=grpc&serviceName=trojan-grpc&sni=${domain}#${user}"
trojanlink_hu="trojan://${uuid}@${domain}:443?path=%2Ftrojan-hu&security=tls&host=${domain}&type=httpupgrade&sni=${domain}#${user}"

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

EOF
cat >/etc/xray/$user-grpc.json <<EOF
      {
      "v": "2",
      "ps": "$user",
      "add": "${domain}",
      "port": "443",
      "id": "${uuid}",
      "aid": "0",
      "net": "grpc",
      "path": "trojan-grpc",
      "type": "none",
      "host": "${domain}",
      "tls": "tls"
}
EOF
cat >/var/www/html/trojan-$user.txt <<-END

---------------------
# Format trojan WS (CDN)
---------------------

- name: trojan-$user
  type: trojan
  server: ${domain}
  port: 443
  uuid: ${uuid}
  alterId: 0
  cipher: auto
  udp: true
  tls: true
  skip-cert-verify: true
  servername: ${domain}
  network: ws
  ws-opts:
    path: /trojan
    headers:
      Host: ${domain}

---------------------
# Format trojan gRPC (SNI)
---------------------

- name: trojan-$user
  server: ${domain}
  port: 443
  type: trojan
  uuid: ${uuid}
  alterId: 0
  cipher: auto
  network: grpc
  tls: true
  servername: ${domain}
  skip-cert-verify: true
  grpc-opts:
    grpc-service-name: trojan-grpc

---------------------
# Link trojan Account
---------------------
Link TLS : ${trojanlink}
---------------------
Link GRPC : ${trojanlink1}
---------------------

END

systemctl restart xray
if [ ! -e /etc/trojan ]; then
  mkdir -p /etc/trojan
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/trojan/${user}
  echo "${iplimit}" >/etc/biji/limit/trojan/ip/$user
fi
DATADB=$(cat /etc/trojan/.trojan.db | grep "^###" | grep -w "${user}" | awk '{print $2}')
if [[ "${DATADB}" != '' ]]; then
  sed -i "/\b${user}\b/d" /etc/trojan/.trojan.db
fi
echo "### ${user} ${exp} ${uuid} ${Quota} ${iplimit}" >>/etc/trojan/.trojan.db

# Display account information
clear -x
print_rainbo "───────────────────────────"
print_rainbo "    Xray/trojan 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 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         : /trojan "
echo -e "ServiceName  : trojan-grpc"
echo -e "User ID      : ${uuid}"
echo -e "Public Key   : ${PUB}"
print_rainbo "───────────────────────────"
echo -e "TLS Link    : ${trojanlink}"
print_rainbo "───────────────────────────"
echo -e "GRPC Link   : ${trojanlink1}"
print_rainbo "───────────────────────────"
echo -e "HU Link     : ${trojanlink_hu}"
print_rainbo "───────────────────────────"
echo -e "OpenClash Format : https://${domain}:81/trojan-$user.txt"
print_rainbo "───────────────────────────"
echo -e "Expires date : $exp"
print_rainbo "───────────────────────────"
echo -e ""



# Save original log
{
print_rainbo "───────────────────────────"
print_rainbo "    Xray/trojan 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 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         : /trojan "
echo -e "ServiceName  : trojan-grpc"
echo -e "User ID      : ${uuid}"
echo -e "Public Key   : ${PUB}"
print_rainbo "───────────────────────────"
echo -e "TLS Link    : ${trojanlink}"
print_rainbo "───────────────────────────"
echo -e "GRPC Link   : ${trojanlink1}"
print_rainbo "───────────────────────────"
echo -e "HU Link     : ${trojanlink_hu}"
print_rainbo "───────────────────────────"
echo -e "OpenClash Format : https://${domain}:81/trojan-$user.txt"
print_rainbo "───────────────────────────"
echo -e "Expires date : $exp"
print_rainbo "───────────────────────────"
echo -e ""    
} >> /etc/xray/log-create-${user}.log
}

trial_trojan() {
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)

# Animasi Loading
echo ""
echo -ne "${yellow}Preparing Premium Account${reset}"
for i in {1..2}; do
    for j in ⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏; do
        echo -ne "\r${yellow}Preparing Premium Account $j${reset}"
        sleep 0.1
    done
done
echo -ne "\r${yellow}Premium Account Ready to be created!${reset}\n"
sleep 1
clear

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

echo -e ""
echo -e "${yellow}Example: 1m for minutes, 1d for 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="TrialMT-$(tr -dc A-Za-z0-9 </dev/urandom | head -c4)"
domain=$(cat /etc/xray/domain)

exp=$(date -d "$masaaktif days" +"%Y-%m-%d")
tgl=$(date -d "$masaaktif days" +"%d")
bln=$(date -d "$masaaktif days" +"%b")
thn=$(date -d "$masaaktif days" +"%Y")
expe="$tgl $bln, $thn"
tgl2=$(date +"%d")
bln2=$(date +"%b")
thn2=$(date +"%Y")
tnggl="$tgl2 $bln2, $thn2"

sed -i '/#trojanws$/a\#! '"$user $exp"'\
},{"password": "'""$uuid""'","email": "'""$user""'"' /etc/xray/config.json
sed -i '/#trojangrpc$/a\#! '"$user $exp"'\
},{"password": "'""$uuid""'","email": "'""$user""'"' /etc/xray/config.json

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

systemctl restart xray
trojanlink1="trojan://${uuid}@${domain}:443?mode=gun&security=tls&type=grpc&serviceName=trojan-grpc&sni=bug.com#${user}"
trojanlink="trojan://${uuid}@bugkamu.com:443?path=%2Ftrojan-ws&security=tls&host=${domain}&type=ws&sni=${domain}#${user}"
trojanlink2="trojan://${uuid}@${domain}:80?path=%2Ftrojan-ws&security=none&host=${domain}&type=ws#${user}"

cat >/var/www/html/trojan-$user.txt <<-END
======================
     $nama 
======================
# Format Trojan GO/WS

- name: Trojan-$user-GO/WS
  server: ${domain}
  port: 443
  type: trojan
  password: ${uuid}
  network: ws
  sni: ${domain}
  skip-cert-verify: true
  udp: true
  ws-opts:
    path: /trojan-ws
    headers:
        Host: ${domain}

# Format Trojan gRPC

- name: Trojan-$user-gRPC
  type: trojan
  server: ${domain}
  port: 443
  password: ${uuid}
  udp: true
  sni: ${domain}
  skip-cert-verify: true
  network: grpc
  grpc-opts:
    grpc-service-name: trojan-grpc

======================
Link Akun Trojan 
======================
Link WS          : 
${trojanlink}
======================
Link GRPC        : 
${trojanlink1}
======================
Aktif Selama  : $exp
END


trojanlink="trojan://${uuid}@${domain}:443?path=%2Ftrojan-ws&security=tls&host=${domain}&type=ws&sni=${domain}#${user}"
trojanlink1="trojan://${uuid}@${domain}:443?mode=gun&security=tls&type=grpc&serviceName=trojan-grpc&sni=${domain}#${user}"
trojanlink_hu="trojan://${uuid}@${domain}:443?path=%2Ftrojan-hu&security=tls&host=${domain}&type=httpupgrade&sni=${domain}#${user}"
if [ ! -e /etc/trojan ]; then
  mkdir -p /etc/trojan
fi

if [[ $iplimit -gt 0 ]]; then
mkdir -p /etc/biji/limit/trojan/ip
echo -e "$iplimit" > /etc/biji/limit/trojan/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/trojan/${user}
fi

# Display account information

clear -x
print_rainbo "───────────────────────────"
print_rainbo "    Xray/Trojan 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 "Security     : auto"
echo -e "Network      : WS or gRPC"
echo -e "Path         : /trojan-ws "
echo -e "ServiceName  : trojan-grpc"
echo -e "Password     : ${uuid}"
echo -e "Public Key   : ${PUB}"
print_rainbo "───────────────────────────"
echo -e "WS Link    : ${trojanlink}" 
print_rainbo "───────────────────────────"
echo -e "TLS Link   : ${trojanlink2}" 
print_rainbo "───────────────────────────"
echo -e "GRPC Link   : ${trojanlink1}" 
print_rainbo "───────────────────────────"
echo -e "HU Link    : ${trojanlink_hu}"
print_rainbo "───────────────────────────"
echo -e "Expires On  : ${exp}"
print_rainbo "───────────────────────────"
echo -e ""
}

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

    case $trojan_choice in
    1) add_trojan ;;
    2) delltrojan ;;
    3) renewtrojan ;;
    4) checktrojan ;;
    5) trojan_members ;;
    6) change_trojan_limit ;;
    7) trojan_details ;;
    8) trial_trojan ;;
    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_trojan_menu
        ;;
    esac
}

# Call function to display menu
display_trojan_menu
