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

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
}

read_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"
}

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"
}

service_status_text() {
    local service="$1"

    if systemctl is-active --quiet "$service" 2>/dev/null; then
        printf '%bAKTIF%b' "$green" "$reset"
    else
        printf '%bNONAKTIF%b' "$red" "$reset"
    fi
}

get_system_name() {
    local value

    value=$(
        . /etc/os-release 2>/dev/null
        printf '%s' "${PRETTY_NAME:-}"
    )

    if [ -z "$value" ]; then
        value=$(uname -srm 2>/dev/null)
    fi

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

    printf '%s' "$value"
}

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 ! [[ "$total_ram_kb" =~ ^[0-9]+$ ]] ||
       ! [[ "$available_ram_kb" =~ ^[0-9]+$ ]]; then

        echo "Tidak diketahui"
        return
    fi

    used_ram_kb=$((total_ram_kb - available_ram_kb))

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

    printf '%s GB / %s GB' "$used_ram_gb" "$total_ram_gb"
}

get_uptime() {
    local uptime_text

    uptime_text=$(uptime -p 2>/dev/null)
    uptime_text=${uptime_text#up }

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

    printf '%s' "$uptime_text"
}

get_cpu_core() {
    local cores

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

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

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

    printf '%s' "$cores"
}

get_public_ip() {
    local ip

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

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

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

    printf '%s' "$ip"
}

display_dashboard() {
    local system_name
    local ram_info
    local uptime_info
    local cpu_core
    local isp
    local city
    local domain
    local nameserver
    local script_key
    local vm
    local vl
    local tr
    local ss
    local ssh

    system_name=$(get_system_name)
    ram_info=$(get_ram_info)
    uptime_info=$(get_uptime)
    cpu_core=$(get_cpu_core)

    isp=$(read_file_value "/etc/xray/isp" "Tidak diketahui")
    city=$(read_file_value "/etc/xray/city" "Tidak diketahui")
    domain=$(read_file_value "/etc/xray/domain" "Belum diatur")
    nameserver=$(read_file_value "/etc/xray/dns" "Belum diatur")
    script_key=$(read_file_value "/root/.key" "Tidak tersedia")

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

    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_middle
    box_center "INFORMASI AKUN" "$bold_white"
    box_middle
    box_left "SSH / OVPN  : $ssh Akun" "$green"
    box_left "VMess       : $vm Akun" "$green"
    box_left "VLESS       : $vl Akun" "$green"
    box_left "Trojan      : $tr Akun" "$green"
    box_left "Shadowsocks : $ss Akun" "$green"
    box_middle
    box_center "STATUS SERVICE" "$bold_white"
    box_middle
    box_left "VMess       : $(service_status_text "vmess@config")" "$white"
    box_left "VLESS       : $(service_status_text "vless@config")" "$white"
    box_left "Trojan      : $(service_status_text "trojan@config")" "$white"
    box_left "Shadowsocks : $(service_status_text "shadowsocks@config")" "$white"
    box_left "HAProxy     : $(service_status_text "haproxy")" "$white"
    box_left "SSH         : $(service_status_text "ssh")" "$white"
    box_middle
    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      : $VERSION" "$green"
    box_middle
    box_left "WhatsApp ~ $WHATSAPP" "$green"
    box_left "Telegram ~ $TELEGRAM" "$cyan"
    box_bottom

    echo ""
    echo -e "Ketik ${green}menu${reset} untuk membuka menu utama."
}

vps_ip=$(get_public_ip)

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

case "${1:-}" in
    dashboard)
        display_dashboard
        ;;
    *)
        echo "Perintah tidak dikenal. Gunakan: rs dashboard"
        exit 1
        ;;
esac