#!/bin/bash

BASE_URL="https://autoscript.interflazz.my.id/v2"
BRAND="INTERFLAZZ.MY.ID"
WHATSAPP="https://wa.me/6285956131443"
TELEGRAM="https://t.me/interflazz"

green="\e[38;5;82m"
red="\e[38;5;196m"
yellow="\e[38;5;226m"
blue="\e[38;5;39m"
purple="\e[38;5;141m"
cyan="\e[38;5;51m"
white="\e[97m"
orange="\e[38;5;130m"
bold_white="\e[1;37m"
reset="\e[0m"

BASE_DIR="/etc/xray/vmess"
CONFIG_FILE="${BASE_DIR}/config.json"
DB_FILE="${BASE_DIR}/.vmess.db"
USAGE_DIR="${BASE_DIR}/usage"
WEB_DIR="/var/www/html"

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 "$BRAND" "$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 ~ $WHATSAPP" "$green"
    box_left "Telegram ~ $TELEGRAM" "$cyan"
    box_bottom

    exit 1
}

generate_username() {
    local generated

    while true; do
        generated=$(
            tr -dc 'a-z0-9' </dev/urandom |
                head -c 8
        )

        [ -z "$generated" ] && continue

        if ! grep -q "^### ${generated} " "$DB_FILE" 2>/dev/null; then
            printf '%s' "$generated"
            return
        fi
    done
}

cleanup_failed_account() {
    local user="$1"
    local exp="$2"

    if [ -f "$CONFIG_FILE" ]; then
        sed -i "/^### ${user} ${exp}$/,+1d" "$CONFIG_FILE"
    fi

    if [ -f "$DB_FILE" ]; then
        sed -i "/^### ${user} /d" "$DB_FILE"
    fi

    rm -f \
        "${BASE_DIR}/${user}" \
        "${BASE_DIR}/${user}IP" \
        "${USAGE_DIR}/${user}" \
        "${BASE_DIR}/log-create-${user}.log" \
        "${BASE_DIR}/${user}-non.json" \
        "${BASE_DIR}/${user}-tls.json" \
        "${BASE_DIR}/${user}-grpc.json" \
        "${WEB_DIR}/vmess-${user}.txt"

    systemctl restart vmess@config >/dev/null 2>&1 || true
}

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

if [ -z "$vps_ip" ]; then
    vps_ip=$(curl -4 -s ipv4.icanhazip.com)
fi

if [ -z "$vps_ip" ]; then
    vps_ip="Tidak diketahui"
fi

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."
fi

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

if [ -z "$expiry_date" ]; then
    show_access_denied "Data masa aktif script tidak valid."
fi

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

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

mkdir -p "$BASE_DIR" "$USAGE_DIR" "$WEB_DIR"

if [ ! -f "$DB_FILE" ]; then
    touch "$DB_FILE"
fi

if [ ! -f "$CONFIG_FILE" ]; then
    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "TRIAL VMESS" "$bold_white"
    box_middle
    box_center "CONFIG VMESS TIDAK DITEMUKAN" "$red"
    box_middle
    box_left "File : $CONFIG_FILE" "$yellow"
    box_bottom

    exit 1
fi

if ! grep -q '^#vmess$' "$CONFIG_FILE"; then
    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "TRIAL VMESS" "$bold_white"
    box_middle
    box_center "MARKER CONFIG TIDAK DITEMUKAN" "$red"
    box_middle
    box_left "Marker : #vmess" "$yellow"
    box_bottom

    exit 1
fi

if ! grep -q '^#vmessgrpc$' "$CONFIG_FILE"; then
    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "TRIAL VMESS" "$bold_white"
    box_middle
    box_center "MARKER CONFIG TIDAK DITEMUKAN" "$red"
    box_middle
    box_left "Marker : #vmessgrpc" "$yellow"
    box_bottom

    exit 1
fi

domain=$(cat /etc/xray/domain 2>/dev/null)
city=$(cat /etc/xray/city 2>/dev/null)
pubkey=$(cat /etc/slowdns/server.pub 2>/dev/null)
ns_domain=$(cat /etc/xray/dns 2>/dev/null)

domain=${domain:-$(hostname -f 2>/dev/null)}
city=${city:-Tidak diketahui}
pubkey=${pubkey:-Tidak tersedia}
ns_domain=${ns_domain:-Belum diatur}

if [ -z "$domain" ]; then
    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "TRIAL VMESS" "$bold_white"
    box_middle
    box_center "DOMAIN BELUM DIATUR" "$red"
    box_middle
    box_center "Silakan atur domain VPS terlebih dahulu." "$yellow"
    box_bottom

    exit 1
fi

