#!/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"
cyan="\e[38;5;51m"
white="\e[97m"
orange="\e[38;5;130m"
bold_white="\e[1;37m"
bright_green="\e[92;1m"
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 "$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
}

convert_size() {
    local bytes="${1:-0}"

    if ! [[ "$bytes" =~ ^[0-9]+$ ]]; then
        bytes=0
    fi

    if [ "$bytes" -lt 1024 ]; then
        echo "${bytes} B"
    elif [ "$bytes" -lt 1048576 ]; then
        echo "$(((bytes + 1023) / 1024)) KB"
    elif [ "$bytes" -lt 1073741824 ]; then
        echo "$(((bytes + 1048575) / 1048576)) MB"
    else
        echo "$(((bytes + 1073741823) / 1073741824)) GB"
    fi
}

get_asn() {
    local ip_address="$1"
    local asn

    if [ "$ip_address" = "127.0.0.1" ]; then
        echo "Localhost"
        return
    fi

    if ! command -v whois >/dev/null 2>&1; then
        echo "Informasi ISP tidak tersedia"
        return
    fi

    asn=$(
        whois "$ip_address" 2>/dev/null |
            grep -Ei '^(descr|org-name|orgname|netname|organization):' |
            head -1 |
            cut -d ':' -f2- |
            xargs
    )

    if [ -z "$asn" ]; then
        asn="ISP tidak teridentifikasi"
    fi

    echo "$asn"
}

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_timestamp=$(date +%s)

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

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

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

my_ip="$vps_ip"

server_data=$(
    curl -s -I https://google.com 2>/dev/null |
        grep -i '^date:' |
        cut -d' ' -f2-
)

if [ -n "$server_data" ]; then
    current_date=$(date +"%Y-%m-%d" -d "$server_data" 2>/dev/null)
fi

if [ -z "${current_date:-}" ]; then
    current_date=$(date +"%Y-%m-%d")
fi

current_time=$(date +%T)

