#!/bin/bash

# ==========================================
#  HOKAGE LEGEND - MOBILE WIDE + LOADING
#  Feat: Spinner Animation during scan
# ==========================================

# --- 1. CONFIG ---
USAGE_DB="/etc/ssh/usage_db"

# Warna
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m'
BOLD='\033[1m'

# --- 2. HEADER TAMPILAN ---
clear
echo -e ""
echo -e "${YELLOW}╔══════════════════════════════════════════════════════╗${NC}"
echo -e "${YELLOW}║      ⚡ HOKAGE PREMIUM MOBILE MONITOR ⚡             ║${NC}"
echo -e "${YELLOW}╚══════════════════════════════════════════════════════╝${NC}"
echo -e ""

# --- 3. ANIMASI LOADING (BACKGROUND PROCESS) ---
# Fungsi Spinner
start_spinner() {
    local delay=0.1
    local spinstr='|/-\'
    while true; do
        local temp=${spinstr#?}
        printf " \r  ${CYAN}⏳ Mohon tunggu, sedang memindai user... [%c]${NC}" "$spinstr"
        local spinstr=$temp${spinstr%"$temp"}
        sleep $delay
    done
}

# Jalankan Spinner di Background
start_spinner &
SPIN_PID=$!

# Trap agar spinner mati jika user tekan Ctrl+C
trap "kill $SPIN_PID 2>/dev/null; exit" SIGINT

# --- 4. FASE SCANNING (BERAT) ---
# (Spinner berputar saat proses ini berjalan)

declare -A on_user      
declare -A on_type
declare -A on_total
declare -A on_session

# Pre-load log data (500 baris terakhir)
log_data=$(tail -n 500 /var/log/auth.log 2>/dev/null)

# >>>> SCAN PORT LOCALHOST <<<<
active_ports=$(ss -tn state established | grep "127.0.0.1" | awk '{print $4,$5}' | tr ' ' '\n' | cut -d: -f2 | grep -vE "^80$|^443$|^22$" | sort -u)

for r_port in $active_ports; do
    pid=$(lsof -t -i :$r_port 2>/dev/null | tail -n 1)
    
    if [[ -n "$pid" ]]; then
        user=$(ps -p "$pid" -o user= | tr -d ' ')
        
        if [[ "$user" == "root" || -z "$user" ]]; then
             user=$(echo "$log_data" | grep -E "\[$pid\]|dropbear\[$pid\]" | grep "auth succeeded" | tail -n 1 | awk '{print $10}' | tr -d "'")
        fi
        
        if [[ -n "$user" && "$user" != "root" && "$user" != "haproxy" && "$user" != "www-data" ]]; then
            on_user["$user"]="ONLINE"
            on_type["$user"]="SSH-WS" 
            
            # AMBIL SESI
            tx_raw=$(ss -ti "sport = :$r_port or dport = :$r_port" | grep "bytes_sent" | grep -oP "bytes_sent:[0-9]+" | cut -d: -f2 | head -n 1)
            [[ -z "$tx_raw" ]] && tx_raw=0
            session_h=$(numfmt --to=iec-i --suffix=B --format="%.2f" "$tx_raw" 2>/dev/null)
            on_session["$user"]=$session_h

            # AMBIL TOTAL
            if [[ -f "$USAGE_DB/$user.total" ]]; then db_bytes=$(cat "$USAGE_DB/$user.total");
            elif [[ -f "$USAGE_DB/$user" ]]; then db_bytes=$(cat "$USAGE_DB/$user");
            else db_bytes=0; fi
            
            total_bytes=$((db_bytes + tx_raw))
            total_h=$(numfmt --to=iec-i --suffix=B --format="%.2f" "$total_bytes" 2>/dev/null)
            on_total["$user"]=$total_h
        fi
    fi
done

# >>>> SCAN OPENSSH STANDAR <<<<
ps_ssh=$(ps -ef | grep "sshd: " | grep -v grep | grep -v "priv")
while read -r line; do
    user_ssh=$(echo "$line" | grep -oP "sshd: \K[a-zA-Z0-9_-]+" | head -1)
    if [[ -n "$user_ssh" && -z "${on_user[$user_ssh]}" ]]; then
         if id "$user_ssh" >/dev/null 2>&1; then
             on_user["$user_ssh"]="ONLINE"
             on_type["$user_ssh"]="OpenSSH"
             on_session["$user_ssh"]="0.00B"
             
             if [[ -f "$USAGE_DB/$user_ssh.total" ]]; then
                val=$(cat "$USAGE_DB/$user_ssh.total")
                on_total["$user_ssh"]=$(numfmt --to=iec-i --suffix=B --format="%.2f" "$val")
             else
                on_total["$user_ssh"]="0.00B"
             fi
         fi
    fi
done <<< "$ps_ssh"

# --- 5. PERSIAPAN DATA (LOOPING USER) ---
BUFFER_ONLINE=""
BUFFER_OFFLINE=""
total_ssh=0; total_online=0; total_offline=0

while IFS=: read -r username _ uid _ _ _ shell; do
    if [[ "$shell" != "/bin/false" && "$shell" != "/usr/sbin/nologin" && "$shell" != "/bin/bash" ]]; then continue; fi
    if [[ "$uid" -lt 1000 ]]; then continue; fi
    if [[ "$username" == "nobody" ]]; then continue; fi

    ((total_ssh++))
    
    if [[ "${on_user[$username]}" == "ONLINE" ]]; then
        # === USER ONLINE ===
        ((total_online++))
        
        sess_data="${on_session[$username]}"
        tot_data="${on_total[$username]}"
        tipe="${on_type[$username]}"
        sts_dot="${GREEN}●${NC}"
        
        if [[ "$tipe" == "SSH-WS" ]]; then color_type="${PURPLE}"; else color_type="${BLUE}"; fi
        
        # Format Lebar
        printf -v row " ${sts_dot} 👤 ${GREEN}%-12s${NC} ${BOLD}⚡${NC} (${color_type}%s${NC})\n       └─ 📥 Sesi: %-9s  📊 Total: %s\n\n" "$username" "$tipe" "$sess_data" "$tot_data"
        BUFFER_ONLINE+="$row"

    else
        # === USER OFFLINE ===
        ((total_offline++))
        sts_dot="${RED}●${NC}"
        
        if [[ -f "$USAGE_DB/$username.total" ]]; then
             raw_db=$(cat "$USAGE_DB/$username.total")
             tot_data=$(numfmt --to=iec-i --suffix=B --format="%.2f" "$raw_db" 2>/dev/null)
        elif [[ -f "$USAGE_DB/$username" ]]; then
             raw_db=$(cat "$USAGE_DB/$username")
             tot_data=$(numfmt --to=iec-i --suffix=B --format="%.2f" "$raw_db" 2>/dev/null)
        else
             tot_data="0.00B"
        fi

        # Format Offline
        printf -v row " ${sts_dot} 👤 ${NC}%-12s${NC} (${RED}Off${NC})\n       └─ 📥 Sesi: -          📊 Total: %s\n" "$username" "$tot_data"
        BUFFER_OFFLINE+="$row"
    fi

done < <(cat /etc/passwd)

# --- 6. STOP LOADING & CETAK HASIL ---
# Matikan Spinner dan Bersihkan Baris Loading
kill "$SPIN_PID" 2>/dev/null
wait "$SPIN_PID" 2>/dev/null
echo -ne "\r\033[K" # Hapus baris loading

# Separator
SEP_LINE="${GREEN}──────────────────────────────────────────────────────${NC}"

echo -e "${GREEN}┌── [ USER ONLINE ]${NC} $SEP_LINE"
if [[ -z "$BUFFER_ONLINE" ]]; then
    echo -e " │ ${YELLOW}(Tidak ada user online)${NC}"
else
    echo -n "$BUFFER_ONLINE"
fi

echo -e "${RED}┌── [ USER OFFLINE ]${NC} ${RED}─────────────────────────────────────${NC}"
echo -n "$BUFFER_OFFLINE"
echo -e ""

# --- 7. FOOTER ---
echo -e "${CYAN}══════════════════════════════════════════════════════${NC}"
tgl=$(date +'%H:%M')
echo -e " Total: $total_ssh  | ${GREEN}ON: $total_online${NC} | ${RED}OFF: $total_offline${NC} | Jam: $tgl"
echo -e ""