if ! command -v trial >/dev/null 2>&1; then
    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "TRIAL VMESS" "$bold_white"
    box_middle
    box_center "COMMAND TRIAL TIDAK DITEMUKAN" "$red"
    box_middle
    box_left "Pastikan /usr/bin/trial sudah terpasang." "$yellow"
    box_bottom

    exit 1
fi

clear

box_top
box_center "$BRAND" "$green"
box_center "BUAT TRIAL VMESS" "$bold_white"
box_middle
box_center "MEMPERSIAPKAN AKUN TRIAL" "$yellow"
box_bottom

echo ""

for i in 1 2; do
    for spinner in "⠋" "⠙" "⠹" "⠸" "⠼" "⠴" "⠦" "⠧" "⠇" "⠏"; do
        printf "\r%bMenyiapkan akun trial %s%b" "$yellow" "$spinner" "$reset"
        sleep 0.1
    done
done

printf "\r%bAkun trial siap dibuat.            %b\n" "$green" "$reset"
sleep 1

clear

box_top
box_center "$BRAND" "$green"
box_center "TRIAL VMESS" "$bold_white"
box_middle
box_center "MASUKKAN DURASI TRIAL" "$yellow"
box_bottom

echo ""

user=$(generate_username)
uuid=$(cat /proc/sys/kernel/random/uuid)

echo -e "Username otomatis : ${green}${user}${reset}"

while true; do
    read -rp "Durasi trial [menit] : " duration

    if [[ "$duration" =~ ^[1-9][0-9]*$ ]]; then
        break
    fi

    echo -e "${red}Durasi trial harus berupa angka lebih dari 0 menit.${reset}"
done

expiration_datetime=$(date -d "+${duration} minutes" +"%Y-%m-%d %H:%M:%S" 2>/dev/null)

expiry_days=$(((duration + 1439) / 1440))

if [ "$expiry_days" -lt 1 ]; then
    expiry_days=1
fi

exp=$(date -d "+${expiry_days} days" +"%Y-%m-%d" 2>/dev/null)

if [ -z "$expiration_datetime" ] || [ -z "$exp" ]; then
    echo -e "${red}Gagal menghitung waktu kadaluarsa akun.${reset}"
    exit 1
fi

if ! sed -i '/^#vmess$/a\### '"$user $exp"'\
},{"id": "'"$uuid"'","alterId": 0,"email": "'"$user"'"}' "$CONFIG_FILE"; then
    echo -e "${red}Gagal menambahkan akun VMess WebSocket.${reset}"
    exit 1
fi

if ! sed -i '/^#vmessgrpc$/a\### '"$user $exp"'\
},{"id": "'"$uuid"'","alterId": 0,"email": "'"$user"'"}' "$CONFIG_FILE"; then
    cleanup_failed_account "$user" "$exp"

    echo -e "${red}Gagal menambahkan akun VMess gRPC.${reset}"
    exit 1
fi

printf '### %s %s %s\n' \
    "$user" \
    "$exp" \
    "$uuid" \
    >>"$DB_FILE"

printf '0\n' >"${BASE_DIR}/${user}"
printf '0\n' >"${BASE_DIR}/${user}IP"
printf '0\n' >"${USAGE_DIR}/${user}"

cat >"${BASE_DIR}/${user}-tls.json" <<EOF
{
  "v": "2",
  "ps": "${user} WS TLS",
  "add": "${domain}",
  "port": "443",
  "id": "${uuid}",
  "aid": "0",
  "scy": "auto",
  "net": "ws",
  "type": "none",
  "host": "${domain}",
  "path": "/whatever/vmess",
  "tls": "tls",
  "sni": "${domain}"
}
EOF

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

cat >"${BASE_DIR}/${user}-grpc.json" <<EOF
{
  "v": "2",
  "ps": "${user} GRPC",
  "add": "${domain}",
  "port": "443",
  "id": "${uuid}",
  "aid": "0",
  "scy": "auto",
  "net": "grpc",
  "type": "none",
  "host": "${domain}",
  "path": "vmess-grpc",
  "tls": "tls",
  "sni": "${domain}"
}
EOF

vmess_tls="vmess://$(base64 -w 0 "${BASE_DIR}/${user}-tls.json")"
vmess_non="vmess://$(base64 -w 0 "${BASE_DIR}/${user}-non.json")"
vmess_grpc="vmess://$(base64 -w 0 "${BASE_DIR}/${user}-grpc.json")"

cat >"${WEB_DIR}/vmess-${user}.txt" <<EOF
========================================
${BRAND}
VMESS TRIAL ACCOUNT
========================================

