#!/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)
password=$(openssl rand -base64 16)

# Exception handling if config file doesn't exist
if [ ! -f "/etc/xray/shadowsocks/config.json" ]; then
  echo "Shadowsocks config file not found. Creating a new file..."
  mkdir -p /etc/xray/shadowsocks
  echo '{"inbounds": []}' >/etc/xray/shadowsocks/config.json
fi

# Exception handling if shadowsocks directory doesn't exist
if [ ! -d "/etc/xray/shadowsocks" ]; then
  echo "Directory /etc/xray/shadowsocks not found. Creating directory..."
  mkdir -p /etc/xray/shadowsocks
fi

# 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/shadowsocks/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/shadowsocks 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
done
until [[ $quota =~ ^[0-9]+$ ]]; do
  read -p "   User Limit (GB): " quota
done
until [[ $ip_limit =~ ^[0-9]+$ ]]; do
  read -p "   User Limit (IP): " ip_limit
done

exp=$(date -d "$duration days" +"%Y-%m-%d")
method="aes-256-gcm"
password=$(cat /proc/sys/kernel/random/uuid)

# Add user to config file
sed -i '/#ssws$/a\### '"$user $exp"'\
},{"password": "'""$password""'","method": "'""$method""'","email": "'""$user""'"' /etc/xray/shadowsocks/config.json
sed -i '/#ssgrpc$/a\### '"$user $exp"'\
},{"password": "'""$password""'","method": "'""$method""'","email": "'""$user""'"' /etc/xray/shadowsocks/config.json

# Generate Shadowsocks links
ss_base64=$(echo -n "${method}:${password}" | base64 -w 0)
ss_link_ws="ss://${ss_base64}@${domain}:443?plugin=xray-plugin;mux=0;path=/ss-ws;host=${domain};tls;network=ws;host=$domain#${user}-WS"
ss_link_grpc="ss://${ss_base64}@${domain}:443?plugin=xray-plugin;mux=0;serviceName=ss-grpc;host=${domain};tls#${user}-gRPC"

# Create JSON config file
cat >/var/www/html/shadowsocks-$user.txt <<-END
---------------------
# Shadowsocks WS Format
---------------------

{
 "dns": {
    "servers": [
      "8.8.8.8",
      "8.8.4.4"
    ]
  },
 "inbounds": [
   {
      "port": 10808,
      "protocol": "socks",
      "settings": {
        "auth": "noauth",
        "udp": true,
        "userLevel": 8
      },
      "sniffing": {
        "destOverride": [
          "http",
          "tls"
        ],
        "enabled": true
      },
      "tag": "socks"
    },
    {
      "port": 10809,
      "protocol": "http",
      "settings": {
        "userLevel": 8
      },
      "tag": "http"
    }
  ],
  "log": {
    "loglevel": "none"
  },
  "outbounds": [
    {
      "mux": {
        "enabled": true
      },
      "protocol": "shadowsocks",
      "settings": {
        "servers": [
          {
            "address": "$domain",
            "level": 8,
            "method": "$method",
            "password": "$password",
            "port": 443
          }
        ]
      },
      "streamSettings": {
        "network": "ws",
        "security": "tls",
        "tlsSettings": {
          "allowInsecure": true,
          "serverName": "$domain"
        },
        "wsSettings": {
          "headers": {
            "Host": "$domain"
          },
          "path": "/ss-ws"
        }
      },
      "tag": "proxy"
    },
    {
      "protocol": "freedom",
      "settings": {},
      "tag": "direct"
    },
    {
      "protocol": "blackhole",
      "settings": {
        "response": {
          "type": "http"
        }
      },
      "tag": "block"
    }
  ],
  "policy": {
    "levels": {
      "8": {
        "connIdle": 300,
        "downlinkOnly": 1,
        "handshake": 4,
        "uplinkOnly": 1
      }
    },
    "system": {
      "statsOutboundUplink": true,
      "statsOutboundDownlink": true
    }
  },
  "routing": {
    "domainStrategy": "Asls",
"rules": []
  },
  "stats": {}
 }

---------------------
# Shadowsocks gRPC Format
---------------------

