#!/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
ip=$(wget -qO- ipv4.icanhazip.com)
srv_date=$(curl -v --insecure --silent https://google.com/ 2>&1 | grep Date | sed -e 's/< Date: //')
date=$(date +"%Y-%m-%d" -d "$srv_date")
city=$(cat /etc/xray/city 2>/dev/null || echo "Unknown city")
pubkey=$(cat /etc/slowdns/server.pub 2>/dev/null || echo "Pubkey not available")
ns_domain=$(cat /etc/xray/dns 2>/dev/null || echo "NS domain not set")
domain=$(cat /etc/xray/domain 2>/dev/null || hostname -f)
uuid=$(cat /proc/sys/kernel/random/uuid)

# Loading animation
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_rainbow "┌─────────────────────────────────────────┐"
print_rainbow "│            ENTER USER DATA              │"
print_rainbow "└─────────────────────────────────────────┘"
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/vmess/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_rainbow "┌─────────────────────────────────────────┐"
print_rainbow "│  .::.  AUTOSCRIPT INTERFLAZZ ID  .::.    │"
print_rainbow "│     Input xray/vmess account deps       │"
print_rainbow "│      Set Quota/IP Limit for Account     │"
print_rainbow "│           0 For Unlimited               │"
print_rainbow "└─────────────────────────────────────────┘"
echo "   Username : $user"
until [[ $duration =~ ^[0-9]+$ ]]; do
    read -p "   Active period (days): " duration
    if [[ -z "$duration" ]]; then
        echo -e "${red}   Active period cannot be empty${reset}"
    fi
done
until [[ $quota =~ ^[0-9]+$ ]]; do
    read -p "   User Quota (GB): " quota
    if [[ -z "$quota" ]]; then
        echo -e "${red}   User limit cannot be empty${reset}"
    fi
done
until [[ $ip_limit =~ ^[0-9]+$ ]]; do
    read -p "   Device Limit (IP): " ip_limit
    if [[ -z "$ip_limit" ]]; then
        echo -e "${red}   IP limit cannot be empty${reset}"
    fi
done

# Account creation process
exp=$(date -d "$duration days" +"%Y-%m-%d")
if [ ! -f "/etc/xray/vmess/config.json" ]; then
    echo "Configuration file not found. Creating new file..."
    echo '{"inbounds": []}' >/etc/xray/vmess/config.json
fi

if ! sed -i '/#vmess$/a\### '"$user $exp"'\
},{"id": "'""$uuid""'","email": "'""$user""'"' /etc/xray/vmess/config.json; then
    echo -e "${red}Failed to add user to config.json${reset}"
    exit 1
fi
if ! sed -i '/#vmessgrpc$/a\### '"$user $exp"'\
},{"id": "'""$uuid""'","email": "'""$user""'"' /etc/xray/vmess/config.json; then
    echo -e "${red}Failed to add user to config.json (GRPC)${reset}"
    exit 1
fi

# Create configuration files
cat >/etc/xray/vmess/$user-tls.json <<EOF
{
    "v": "2",
    "ps": "$user WS (CDN) TLS",
    "add": "${domain}",
    "port": "443",
    "id": "${uuid}",
    "aid": "0",
    "net": "ws",
    "path": "/vmess",
    "type": "none",
    "host": "${domain}",
    "tls": "tls"
}
EOF

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

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

# Create configuration file for OpenClash
cat >/var/www/html/vmess-$user.txt <<-END
---------------------
# Format Vmess WS (CDN)
---------------------

- name: Vmess-$user-WS (CDN)
  type: vmess
  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: /vmess
    headers:
      Host: ${domain}
---------------------
# Format Vmess WS (CDN) Non TLS
---------------------

- name: Vmess-$user-WS (CDN) Non TLS
  type: vmess
  server: ${domain}
  port: 80
  uuid: ${uuid}
  alterId: 0
  cipher: auto
  udp: true
  tls: false
  skip-cert-verify: false
  servername: ${domain}
  network: ws
  ws-opts:
    path: /vmess
    headers:
      Host: ${domain}
---------------------
# Format Vmess gRPC (SNI)
---------------------

- name: Vmess-$user-gRPC (SNI)
  server: ${domain}
  port: 443
  type: vmess
  uuid: ${uuid}
  alterId: 0
  cipher: auto
  network: grpc
  tls: true
  servername: ${domain}
  skip-cert-verify: true
  grpc-opts:
    grpc-service-name: vmess-grpc

---------------------
# Vmess Account Links
---------------------
TLS Link : vmess://$(base64 -w 0 /etc/xray/vmess/$user-tls.json)
---------------------
Non-TLS Link : vmess://$(base64 -w 0 /etc/xray/vmess/$user-non.json)
---------------------
GRPC Link : vmess://$(base64 -w 0 /etc/xray/vmess/$user-grpc.json)
---------------------

END

# Generate Vmess links
vmess_tls="vmess://$(base64 -w 0 /etc/xray/vmess/$user-tls.json)"
vmess_non="vmess://$(base64 -w 0 /etc/xray/vmess/$user-non.json)"
vmess_grpc="vmess://$(base64 -w 0 /etc/xray/vmess/$user-grpc.json)"

# Restart service
if ! systemctl restart vmess@config; then
    echo -e "${red}Failed to restart vmess service${reset}"
    exit 1
fi

# Exception if configuration file doesn't exist
if [ ! -f "/etc/xray/vmess/config.json" ]; then
    echo "Warning: Vmess configuration file not found. Creating new file..."
    mkdir -p /etc/xray/vmess
    echo '{"inbounds": []}' >/etc/xray/vmess/config.json
    systemctl restart vmess@config
fi

# Create directory if it doesn't exist
if [ ! -d "/etc/xray/vmess" ]; then
    echo "Directory /etc/xray/vmess not found. Creating directory..."
    mkdir -p /etc/xray/vmess
    if [ $? -ne 0 ]; then
        echo "Failed to create directory /etc/xray/vmess. Make sure you have sufficient permissions."
        exit 1
    fi
fi

# Exception if configuration file doesn't exist
if [ ! -f "/etc/xray/vmess/config.json" ]; then
    echo "Vmess configuration file not found. Creating new file..."
    echo '{"inbounds": []}' >/etc/xray/vmess/config.json
    if [ $? -ne 0 ]; then
        echo "Failed to create Vmess configuration file. Make sure you have sufficient permissions."
        exit 1
    fi
fi

# Set default values if empty
ip_limit=${ip_limit:-0}
quota=${quota:-0}

# Convert Quota to bytes
quota_bytes=$((${quota} * 1024 * 1024 * 1024))

# Save quota and IP limit data
if [[ ${quota} != "0" ]]; then
    echo "${quota_bytes}" >/etc/xray/vmess/${user}
    echo "${ip_limit}" >/etc/xray/vmess/${user}IP
fi

# Update database
db_file="/etc/xray/vmess/.vmess.db"
temp_file="/etc/xray/vmess/.vmess.db.tmp"

# Exception if database file doesn't exist
if [ ! -f "$db_file" ]; then
    echo "Warning: Vmess database file not found. Creating new file..."
    touch "$db_file"
fi

# Remove old entry if exists
grep -v "^### ${user} " "$db_file" >"$temp_file"
mv "$temp_file" "$db_file"

# Add new entry
echo "### ${user} ${exp} ${uuid}" >>"$db_file"

# Display account information
clear -x
print_rainbow "───────────────────────────"
print_rainbow "    Xray/Vmess Account    "
print_rainbow "───────────────────────────"
echo -e "Remarks      : ${user}"
echo -e "Host Server  : ${domain}"
echo -e "Host XrayDNS : ${ns_domain}"
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   : ${pubkey}"
print_rainbow "───────────────────────────"
echo -e "TLS Link    : ${vmess_tls}"
print_rainbow "───────────────────────────"
echo -e "NTLS Link   : ${vmess_non}"
print_rainbow "───────────────────────────"
echo -e "GRPC Link   : ${vmess_grpc}"
print_rainbow "───────────────────────────"
echo -e "OpenClash Format : https://${domain}:81/vmess-$user.txt"
print_rainbow "───────────────────────────"
echo -e "Expires On  : $exp"
echo -e ""

# Save original log
{
    echo "───────────────────────────"
    echo "    Xray/Vmess Account    "
    echo "───────────────────────────"
    echo "remarks      : ${user}"
    echo "host_server  : ${domain}"
    echo "host_xraydns : ${ns_domain}"
    echo "location     : $city"
    echo "location     : $kota"
    echo "port_tls     : 443"
    echo "port_nontls  : 80, 8080"
    echo "port_dns     : 443, 53"
    echo "port_grpc    : 443"
    echo "alterid      : 0"
    echo "security     : auto"
    echo "network      : WS or gRPC"
    echo "path         : /vmess"
    echo "servicename  : vmess-grpc"
    echo "user_id      : ${uuid}"
    echo "public_key   : ${pubkey}"
    echo "───────────────────────────"
    echo "tls_link     : ${vmess_tls}"
    echo "───────────────────────────"
    echo "ntls_link    : ${vmess_non}"
    echo "───────────────────────────"
    echo "grpc_link    : ${vmess_grpc}"
    echo "───────────────────────────"
    echo "openclash_format : https://${domain}:81/vmess-$user.txt"
    echo "───────────────────────────"
    echo "expires_on   : $exp"
    echo ""
} >> /etc/xray/vmess/log-create-${user}.log

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