#!/bin/bash

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

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

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
}

count_accounts() {
    local protocol="$1"
    local db_file="/etc/xray/${protocol}/.${protocol}.db"

    mkdir -p "/etc/xray/${protocol}"

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

    grep -c '^### ' "$db_file" 2>/dev/null || echo "0"
}

count_ssh_accounts() {
    mkdir -p /etc/ssh

    if [ ! -f "/etc/ssh/.ssh.db" ]; then
        touch /etc/ssh/.ssh.db
    fi

    grep -c '^### ' /etc/ssh/.ssh.db 2>/dev/null || echo "0"
}

get_system_name() {
    local system_name

    system_name=$(
        awk -F= '/^PRETTY_NAME=/{gsub(/"/,"",$2); print $2}' \
            /etc/os-release 2>/dev/null
    )

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

    printf '%s' "$system_name"
}

get_ram_info() {
    local total_ram_kb
    local available_ram_kb
    local used_ram_kb
    local total_ram_gb
    local used_ram_gb

    total_ram_kb=$(
        awk '/MemTotal/ {print $2}' /proc/meminfo 2>/dev/null
    )

    available_ram_kb=$(
        awk '/MemAvailable/ {print $2}' /proc/meminfo 2>/dev/null
    )

    if [ -z "$total_ram_kb" ] || [ -z "$available_ram_kb" ]; then
        printf 'Tidak diketahui'
        return
    fi

    used_ram_kb=$((total_ram_kb - available_ram_kb))

    total_ram_gb=$(
        awk -v value="$total_ram_kb" \
            'BEGIN {printf "%.2f", value / 1024 / 1024}'
    )

    used_ram_gb=$(
        awk -v value="$used_ram_kb" \
            'BEGIN {printf "%.2f", value / 1024 / 1024}'
    )

    printf '%s GB Total / %s GB Terpakai' \
        "$total_ram_gb" \
        "$used_ram_gb"
}

get_uptime() {
    local uptime_text

    uptime_text=$(uptime -p 2>/dev/null | sed 's/^up //')

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

    printf '%s' "$uptime_text"
}

get_cpu_core() {
    local cpu_core

    cpu_core=$(nproc 2>/dev/null)

    if ! [[ "$cpu_core" =~ ^[0-9]+$ ]]; then
        cpu_core=$(
            grep -c '^processor' /proc/cpuinfo 2>/dev/null
        )
    fi

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

    printf '%s' "$cpu_core"
}

get_file_value() {
    local file="$1"
    local fallback="$2"
    local value

    value=$(cat "$file" 2>/dev/null)

    if [ -z "$value" ]; then
        value="$fallback"
    fi

    printf '%s' "$value"
}

show_account_summary() {
    box_top
    box_center "RINGKASAN AKUN" "$bold_white"
    box_middle
    box_left "SSH / OVPN     : $ssh Akun" "$white"
    box_left "VMess          : $vm Akun" "$white"
    box_left "VLESS          : $vl Akun" "$white"
    box_left "Trojan         : $tr Akun" "$white"
    box_left "Shadowsocks    : $ss Akun" "$white"
    box_bottom
}

show_main_options() {
    box_top
    box_center "MENU UTAMA" "$bold_white"
    box_middle
    box_left "1. SSH / OVPN Manager" "$green"
    box_left "2. VMess Manager" "$green"
    box_left "3. VLESS Manager" "$green"
    box_left "4. Trojan Manager" "$green"
    box_left "5. Shadowsocks Manager" "$green"
    box_left "6. Pengaturan Lainnya" "$green"
    box_left "X. Keluar" "$red"
    box_bottom
}

display_menu() {
    local system_name
    local ram_info
    local uptime_info
    local cpu_core
    local isp
    local city
    local domain
    local nameserver
    local script_key
    local choice

    vm=$(count_accounts "vmess")
    vl=$(count_accounts "vless")
    tr=$(count_accounts "trojan")
    ss=$(count_accounts "shadowsocks")
    ssh=$(count_ssh_accounts)

    system_name=$(get_system_name)
    ram_info=$(get_ram_info)
    uptime_info=$(get_uptime)
    cpu_core=$(get_cpu_core)
    isp=$(get_file_value "/etc/xray/isp" "Tidak diketahui")
    city=$(get_file_value "/etc/xray/city" "Tidak diketahui")
    domain=$(get_file_value "/etc/xray/domain" "Belum diatur")
    nameserver=$(get_file_value "/etc/xray/dns" "Belum diatur")
    script_key=$(get_file_value "/root/.key" "Tidak tersedia")

    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "AUTOSCRIPT PREMIUM" "$bold_white"
    box_middle
    box_left "Sistem          : $system_name" "$white"
    box_left "RAM             : $ram_info" "$white"
    box_left "Uptime          : $uptime_info" "$white"
    box_left "CPU Core        : $cpu_core" "$white"
    box_left "ISP             : $isp" "$white"
    box_left "Kota            : $city" "$white"
    box_left "IP VPS          : $vps_ip" "$white"
    box_left "Domain          : $domain" "$white"
    box_left "Nameserver      : $nameserver" "$white"
    box_bottom

    echo ""

    show_account_summary

    echo ""

    show_main_options

    echo ""

    box_top
    box_center "INFORMASI SCRIPT" "$bold_white"
    box_middle
    box_left "Script Key      : $script_key" "$white"
    box_left "Masa Aktif      : $remaining_days Hari" "$yellow"
    box_left "Kadaluarsa      : $data_acc" "$yellow"
    box_left "Versi Script    : $VERSION" "$green"
    box_bottom

    echo ""

    read -rp "Pilih menu [1-6] atau X untuk keluar : " choice

    case "$choice" in
        1)
            if command -v menussh >/dev/null 2>&1; then
                menussh
            else
                echo -e "${red}Menu SSH / OVPN tidak ditemukan.${reset}"
                sleep 2
                display_menu
            fi
            ;;
        2)
            if command -v menuvmess >/dev/null 2>&1; then
                menuvmess
            else
                echo -e "${red}Menu VMess tidak ditemukan.${reset}"
                sleep 2
                display_menu
            fi
            ;;
        3)
            if command -v menuvless >/dev/null 2>&1; then
                menuvless
            else
                echo -e "${red}Menu VLESS tidak ditemukan.${reset}"
                sleep 2
                display_menu
            fi
            ;;
        4)
            if command -v menutrojan >/dev/null 2>&1; then
                menutrojan
            else
                echo -e "${red}Menu Trojan tidak ditemukan.${reset}"
                sleep 2
                display_menu
            fi
            ;;
        5)
            if command -v menushadowsocks >/dev/null 2>&1; then
                menushadowsocks
            else
                echo -e "${red}Menu Shadowsocks tidak ditemukan.${reset}"
                sleep 2
                display_menu
            fi
            ;;
        6)
            if command -v menusetting >/dev/null 2>&1; then
                menusetting
            else
                echo -e "${red}Menu pengaturan tidak ditemukan.${reset}"
                sleep 2
                display_menu
            fi
            ;;
        x|X)
            clear

            box_top
            box_center "$BRAND" "$green"
            box_center "TERIMA KASIH" "$bold_white"
            box_middle
            box_center "Terima kasih telah menggunakan layanan kami." "$white"
            box_middle
            box_left "WhatsApp ~ $WHATSAPP" "$green"
            box_left "Telegram ~ $TELEGRAM" "$cyan"
            box_bottom

            exit 0
            ;;
        *)
            echo ""
            echo -e "${red}Pilihan tidak valid. Silakan coba kembali.${reset}"
            sleep 2
            display_menu
            ;;
    esac
}

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))

display_menu