{
    "dns": {
    "servers": [
      "8.8.8.8",
      "8.8.4.4"
    ]
  },
 "inbounds": [
   {
      "port": 10808,
      "protocol": "socks",
      "settings": {
        "auth": "noauth",
        "udp": true,
        "userLevel": 8
      },
      "sniffing": {
        "destOverride": [
          "http",
          "tls"
        ],
        "enabled": true
      },
      "tag": "socks"
    },
    {
      "port": 10809,
      "protocol": "http",
      "settings": {
        "userLevel": 8
      },
      "tag": "http"
    }
  ],
  "log": {
    "loglevel": "none"
  },
  "outbounds": [
    {
      "mux": {
        "enabled": true
      },
      "protocol": "shadowsocks",
      "settings": {
        "servers": [
          {
            "address": "$domain",
            "level": 8,
            "method": "$method",
            "password": "$password",
            "port": 443
          }
        ]
      },
      "streamSettings": {
        "grpcSettings": {
          "multiMode": true,
          "serviceName": "ss-grpc"
        },
        "network": "grpc",
        "security": "tls",
        "tlsSettings": {
          "allowInsecure": true,
          "serverName": "$domain"
        }
      },
      "tag": "proxy"
    },
    {
      "protocol": "freedom",
      "settings": {},
      "tag": "direct"
    },
    {
      "protocol": "blackhole",
      "settings": {
        "response": {
          "type": "http"
        }
      },
      "tag": "block"
    }
  ],
  "policy": {
    "levels": {
      "8": {
        "connIdle": 300,
        "downlinkOnly": 1,
        "handshake": 4,
        "uplinkOnly": 1
      }
    },
    "system": {
      "statsOutboundUplink": true,
      "statsOutboundDownlink": true
    }
  },
  "routing": {
    "domainStrategy": "Asls",
"rules": []
  },
  "stats": {}
}

---------------------
# Shadowsocks Account Links
---------------------
TLS Link : ${ss_link_ws}
---------------------
gRPC Link : ${ss_link_grpc}
---------------------

END

# Restart service
if ! systemctl restart shadowsocks@config >/dev/null 2>&1; then
  echo -e "${red}Failed to restart Shadowsocks service. Please check system logs for more information.${reset}"
  exit 1
fi

# Exception handling if config file doesn't exist
if [ ! -f "/etc/xray/shadowsocks/config.json" ]; then
  echo "Warning: Shadowsocks config file not found. Creating a new file..."
  mkdir -p /etc/xray/shadowsocks
  echo '{"server":["::1", "0.0.0.0"],"mode":"tcp_and_udp"}' >/etc/xray/shadowsocks/config.json
  systemctl restart shadowsocks@config
fi

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

# Set default values if empty
[ -z ${ip_limit} ] && ip_limit="0"
[ -z ${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/shadowsocks/${user}
  echo "${ip_limit}" >/etc/xray/shadowsocks/${user}IP
fi

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

# Exception handling if database file doesn't exist
if [ ! -f "$db_file" ]; then
  echo "Database file not found. Creating a 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} ${password}" >>"$db_file"

# Display account information
clear -x
print_rainbow "───────────────────────────"
print_rainbow "  Xray/Shadowsocks Account "
print_rainbow "───────────────────────────"
echo -e "Description  : ${user}"
echo -e "Server Host  : ${domain}"
echo -e "XrayDNS Host : ${ns_domain}"
echo -e "Location     : ${city}"
echo -e "Port         : 443"
echo -e "Method       : ${method}"
echo -e "Password     : ${password}"
echo -e "WS Path      : /ss-ws"
echo -e "ServiceName  : ss-grpc"
echo -e "Public Key   : ${pubkey}"
print_rainbow "───────────────────────────"
echo -e "SS WS Link   : ${ss_link_ws}"
print_rainbow "───────────────────────────"
echo -e "SS gRPC Link : ${ss_link_grpc}"
print_rainbow "───────────────────────────"
echo -e "OpenClash Format : https://${domain}:81/shadowsocks-${user}.txt"
print_rainbow "───────────────────────────"
echo -e "Expires On   : ${exp}"
echo -e ""

# Save log
{
  echo "───────────────────────────"
  echo "  Xray/Shadowsocks Account "
  echo "───────────────────────────"
  echo "Description  : ${user}"
  echo "Server Host  : ${domain}"
  echo "XrayDNS Host : ${ns_domain}"
  echo "Location     : ${city}"
  echo "Port         : 443"
  echo "Method       : ${method}"
  echo "Password     : ${password}"
  echo "WS Path      : /ss-ws"
  echo "ServiceName  : ss-grpc"
  echo "Public Key   : ${pubkey}"
  echo "───────────────────────────"
  echo "SS WS Link   : ${ss_link_ws}"
  echo "───────────────────────────"
  echo "SS gRPC Link : ${ss_link_grpc}"
  echo "───────────────────────────"
  echo "OpenClash Format : https://${domain}:81/shadowsocks-${user}.txt"
  echo "───────────────────────────"
  echo "Expires On   : ${exp}"
  echo ""
} >> "/etc/xray/shadowsocks/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