#!/bin/bash

BASE_URL="https://autoscript.interflazz.my.id/v2"

red="\e[91m"
green="\e[92m"
yellow="\e[93m"
blue="\e[94m"
purple="\e[95m"
cyan="\e[96m"
white="\e[97m"
orange="\e[38;5;130m"
bold_white="\e[1;37m"
reset="\e[0m"

update_box_width() {
    local cols

    cols=$(tput cols 2>/dev/null || echo 80)

    if [ "$cols" -gt 72 ]; then
        BOX_WIDTH=72
    elif [ "$cols" -lt 30 ]; then
        BOX_WIDTH=30
    else
        BOX_WIDTH=$((cols - 2))
    fi

    BOX_INNER=$((BOX_WIDTH - 4))
}

repeat_char() {
    local count="$1"
    local char="$2"
    local line

    printf -v line '%*s' "$count" ""
    printf '%s' "${line// /$char}"
}

box_top() {
    update_box_width

    printf "%b┌" "$orange"
    repeat_char $((BOX_WIDTH - 2)) "─"
    printf "┐%b\n" "$reset"
}

box_middle() {
    update_box_width

    printf "%b├" "$orange"
    repeat_char $((BOX_WIDTH - 2)) "─"
    printf "┤%b\n" "$reset"
}

box_bottom() {
    update_box_width

    printf "%b└" "$orange"
    repeat_char $((BOX_WIDTH - 2)) "─"
    printf "┘%b\n" "$reset"
}

box_empty() {
    update_box_width

    printf "%b│%b" "$orange" "$reset"
    printf "%*s" $((BOX_WIDTH - 2)) ""
    printf "%b│%b\n" "$orange" "$reset"
}