Username       : ${user}
UUID           : ${uuid}
Host           : ${domain}
Xray DNS       : ${ns_domain}
Lokasi         : ${city}
TLS Port       : 443
Non-TLS Port   : 80
gRPC Port      : 443
AlterId        : 0
Security       : auto
Path WS        : /whatever/vmess
ServiceName    : vmess-grpc
Public Key     : ${pubkey}
Durasi Trial   : ${duration} Menit
Kadaluarsa     : ${expiration_datetime}

========================================
VMESS WEBSOCKET TLS
========================================

${vmess_tls}

========================================
VMESS WEBSOCKET NON-TLS
========================================

${vmess_non}

========================================
VMESS GRPC
========================================

${vmess_grpc}

========================================
EOF

cat >"${BASE_DIR}/log-create-${user}.log" <<EOF
========================================
${BRAND}
VMESS TRIAL ACCOUNT
========================================

Username       : ${user}
Host Server    : ${domain}
Host XrayDNS   : ${ns_domain}
Lokasi         : ${city}
TLS Port       : 443
Non-TLS Port   : 80
gRPC Port      : 443
AlterId        : 0
Security       : auto
Network        : WS / gRPC
Path WS        : /whatever/vmess
ServiceName    : vmess-grpc
UUID           : ${uuid}
Public Key     : ${pubkey}
Durasi Trial   : ${duration} Menit
Kadaluarsa     : ${expiration_datetime}

========================================
TLS LINK
========================================

${vmess_tls}

========================================
NON-TLS LINK
========================================

${vmess_non}

========================================
GRPC LINK
========================================

${vmess_grpc}

========================================
EOF

if ! systemctl restart vmess@config >/dev/null 2>&1; then
    cleanup_failed_account "$user" "$exp"

    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "GAGAL MEMBUAT TRIAL VMESS" "$red"
    box_middle
    box_center "Service VMess gagal direstart." "$yellow"
    box_bottom

    exit 1
fi

if command -v tmux >/dev/null 2>&1; then
    tmux kill-session \
        -t "trial_vmess_${user}" \
        >/dev/null 2>&1 || true

    if ! tmux new-session \
        -d \
        -s "trial_vmess_${user}" \
        "trial trialws '${user}' '${duration}'"; then

        cleanup_failed_account "$user" "$exp"

        clear

        box_top
        box_center "$BRAND" "$green"
        box_center "GAGAL MENJALANKAN TIMER" "$red"
        box_bottom

        exit 1
    fi
else
    nohup trial trialws "$user" "$duration" \
        >/dev/null 2>&1 &

    trial_pid=$!

    if ! kill -0 "$trial_pid" >/dev/null 2>&1; then
        cleanup_failed_account "$user" "$exp"

        clear

        box_top
        box_center "$BRAND" "$green"
        box_center "GAGAL MENJALANKAN TIMER" "$red"
        box_bottom

        exit 1
    fi
fi

clear

box_top
box_center "$BRAND" "$green"
box_center "TRIAL VMESS BERHASIL" "$bold_white"
box_middle
box_left "Username      : $user" "$white"
box_left "Host Server   : $domain" "$white"
box_left "Host XrayDNS  : $ns_domain" "$white"
box_left "Lokasi        : $city" "$white"
box_left "TLS Port      : 443" "$white"
box_left "Non-TLS Port  : 80" "$white"
box_left "gRPC Port     : 443" "$white"
box_left "AlterId       : 0" "$white"
box_left "Security      : auto" "$white"
box_left "Network       : WS / gRPC" "$white"
box_left "Path WS       : /whatever/vmess" "$white"
box_left "ServiceName   : vmess-grpc" "$white"
box_left "UUID          : $uuid" "$white"
box_left "Public Key    : $pubkey" "$white"
box_middle
box_left "Durasi Trial  : $duration Menit" "$yellow"
box_left "Kadaluarsa    : $expiration_datetime" "$yellow"
box_bottom

echo ""

box_top
box_center "VMESS WEBSOCKET TLS" "$bold_white"
box_middle
box_left "$vmess_tls" "$green"
box_bottom

echo ""

box_top
box_center "VMESS WEBSOCKET NON-TLS" "$bold_white"
box_middle
box_left "$vmess_non" "$green"
box_bottom

echo ""

box_top
box_center "VMESS GRPC" "$bold_white"
box_middle
box_left "$vmess_grpc" "$green"
box_bottom

echo ""

box_top
box_center "DETAIL AKUN" "$bold_white"
box_middle
box_left "https://${domain}:81/vmess-${user}.txt" "$cyan"
box_bottom

echo ""

box_top
box_center "INFORMASI SCRIPT" "$bold_white"
box_middle
box_left "Masa Aktif Script : $remaining_days Hari" "$yellow"
box_left "WhatsApp ~ $WHATSAPP" "$green"
box_left "Telegram ~ $TELEGRAM" "$cyan"
box_bottom

exit 0