check_trojan() {
    local db_file="/etc/xray/trojan/.trojan.db"
    local access_log="/var/log/xray/access.log"
    local rotation_file="/tmp/rotation_trojan"
    local user
    local line
    local access_time
    local ip_address
    local current_time_seconds
    local access_time_seconds
    local time_difference
    local usage
    local readable_usage
    local limit
    local readable_limit
    local connection_count
    local ip_limit
    local asn
    local previous_user=""

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

        box_top
        box_center "$BRAND" "$green"
        box_center "CEK LOGIN TROJAN" "$bold_white"
        box_middle
        box_center "DATABASE TIDAK DITEMUKAN" "$red"
        box_middle
        box_left "$db_file" "$yellow"
        box_bottom

        exit 1
    fi

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

        box_top
        box_center "$BRAND" "$green"
        box_center "CEK LOGIN TROJAN" "$bold_white"
        box_middle
        box_center "LOG XRAY TIDAK DITEMUKAN" "$red"
        box_middle
        box_left "$access_log" "$yellow"
        box_bottom

        exit 1
    fi

    echo ""
    echo -ne "${yellow}Memeriksa Akun Trojan${reset}"

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

    echo -ne "\r${green}Pemeriksaan akun Trojan berhasil!${reset}     \n"

    sleep 1
    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "LOGIN AKUN TROJAN" "$bold_white"
    box_middle
    box_left "IP VPS          : $my_ip" "$white"
    box_left "Tanggal         : $current_date" "$white"
    box_left "Waktu           : $current_time" "$white"
    box_left "Akses Script    : $remaining_days Hari" "$yellow"
    box_bottom

    echo ""

    mapfile -t user_list < <(
        grep '^### ' "$db_file" 2>/dev/null |
            awk '{print $2}' |
            sort -u
    )

    : >"$rotation_file"

    declare -A user_ips
    declare -A last_access_time
    declare -A log_count

    for user in "${user_list[@]}"; do
        [ -z "$user" ] && continue

        log_count["$user"]=$(
            grep -w "email: ${user}" "$access_log" 2>/dev/null |
                grep -v "127.0.0.1" |
                wc -l
        )

        while IFS= read -r line; do
            [ -z "$line" ] && continue

            read -r _ access_time ip_address _ <<<"$line"

            if [[ "$ip_address" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+(:[0-9]+)?$ ]]; then
                ip_address=${ip_address%%:*}

                access_time_seconds=$(date -d "$access_time" +%s 2>/dev/null)

                if [ -z "$access_time_seconds" ]; then
                    continue
                fi

                current_time_seconds=$(date +%s)
                time_difference=$((current_time_seconds - access_time_seconds))

                if [ "$time_difference" -ge 0 ] &&
                   [ "$time_difference" -lt 60 ]; then

                    if [ -n "${user_ips[$ip_address]:-}" ] &&
                       [ "${user_ips[$ip_address]}" != "$user" ]; then
                        continue
                    fi

                    user_ips["$ip_address"]="$user"
                    last_access_time["${user}:${ip_address}"]="$access_time"
                fi
            fi
        done < <(
            tail -n 300 "$access_log" |
                grep -w "email: ${user}" |
                grep -v "127.0.0.1"
        )
    done

    for user in "${user_list[@]}"; do
        for ip_address in "${!user_ips[@]}"; do
            if [ "${user_ips[$ip_address]}" = "$user" ]; then
                access_time="${last_access_time["${user}:${ip_address}"]}"

                echo "${user} ${ip_address} ${access_time}"
            fi
        done
    done |
        sort -k1,1 -k3,3r \
            >"$rotation_file"

    if [ ! -s "$rotation_file" ]; then
        box_top
        box_center "$BRAND" "$green"
        box_middle
        box_center "TIDAK ADA KONEKSI AKTIF" "$yellow"
        box_middle
        box_center "Belum ada pengguna Trojan yang terhubung." "$white"
        box_bottom

        rm -f "$rotation_file"
        exit 0
    fi

    while IFS= read -r line; do
        [ -z "$line" ] && continue

        read -r user ip_address access_time <<<"$line"

        access_time_seconds=$(date -d "$access_time" +%s 2>/dev/null)

        if [ -z "$access_time_seconds" ]; then
            continue
        fi

        current_time_seconds=$(date +%s)
        time_difference=$((current_time_seconds - access_time_seconds))

        if [ "$time_difference" -lt 0 ] ||
           [ "$time_difference" -ge 60 ]; then
            continue
        fi

        if [ "$user" != "$previous_user" ]; then
            if [ -n "$previous_user" ]; then
                box_bottom
                echo ""
            fi

            usage_file="/etc/xray/trojan/usage/${user}"
            quota_file="/etc/xray/trojan/${user}"
            ip_file="/etc/xray/trojan/${user}IP"

            if [ -f "$usage_file" ]; then
                usage=$(cat "$usage_file" 2>/dev/null)
            else
                usage=0
            fi

            if [ -f "$quota_file" ]; then
                limit=$(cat "$quota_file" 2>/dev/null)
            else
                limit=0
            fi

            if [ -f "$ip_file" ]; then
                ip_limit=$(cat "$ip_file" 2>/dev/null)
            else
                ip_limit=0
            fi

            usage=${usage:-0}
            limit=${limit:-0}
            ip_limit=${ip_limit:-0}

            readable_usage=$(convert_size "$usage")

            if [ "$limit" = "0" ]; then
                readable_limit="Tanpa Batas"
            else
                readable_limit=$(convert_size "$limit")
            fi

            connection_count=$(
                awk -v target="$user" '$1 == target {print $2}' "$rotation_file" |
                    sort -u |
                    wc -l
            )

            box_top
            box_center "DETAIL KONEKSI" "$red"
            box_middle
            box_left "Pengguna        : $user" "$white"
            box_left "Pemakaian       : $readable_usage" "$white"
            box_left "Kuota           : $readable_limit" "$white"

            if [ "$ip_limit" = "0" ]; then
                box_left "Batas IP        : Tanpa Batas" "$white"
            else
                box_left "Batas IP        : $ip_limit" "$white"
            fi

            box_left "Jumlah IP       : $connection_count" "$white"
            box_left "Jumlah Log      : ${log_count[$user]:-0}" "$white"
            box_middle
            box_left "DAFTAR IP" "$bright_green"

            previous_user="$user"
        fi

        asn=$(get_asn "$ip_address")

        box_left "${ip_address} » ${asn}" "$white"
    done <"$rotation_file"

    if [ -n "$previous_user" ]; then
        box_bottom
    fi

    echo ""

    box_top
    box_center "$BRAND" "$green"
    box_center "PEMERIKSAAN SELESAI" "$bold_white"
    box_middle
    box_left "WhatsApp ~ $WHATSAPP" "$green"
    box_left "Telegram ~ $TELEGRAM" "$cyan"
    box_bottom

    rm -f "$rotation_file"
}

check_trojan