box_center() {
    update_box_width

    local text="$1"
    local color="${2:-$white}"
    local length=${#text}
    local available="$BOX_INNER"

    if [ "$length" -gt "$available" ]; then
        box_left "$text" "$color"
        return
    fi

    local left=$(((available - length) / 2))
    local right=$((available - length - left))

    printf "%b│%b " "$orange" "$reset"
    printf "%*s" "$left" ""
    printf "%b%s%b" "$color" "$text" "$reset"
    printf "%*s" "$right" ""
    printf " %b│%b\n" "$orange" "$reset"
}

box_left() {
    update_box_width

    local text="$1"
    local color="${2:-$white}"
    local available="$BOX_INNER"
    local length=${#text}
    local offset=0
    local part
    local part_length
    local right

    if [ "$length" -eq 0 ]; then
        box_empty
        return
    fi

    while [ "$offset" -lt "$length" ]; do
        part="${text:$offset:$available}"
        part_length=${#part}
        right=$((available - part_length))

        printf "%b│%b " "$orange" "$reset"
        printf "%b%s%b" "$color" "$part" "$reset"
        printf "%*s" "$right" ""
        printf " %b│%b\n" "$orange" "$reset"

        offset=$((offset + available))
    done
}

show_access_denied() {
    local reason="$1"

    clear

    box_top
    box_center "INTERFLAZZ.MY.ID" "$green"
    box_center "AUTOSCRIPT PREMIUM" "$bold_white"
    box_middle
    box_center "AKSES DITOLAK!" "$red"
    box_middle
    box_left "IP VPS : $vps_ip" "$yellow"
    box_left "$reason" "$yellow"
    box_middle
    box_center "HUBUNGI ADMIN" "$bold_white"
    box_left "WhatsApp ~ https://wa.me/6285956131443" "$green"
    box_left "Telegram ~ https://t.me/interflazz" "$cyan"
    box_bottom
}

vps_ip=$(wget -qO- ipv4.icanhazip.com)

data_acc=$(
    curl -s "${BASE_URL}/access" |
        grep "### $vps_ip " |
        awk '{print $3}'
)

if [ -z "$data_acc" ]; then
    show_access_denied "VPS belum memiliki izin akses script."
    exit 1
fi

expiry_date=$(date -d "$data_acc" +%s 2>/dev/null)
current_date=$(date +%s)

if [ -z "$expiry_date" ] || [ "$expiry_date" -le "$current_date" ]; then
    show_access_denied "Masa aktif akses script telah berakhir."
    exit 1
fi

remaining_days=$(((expiry_date - current_date) / 86400))

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" 2>/dev/null)
city=$(cat /etc/xray/city 2>/dev/null || echo "Tidak diketahui")
pubkey=$(cat /etc/slowdns/server.pub 2>/dev/null || echo "Public Key tidak tersedia")
ns_domain=$(cat /etc/xray/dns 2>/dev/null || echo "Domain SlowDNS belum tersedia")
domain=$(cat /etc/xray/domain 2>/dev/null || hostname -f)
uuid=$(cat /proc/sys/kernel/random/uuid)

if [ ! -d "/etc/xray/trojan" ]; then
    echo -e "${yellow}Direktori /etc/xray/trojan tidak ditemukan. Membuat direktori...${reset}"

    mkdir -p /etc/xray/trojan

    if [ $? -ne 0 ]; then
        echo -e "${red}Gagal membuat direktori /etc/xray/trojan.${reset}"
        exit 1
    fi
fi

if [ ! -f "/etc/xray/trojan/config.json" ]; then
    echo -e "${yellow}Konfigurasi Trojan tidak ditemukan. Membuat konfigurasi baru...${reset}"

    echo '{"inbounds": []}' >/etc/xray/trojan/config.json
fi

if [ ! -f "/etc/xray/trojan/.trojan.db" ]; then
    echo -e "${yellow}Database Trojan tidak ditemukan. Membuat database baru...${reset}"

    touch /etc/xray/trojan/.trojan.db
fi

mkdir -p /var/www/html

echo ""
echo -ne "${yellow}Menyiapkan Akun Premium${reset}"

for i in {1..2}; do
    for j in ⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏; do
        echo -ne "\r${yellow}Menyiapkan Akun Premium $j${reset}"
        sleep 0.1
    done
done

echo -ne "\r${green}Akun Premium siap dibuat!${reset}\n"

sleep 1

clear

box_top
box_center "INTERFLAZZ.MY.ID" "$green"
box_center "BUAT AKUN XRAY / TROJAN" "$bold_white"
box_middle
box_center "MASUKKAN DATA PENGGUNA" "$yellow"
box_bottom

echo ""

while true; do
    read -p "Nama Pengguna : " user

    if [[ ${#user} -lt 3 || ! "$user" =~ ^[a-zA-Z0-9_-]+$ ]]; then
        echo -e "${red}Nama pengguna minimal 3 karakter dan hanya boleh berisi huruf, angka, _ atau -.${reset}"
        continue
    fi

    if grep -q "^### $user " /etc/xray/trojan/config.json; then
        random_number=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 5)

        user="${random_number}${user}"

        echo -e "${yellow}Nama pengguna sudah digunakan. Nama baru: $user${reset}"

        break
    fi

    break
done

echo ""

clear

box_top
box_center "INTERFLAZZ.MY.ID" "$green"
box_center "XRAY / TROJAN PREMIUM" "$bold_white"
box_middle
box_left "Nama Pengguna : $user" "$white"
box_middle
box_left "Masukkan masa aktif akun dalam hari." "$yellow"
box_left "Masukkan batas kuota akun dalam GB." "$yellow"
box_left "Masukkan batas penggunaan IP akun." "$yellow"
box_left "Gunakan angka 0 untuk tanpa batas." "$green"
box_bottom

echo ""

until [[ ${duration:-} =~ ^[0-9]+$ ]]; do
    read -p "Masa Aktif (Hari) : " duration

    if [[ ! ${duration:-} =~ ^[0-9]+$ ]]; then
        echo -e "${red}Masa aktif harus berupa angka.${reset}"
    fi
done

until [[ ${quota:-} =~ ^[0-9]+$ ]]; do
    read -p "Batas Kuota (GB) : " quota

    if [[ ! ${quota:-} =~ ^[0-9]+$ ]]; then
        echo -e "${red}Kuota harus berupa angka.${reset}"
    fi
done

until [[ ${ip_limit:-} =~ ^[0-9]+$ ]]; do
    read -p "Batas IP : " ip_limit

    if [[ ! ${ip_limit:-} =~ ^[0-9]+$ ]]; then
        echo -e "${red}Batas IP harus berupa angka.${reset}"
    fi
done

exp=$(date -d "$duration days" +"%Y-%m-%d")

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

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

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

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

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

trojan_tls="trojan://${uuid}@${domain}:443?path=%2Fwhatever%2Ftrojan-ws&security=tls&host=${domain}&type=ws&sni=${domain}#${user}"

trojan_grpc="trojan://${uuid}@${domain}:443?mode=gun&security=tls&type=grpc&serviceName=trojan-grpc&sni=${domain}#${user}"

cat >/var/www/html/trojan-$user.txt <<END
────────────────────────────────────────────
INTERFLAZZ.MY.ID
FORMAT TROJAN WS TLS
────────────────────────────────────────────

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

────────────────────────────────────────────
FORMAT TROJAN WS NON TLS
────────────────────────────────────────────

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

────────────────────────────────────────────
FORMAT TROJAN GRPC
────────────────────────────────────────────

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

────────────────────────────────────────────
LINK AKUN TROJAN
────────────────────────────────────────────

TLS Link
${trojan_tls}

────────────────────────────────────────────

gRPC Link
${trojan_grpc}

────────────────────────────────────────────
INTERFLAZZ.MY.ID
────────────────────────────────────────────
END

if ! systemctl restart trojan@config >/dev/null 2>&1; then
    echo ""

    box_top
    box_center "INTERFLAZZ.MY.ID" "$green"
    box_middle
    box_center "GAGAL MEMULAI ULANG TROJAN" "$red"
    box_middle
    box_left "Silakan periksa konfigurasi Xray dan log systemd." "$yellow"
    box_bottom

    exit 1
fi

if [ ! -f "/etc/xray/trojan/config.json" ]; then
    echo -e "${yellow}Konfigurasi Trojan tidak ditemukan. Membuat konfigurasi baru...${reset}"

    mkdir -p /etc/xray/trojan

    echo '{"inbounds": []}' >/etc/xray/trojan/config.json

    systemctl restart trojan@config
fi

if [ ! -d "/etc/xray/trojan" ]; then
    echo -e "${yellow}Direktori /etc/xray/trojan tidak ditemukan. Membuat direktori...${reset}"

    mkdir -p /etc/xray/trojan

    if [ $? -ne 0 ]; then
        echo -e "${red}Gagal membuat direktori /etc/xray/trojan. Pastikan izin akses mencukupi.${reset}"
        exit 1
    fi
fi

[ -z "${ip_limit:-}" ] && ip_limit="0"
[ -z "${quota:-}" ] && quota="0"

quota_bytes=$((${quota} * 1024 * 1024 * 1024))

if [[ ${quota} != "0" ]]; then
    echo "${quota_bytes}" >/etc/xray/trojan/${user}
    echo "${ip_limit}" >/etc/xray/trojan/${user}IP
fi

db_file="/etc/xray/trojan/.trojan.db"
temp_file="/etc/xray/trojan/.trojan.db.tmp"

if [ ! -f "$db_file" ]; then
    echo -e "${yellow}Database Trojan tidak ditemukan. Membuat database baru...${reset}"

    touch "$db_file"
fi

grep -v "^### ${user} " "$db_file" >"$temp_file"

mv "$temp_file" "$db_file"

echo "### ${user} ${exp} ${uuid}" >>"$db_file"

clear -x

box_top
box_center "INTERFLAZZ.MY.ID" "$green"
box_center "AKUN XRAY / TROJAN" "$bold_white"
box_middle
box_left "Nama Pengguna : ${user}" "$white"
box_left "Server         : ${domain}" "$white"
box_left "XrayDNS        : ${ns_domain}" "$white"
box_left "Lokasi         : ${city}" "$white"
box_middle
box_left "TLS Port       : 443" "$cyan"
box_left "DNS Port       : 443, 53" "$cyan"
box_left "gRPC Port      : 443" "$cyan"
box_left "Keamanan       : auto" "$cyan"
box_left "Jaringan       : WS atau gRPC" "$cyan"
box_left "Path WS        : /whatever/trojan-ws" "$cyan"
box_left "Service Name   : trojan-grpc" "$cyan"
box_middle
box_left "Password       : ${uuid}" "$white"
box_left "Public Key     : ${pubkey}" "$white"
box_middle
box_left "Batas IP       : ${ip_limit}" "$yellow"
box_left "Kuota          : ${quota} GB" "$yellow"
box_left "Masa Aktif     : ${duration} Hari" "$yellow"
box_left "Kadaluarsa    : ${exp}" "$yellow"
box_middle
box_left "TLS Link :" "$green"
box_left "${trojan_tls}" "$white"
box_middle
box_left "gRPC Link :" "$green"
box_left "${trojan_grpc}" "$white"
box_middle
box_left "Format OpenClash :" "$cyan"
box_left "https://${domain}:81/trojan-${user}.txt" "$white"
box_middle
box_left "WhatsApp ~ https://wa.me/6285956131443" "$green"
box_left "Telegram ~ https://t.me/interflazz" "$cyan"
box_bottom

{
    echo "────────────────────────────────────────────"
    echo "INTERFLAZZ.MY.ID"
    echo "AKUN XRAY / TROJAN"
    echo "────────────────────────────────────────────"
    echo "Nama Pengguna : ${user}"
    echo "Server         : ${domain}"
    echo "XrayDNS        : ${ns_domain}"
    echo "Lokasi         : ${city}"
    echo "────────────────────────────────────────────"
    echo "TLS Port       : 443"
    echo "DNS Port       : 443, 53"
    echo "gRPC Port      : 443"
    echo "Keamanan       : auto"
    echo "Jaringan       : WS atau gRPC"
    echo "Path WS        : /whatever/trojan-ws"
    echo "Service Name   : trojan-grpc"
    echo "Password       : ${uuid}"
    echo "Public Key     : ${pubkey}"
    echo "────────────────────────────────────────────"
    echo "Batas IP       : ${ip_limit}"
    echo "Kuota          : ${quota} GB"
    echo "Masa Aktif     : ${duration} Hari"
    echo "Kadaluarsa    : ${exp}"
    echo "────────────────────────────────────────────"
    echo "TLS Link"
    echo "${trojan_tls}"
    echo "────────────────────────────────────────────"
    echo "gRPC Link"
    echo "${trojan_grpc}"
    echo "────────────────────────────────────────────"
    echo "Format OpenClash"
    echo "https://${domain}:81/trojan-${user}.txt"
    echo "────────────────────────────────────────────"
    echo "WhatsApp ~ https://wa.me/6285956131443"
    echo "Telegram ~ https://t.me/interflazz"
    echo "────────────────────────────────────────────"
    echo ""
} >>"/etc/xray/trojan/log-create-${user}.log"