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

cleanup() {
    rm -f \
        /tmp/ssh_login_user \
        /tmp/login-db-ssh.txt \
        /tmp/login-db-dropbear.txt \
        /tmp/login-db-pid-ssh.txt \
        /tmp/login-db-pid-dropbear.txt
}

trap cleanup EXIT

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

if [ -e "/var/log/auth.log" ]; then
    LOG_FILE="/var/log/auth.log"
elif [ -e "/var/log/secure" ]; then
    LOG_FILE="/var/log/secure"
else
    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "CEK LOGIN SSH" "$bold_white"
    box_middle
    box_center "FILE LOG TIDAK DITEMUKAN" "$red"
    box_middle
    box_left "Tidak ditemukan /var/log/auth.log atau /var/log/secure." "$yellow"
    box_bottom

    exit 1
fi

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

cleanup
touch /tmp/ssh_login_user

tampilkan_info_pengguna() {
    local file="$1"
    local user
    local user_count
    local ip_limit
    local total_ip_connect
    local user_ip_pid
    local line
    local ip
    local pid
    local i
    local found_user=0

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

    if [ ! -s "$file" ]; then
        box_top
        box_center "$BRAND" "$green"
        box_middle
        box_center "TIDAK ADA KONEKSI AKTIF" "$yellow"
        box_middle
        box_center "Belum ada pengguna SSH atau Dropbear yang terhubung." "$white"
        box_bottom
        return
    fi

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

        user_count=$(
            awk -v target="$user" '$2 == target {count++} END {print count+0}' "$file"
        )

        if [ "$user_count" -le 0 ]; then
            continue
        fi

        ip_limit=$(cat "/etc/ssh/${user}" 2>/dev/null)

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

        total_ip_connect=$(
            awk -v target="$user" '$2 == target {print $3}' "$file" |
                sort -u |
                grep -c .
        )

        if [ "$found_user" -eq 1 ]; then
            echo ""
        fi

        box_top
        box_center "DETAIL KONEKSI" "$red"
        box_middle
        box_left "Pengguna        : ${user}" "$white"

        if [ "$ip_limit" -eq 0 ]; then
            box_left "Batas IP        : Tanpa Batas" "$white"
        else
            box_left "Batas IP        : ${ip_limit}" "$white"
        fi

        box_left "Total IP Aktif  : ${total_ip_connect}" "$white"
        box_left "Total Sesi      : ${user_count}" "$white"
        box_middle
        box_left "DAFTAR IP / PID" "$bright_green"

        i=1

        user_ip_pid=$(
            awk -v target="$user" '$2 == target {print $3, $1}' "$file" |
                sort -u
        )

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

            ip=$(echo "$line" | awk '{print $1}')
            pid=$(echo "$line" | awk '{print $2}')

            box_left "${i}. ${ip} » PID: ${pid}" "$white"

            i=$((i + 1))
        done <<<"$user_ip_pid"

        box_bottom

        found_user=1
    done

    if [ "$found_user" -eq 0 ]; then
        box_top
        box_center "$BRAND" "$green"
        box_middle
        box_center "TIDAK ADA KONEKSI AKTIF" "$yellow"
        box_middle
        box_center "Tidak ada akun database yang sedang terhubung." "$white"
        box_bottom
    fi
}

tampilkan_info_ssh_dropbear() {
    local ssh_pid
    local ssh_user
    local ssh_ip
    local dropbear_pid
    local dropbear_user
    local dropbear_ip

    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "LOGIN AKUN SSH / DROPBEAR" "$bold_white"
    box_middle
    box_left "IP VPS        : $vps_ip" "$white"
    box_left "Akses Script  : $remaining_days Hari" "$yellow"
    box_bottom

    echo ""

    grep -i "sshd" "$LOG_FILE" 2>/dev/null |
        grep -i "Accepted password for" \
        >/tmp/login-db-ssh.txt

    grep -i "dropbear" "$LOG_FILE" 2>/dev/null |
        grep -i "Password auth succeeded" \
        >/tmp/login-db-dropbear.txt

    mapfile -t ssh_pids < <(
        pgrep sshd 2>/dev/null
    )

    mapfile -t dropbear_pids < <(
        pgrep dropbear 2>/dev/null
    )

    for ssh_pid in "${ssh_pids[@]}"; do
        [ -z "$ssh_pid" ] && continue

        if grep -q "sshd\[$ssh_pid\]" /tmp/login-db-ssh.txt 2>/dev/null; then
            grep "sshd\[$ssh_pid\]" \
                /tmp/login-db-ssh.txt \
                >/tmp/login-db-pid-ssh.txt

            ssh_user=$(
                grep -oP '(?<=for )\w+' \
                    /tmp/login-db-pid-ssh.txt |
                    tail -1
            )

            ssh_ip=$(
                grep -oP '(?<=from )\d+\.\d+\.\d+\.\d+' \
                    /tmp/login-db-pid-ssh.txt |
                    tail -1
            )

            if [ -n "$ssh_user" ] && [ -n "$ssh_ip" ]; then
                echo "$ssh_pid $ssh_user $ssh_ip" >>/tmp/ssh_login_user
            fi
        fi
    done

    for dropbear_pid in "${dropbear_pids[@]}"; do
        [ -z "$dropbear_pid" ] && continue

        if grep -q "dropbear\[$dropbear_pid\]" /tmp/login-db-dropbear.txt 2>/dev/null; then
            grep "dropbear\[$dropbear_pid\]" \
                /tmp/login-db-dropbear.txt \
                >/tmp/login-db-pid-dropbear.txt

            dropbear_user=$(
                grep -oP "(?<=for ')\w+(?=' from)" \
                    /tmp/login-db-pid-dropbear.txt |
                    tail -1 |
                    sed "s/'//g"
            )

            dropbear_ip=$(
                grep -oP '(?<=from )\d+\.\d+\.\d+\.\d+' \
                    /tmp/login-db-pid-dropbear.txt |
                    tail -1 |
                    cut -d ':' -f1
            )

            if [ -n "$dropbear_user" ] && [ -n "$dropbear_ip" ]; then
                echo "$dropbear_pid $dropbear_user $dropbear_ip" >>/tmp/ssh_login_user
            fi
        fi
    done

    if [ -s /tmp/ssh_login_user ]; then
        sort -u /tmp/ssh_login_user -o /tmp/ssh_login_user
    fi

    tampilkan_info_pengguna "/tmp/ssh_login_user"

    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
}

tampilkan_info_ssh_dropbear

exit 0