#!/bin/bash

vps_ip=$(wget -qO- ipv4.icanhazip.com)
data_acc=$(awk '/^### / {print $3; exit}' /etc/interflazz/access 2>/dev/null)

if [ -n "$data_acc" ]; then

  expiry_date=$(date -d "$data_acc" +%s)
  current_date=$(date +%s)
  remaining_days=$(( (expiry_date - current_date) / 86400 ))

if [ $expiry_date -gt $current_date ]; then
    
# colors
red="\e[91m"
green="\e[92m"
yellow="\e[93m"
blue="\e[94m"
purple="\e[95m"
cyan="\e[96m"
white="\e[97m"
reset="\e[0m"

# Function to print rainbow text
print_rainbow() {
    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"
}

# variables
domain=$(cat /etc/xray/domain 2>/dev/null || hostname -f)
clear
print_rainbow "┌─────────────────────────────────────────┐"
print_rainbow "│         UPDATE TROJAN ACCOUNT           │"
print_rainbow "└─────────────────────────────────────────┘"

account_count=$(grep -c -E "^### " "/etc/xray/trojan/.trojan.db")
if [[ ${account_count} == '0' ]]; then
    echo ""
    echo "  No customer names available"
    echo ""
    exit 0
fi

echo " ┌────┬────────────────────┬─────────────┐"
echo " │ NO │ USERNAME           │     EXP     │"
echo " ├────┼────────────────────┼─────────────┤"
grep -E "^### " "/etc/xray/trojan/.trojan.db" | awk '{
    cmd = "date -d \"" $3 "\" +%s"
    cmd | getline exp_timestamp
    close(cmd)
    current_timestamp = systime()
    days_left = int((exp_timestamp - current_timestamp) / 86400)
    if (days_left < 0) days_left = 0
    printf " │ %-2d │ %-18s │ %-11s │\n", NR, $2, days_left " days"
}'
echo " └────┴────────────────────┴─────────────┘"

while true; do
    read -rp "Choose account number [1-${account_count}]: " account_number
    if [[ ${account_number} =~ ^[0-9]+$ ]] && ((account_number >= 1 && account_number <= account_count)); then
        break
    else
        echo "Invalid input. Please enter a number between 1 and ${account_count}."
    fi
done

user=$(grep -E "^### " "/etc/xray/trojan/.trojan.db" | cut -d ' ' -f 2 | sed -n "${account_number}p")
exp=$(grep -E "^### " "/etc/xray/trojan/.trojan.db" | cut -d ' ' -f 3 | sed -n "${account_number}p")

clear
echo -e "${yellow}Updating premium account $user${reset}"
echo ""

# Read expiration date from database
old_exp=$(grep -E "^### $user " "/etc/xray/trojan/.trojan.db" | cut -d ' ' -f 3)

# Calculate remaining active days
remaining_days=$((($(date -d "$old_exp" +%s) - $(date +%s)) / 86400))

echo "Remaining active days: $remaining_days days"

while true; do
    read -p "Add active days: " active_period
    if [[ "$active_period" =~ ^[0-9]+$ ]]; then
        break
    else
        echo "Input must be a positive number."
    fi
done

while true; do
    read -p "Usage limit (GB, 0 for unlimited): " quota
    if [[ "$quota" =~ ^[0-9]+$ ]]; then
        break
    else
        echo "Input must be a positive number or 0."
    fi
done

while true; do
    read -p "Device limit (IP, 0 for unlimited): " ip_limit
    if [[ "$ip_limit" =~ ^[0-9]+$ ]]; then
        break
    else
        echo "Input must be a positive number or 0."
    fi
done

if [ ! -d /etc/xray/trojan ]; then
    mkdir -p /etc/xray/trojan
fi

if [[ $quota != "0" ]]; then
    quota_bytes=$((quota * 1024 * 1024 * 1024))
    echo "${quota_bytes}" >/etc/xray/trojan/${user}
    echo "${ip_limit}" >/etc/xray/trojan/${user}IP
else
    rm -f /etc/xray/trojan/${user} /etc/xray/trojan/${user}IP
fi

# Calculate new expiration date
new_exp=$(date -d "$old_exp +${active_period} days" +"%Y-%m-%d")
uuid=$(grep -E "^### $user " "/etc/xray/trojan/.trojan.db" | cut -d ' ' -f 4)
# Check if config file exists before making changes
if [ ! -f "/etc/xray/trojan/config.json" ]; then
    echo "Config file not found. Creating new file..."
    echo '{"inbounds": []}' >/etc/xray/trojan/config.json
fi

sed -i "/^### $user/c\### $user $new_exp" /etc/xray/trojan/config.json
sed -i "/^### $user/c\### $user $new_exp $uuid" /etc/xray/trojan/.trojan.db

# Restart service with error handling
if ! systemctl restart trojan@config >/dev/null 2>&1; then
    echo "Warning: Failed to restart trojan service. Please check system logs for more information."
    echo "However, the account has been successfully updated in the database."
fi

clear
print_rainbow "┌─────────────────────────────────────────┐"
print_rainbow "│   TROJAN ACCOUNT UPDATED SUCCESSFULLY   │"
print_rainbow "└─────────────────────────────────────────┘"
echo -e "Username     : ${green}$user${reset}"
echo -e "Quota limit  : ${yellow}$quota GB${reset}"
echo -e "IP limit     : ${yellow}$ip_limit devices${reset}"
echo -e "Expiration   : ${yellow}$new_exp${reset}"
echo ""
else
    echo -e "\e[38;5;130m────────────────────────────────────────────\033[0m"
    echo -e "\e[38;5;82m             AUTOSCRIPT INTERFLAZZ ID             \033[0m"
    echo -e "\e[38;5;130m────────────────────────────────────────────\033[0m"
    echo -e ""
    echo -e "            \033[31mPERMISSION DENIED !\033[0m"
    echo -e "   \033[0;33mYour VPS\033[0m $(wget -qO- ipv4.icanhazip.com) \033[0;33mHas been Banned\033[0m"
    echo -e "     \033[0;33mBuy access permissions for scripts\033[0m"
    echo -e "             \033[0;33mContact Admin :\033[0m"
    echo -e "      \033[0;32mWhatsApp\033[0m wa.me/+6285196156105"
    echo -e "      \033[0;96mTelegram\033[0m t.me/interflazzid"
    echo -e "\e[38;5;130m────────────────────────────────────────────\033[0m"
    exit
fi
else
    echo -e "\e[38;5;130m────────────────────────────────────────────\033[0m"
    echo -e "\e[38;5;82m             AUTOSCRIPT INTERFLAZZ ID             \033[0m"
    echo -e "\e[38;5;130m────────────────────────────────────────────\033[0m"
    echo -e ""
    echo -e "            \033[31mPERMISSION DENIED !\033[0m"
    echo -e "   \033[0;33mYour VPS\033[0m $(wget -qO- ipv4.icanhazip.com) \033[0;33mHas been Banned\033[0m"
    echo -e "     \033[0;33mBuy access permissions for scripts\033[0m"
    echo -e "             \033[0;33mContact Admin :\033[0m"
    echo -e "      \033[0;32mWhatsApp\033[0m wa.me/+6285196156105"
    echo -e "      \033[0;96mTelegram\033[0m t.me/interflazzid"
    echo -e "\e[38;5;130m────────────────────────────────────────────\033[0m"
    exit
fi