#!/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"

DB_FILE="/etc/ssh/.ssh.db"
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 ! id "$generated" >/dev/null 2>&1 &&
           ! grep -q "^### ${generated} " "$DB_FILE" 2>/dev/null; then
            printf '%s' "$generated"
            return
        fi
    done
}

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 /etc/ssh /etc/xray "$WEB_DIR"

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

ip="$vps_ip"

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

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

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

    box_top
    box_center "$BRAND" "$green"
    box_center "TRIAL SSH / OVPN" "$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 SSH / OVPN" "$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 SSH / OVPN" "$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 SSH / OVPN" "$bold_white"
box_middle
box_center "MASUKKAN DURASI TRIAL" "$yellow"
box_bottom

echo ""

user=$(generate_username)
password="$user"

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)
expiration_date=$(date -d "+${duration} minutes" +"%Y-%m-%d" 2>/dev/null)

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

if ! useradd \
    -e "$expiration_date" \
    -s /bin/false \
    -M \
    "$user" >/dev/null 2>&1; then

    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "GAGAL MEMBUAT AKUN" "$red"
    box_middle
    box_left "Username : $user" "$yellow"
    box_bottom

    exit 1
fi

if ! printf '%s:%s\n' "$user" "$password" |
    chpasswd >/dev/null 2>&1; then

    userdel -f "$user" >/dev/null 2>&1

    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "GAGAL MEMBUAT PASSWORD" "$red"
    box_bottom

    exit 1
fi

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

printf '0\n' >"/etc/ssh/${user}"

payload="GET wss://BUG.COM/ HTTP/1.1[crlf]Host: ${domain}[crlf]Upgrade: websocket[crlf]Connection: Upgrade[crlf][crlf]"

cat >"${WEB_DIR}/ssh-${user}.txt" <<EOF
========================================
${BRAND}
SSH / OVPN TRIAL ACCOUNT
========================================

Username       : ${user}
Password       : ${password}
IP VPS         : ${ip}
Host           : ${domain}
SlowDNS Host   : ${ns_domain}
Lokasi         : ${city}

========================================
PORT
========================================

OpenSSH        : 22, 80, 443
Dropbear       : 109, 143, 443
SSH WebSocket  : 80, 8080
SSH SSL WS     : 443
SSL/TLS        : 443
OpenVPN SSL    : 443
OpenVPN TCP    : 1194
OpenVPN UDP    : 2200
UDP Custom     : 1-65535
DNS            : 53, 443
BadVPN UDP     : 7100, 7200, 7300

========================================
SLOWDNS
========================================

Nameserver     : ${ns_domain}
Public Key     : ${public_key}

========================================
WEBSOCKET PAYLOAD
========================================

${payload}

========================================
DOWNLOAD
========================================

OpenVPN:
https://${domain}:81/allovpn.zip

Detail Akun:
https://${domain}:81/ssh-${user}.txt

========================================
TRIAL
========================================

Durasi         : ${duration} Menit
Kadaluarsa     : ${expiration_datetime}

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

cat >"/etc/xray/log-createssh-${user}.log" <<EOF
========================================
${BRAND}
SSH / OVPN TRIAL ACCOUNT
========================================

Username         : ${user}
Password         : ${password}
IP VPS           : ${ip}
Host             : ${domain}
SlowDNS Host     : ${ns_domain}
Lokasi           : ${city}
OpenSSH          : 22, 80, 443
Dropbear         : 109, 143, 443
SSH WebSocket    : 80, 8080
SSH SSL WS       : 443
SSL/TLS          : 443
OpenVPN SSL      : 443
OpenVPN TCP      : 1194
OpenVPN UDP      : 2200
UDP Custom       : 1-65535
DNS              : 53, 443
BadVPN UDP       : 7100, 7200, 7300
SlowDNS Pubkey   : ${public_key}
Durasi Trial     : ${duration} Menit
Kadaluarsa       : ${expiration_datetime}

Payload:
${payload}

OpenVPN:
https://${domain}:81/allovpn.zip

Detail Akun:
https://${domain}:81/ssh-${user}.txt

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

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

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

        sed -i "/^### ${user} /d" "$DB_FILE"
        rm -f \
            "/etc/ssh/${user}" \
            "/etc/xray/log-createssh-${user}.log" \
            "${WEB_DIR}/ssh-${user}.txt"

        userdel -f "$user" >/dev/null 2>&1

        echo -e "${red}Gagal menjalankan timer trial.${reset}"
        exit 1
    fi
else
    nohup trial trialssh "$user" "$duration" \
        >/dev/null 2>&1 &

    trial_pid=$!

    if ! kill -0 "$trial_pid" >/dev/null 2>&1; then
        sed -i "/^### ${user} /d" "$DB_FILE"
        rm -f \
            "/etc/ssh/${user}" \
            "/etc/xray/log-createssh-${user}.log" \
            "${WEB_DIR}/ssh-${user}.txt"

        userdel -f "$user" >/dev/null 2>&1

        echo -e "${red}Gagal menjalankan timer trial.${reset}"
        exit 1
    fi
fi

clear

box_top
box_center "$BRAND" "$green"
box_center "TRIAL SSH / OVPN BERHASIL" "$bold_white"
box_middle
box_left "Username      : $user" "$white"
box_left "Password      : $password" "$white"
box_left "IP VPS        : $ip" "$white"
box_left "Host          : $domain" "$white"
box_left "SlowDNS Host  : $ns_domain" "$white"
box_left "Lokasi        : $city" "$white"
box_middle
box_left "OpenSSH       : 22, 80, 443" "$white"
box_left "Dropbear      : 109, 143, 443" "$white"
box_left "SSH WebSocket : 80, 8080" "$white"
box_left "SSH SSL WS    : 443" "$white"
box_left "SSL/TLS       : 443" "$white"
box_left "OpenVPN SSL   : 443" "$white"
box_left "OpenVPN TCP   : 1194" "$white"
box_left "OpenVPN UDP   : 2200" "$white"
box_left "UDP Custom    : 1-65535" "$white"
box_left "DNS           : 53, 443" "$white"
box_left "BadVPN UDP    : 7100, 7200, 7300" "$white"
box_middle
box_left "Public Key    : $public_key" "$white"
box_left "Durasi Trial  : $duration Menit" "$yellow"
box_left "Kadaluarsa    : $expiration_datetime" "$yellow"
box_bottom

echo ""

box_top
box_center "PAYLOAD WEBSOCKET" "$bold_white"
box_middle
box_left "$payload" "$green"
box_bottom

echo ""

box_top
box_center "DOWNLOAD OPENVPN" "$bold_white"
box_middle
box_left "https://${domain}:81/allovpn.zip" "$cyan"
box_bottom

echo ""

box_top
box_center "DETAIL AKUN" "$bold_white"
box_middle
box_left "https://${domain}:81/ssh-${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