# !/bin/bash
# ████████╗░█████╗░██╗░░██╗░█████╗░██╗░░░██╗██████╗░███╗░░██╗
# ╚══██╔══╝██╔══██╗██║░██╔╝██╔══██╗██║░░░██║██╔══██╗████╗░██║
# ░░░██║░░░██║░░██║█████═╝░██║░░██║╚██╗░██╔╝██████╔╝██╔██╗██║
# ░░░██║░░░██║░░██║██╔═██╗░██║░░██║░╚████╔╝░██╔═══╝░██║╚████║
# ░░░██║░░░╚█████╔╝██║░╚██╗╚█████╔╝░░╚██╔╝░░██║░░░░░██║░╚███║
# ░░░╚═╝░░░░╚════╝░╚═╝░░╚═╝░╚════╝░░░░╚═╝░░░╚═╝░░░░░╚═╝░░╚══╝

SERVICES=("vmip")
EXPECTED_STATUS="Start vlip"

# Dapatkan waktu saat script dijalankan
START_TIME=$(date +"%Y-%m-%d %H:%M:%S")

echo "Cek status ${SERVICES[*]} sejak $START_TIME"
journalctl -u "${SERVICES[0]}" -f --since "$START_TIME" --no-pager | while read -r line; do
    if [[ "$line" == *"$EXPECTED_STATUS"* ]]; then
        echo "Log ${EXPECTED_STATUS} terdeteksi. Eksekusi vlip dimulai"

function send_log() {
DOMAIN_PART=$(cut -d '.' -f1 /etc/xray/domain | tr '[:lower:]' '[:upper:]')
FULL_DOMAIN=$(cat /etc/xray/domain)
IP_LIST=$(grep "$akun" /var/log/xray/access.log | grep "accepted" | awk -F "from " '{print $2}' | sed 's/tcp://g' | cut -d ':' -f1 | sort -u | awk -F '.' '!seen[$1"."$2]++' |  awk '{print NR". "$0}')

# Cek apakah DOMAIN mengandung "SG"
if [[ "$DOMAIN_PART" == *"SG"* ]]; then
    FLAG="🇸🇬"
else
    FLAG="🇮🇩"
fi

# Konfigurasi informasi Telegram
CHATID=$(grep -E "^#bot# " "/etc/bot/.bot.db" | cut -d ' ' -f 3)
KEY=$(grep -E "^#bot# " "/etc/bot/.bot.db" | cut -d ' ' -f 2)
TIMEOUT="10"
URL="https://api.telegram.org/bot$KEY/sendMessage"
TEXT="
──────────────────────
🚫 Notifikasi Multilogin VLESS
──────────────────────
<blockquote><code>SERVER $DOMAIN_PART $FLAG</code></blockquote>
<code>User  :</code> <code>$akun</code>
<code>Login :</code> <code>$jum3 IP</code>
<code>Limit :</code> <code>$((MAX / 2)) IP</code>
──────────────────────
$IP_LIST
────────────────────── 
Notif "$jumx"X Multilogin: 3X Autolock
────────────────────── "

# Kirim pesan ke Telegram
curl -s --max-time "$TIMEOUT" -d "chat_id=$CHATID&disable_web_page_preview=1&text=$TEXT&parse_mode=html" $URL >/dev/null
}

function send_logx() {
DOMAIN_PART=$(cut -d '.' -f1 /etc/xray/domain | tr '[:lower:]' '[:upper:]')
FULL_DOMAIN=$(cat /etc/xray/domain)
IP_LIST=$(grep "$akun" /var/log/xray/access.log | grep "accepted" | awk -F "from " '{print $2}' | sed 's/tcp://g' | cut -d ':' -f1 | sort -u | awk -F '.' '!seen[$1"."$2]++' |  awk '{print NR". "$0}')

# Cek apakah DOMAIN mengandung "SG"
if [[ "$DOMAIN_PART" == *"SG"* ]]; then
    FLAG="🇸🇬"
else
    FLAG="🇮🇩"
fi

# Konfigurasi informasi Telegram
CHATID=$(grep -E "^#bot# " "/etc/bot/.bot.db" | cut -d ' ' -f 3)
KEY=$(grep -E "^#bot# " "/etc/bot/.bot.db" | cut -d ' ' -f 2)
TIMEOUT="10"
URL="https://api.telegram.org/bot$KEY/sendMessage"
TEXT="
──────────────────────
🚫 Notifikasi Multilogin VLESS
──────────────────────
<blockquote><code>SERVER $DOMAIN_PART $FLAG</code></blockquote>
<code>User  :</code> <code>$akun</code>
<code>Login :</code> <code>$jum3 IP</code>
<code>Limit :</code> <code>$((MAX / 2)) IP</code>
──────────────────────
$IP_LIST
────────────────────── 
Notif 3X Multilogin: Lock 15 Menit
────────────────────── "

# Kirim pesan ke Telegram
curl -s --max-time "$TIMEOUT" -d "chat_id=$CHATID&disable_web_page_preview=1&text=$TEXT&parse_mode=html" $URL >/dev/null
}

function send_logxx() {
DOMAIN_PART=$(cut -d '.' -f1 /etc/xray/domain | tr '[:lower:]' '[:upper:]')
FULL_DOMAIN=$(cat /etc/xray/domain)
IP_LIST=$(grep "$akun" /var/log/xray/access.log | grep "accepted" | awk -F "from " '{print $2}' | sed 's/tcp://g' | cut -d ':' -f1 | sort -u | awk -F '.' '!seen[$1"."$2]++' |  awk '{print NR". "$0}')

# Cek apakah DOMAIN mengandung "SG"
if [[ "$DOMAIN_PART" == *"SG"* ]]; then
    FLAG="🇸🇬"
else
    FLAG="🇮🇩"
fi

# Konfigurasi informasi Telegram
CHATID=$(grep -E "^#bot# " "/etc/bot/.bot.db" | cut -d ' ' -f 3)
KEY=$(grep -E "^#bot# " "/etc/bot/.bot.db" | cut -d ' ' -f 2)
TIMEOUT="10"
URL="https://api.telegram.org/bot$KEY/sendMessage"
TEXT="
──────────────────────
🚫 Notifikasi Multilogin VLESS
──────────────────────
<blockquote><code>SERVER $DOMAIN_PART $FLAG</code></blockquote>
<code>User  :</code> <code>$akun</code>
<code>Login :</code> <code>$jum3 IP</code>
<code>Limit :</code> <code>$((MAX / 2)) IP</code>
──────────────────────
$IP_LIST
────────────────────── 
Notif 4X Multilogin: Locked!
────────────────────── "

# Kirim pesan ke Telegram
curl -s --max-time "$TIMEOUT" -d "chat_id=$CHATID&disable_web_page_preview=1&text=$TEXT&parse_mode=html" $URL >/dev/null
}

data=(`cat /etc/xray/config.json | grep '#&' | cut -d ' ' -f 2 | sort | uniq`)

# Loop through each user
echo "Memulai proses monitoring VLESS."
truncate -s 0 /var/log/xray/access.log
echo "Persiapan, sleep 30 detik!"
sleep 30

# Read log data once and process it
log_data=$(cat /var/log/xray/access.log | tail -n 500)
ip_data=($(echo "$log_data" | grep email | grep "accepted" | awk -F "from " '{print $2}' | sed 's/tcp://g' | sed 's/\[.*//g' | cut -d: -f1 | sort | uniq))
status=0

for akun in "${data[@]}"; do
    echo -n > /tmp/ipvlessx.txt
    for ip in "${ip_data[@]}"; do
        # Extract the first two segments of the IP
        ip_prefiks=$(echo "$ip" | cut -d "." -f1,2)

        # Check if this IP belongs to the current user (only need to search through the preloaded log data)
        jum=$(echo "$log_data" | grep -w "$akun" | grep -w "$ip_prefiks" | grep "accepted" | awk -F "from " '{print $2}' | sed 's/tcp://g' | cut -d ":" -f1 | cut -d "." -f1,2 | sort | uniq)
        if [[ "$jum" == "$ip_prefiks" ]]; then
            echo "$jum" >> /tmp/ipvlessx.txt
        fi
    done
    
    jum=$(cat /tmp/ipvlessx.txt)
    if [[ -n "$jum" ]]; then
        if [ -e "/etc/kyt/limit/vless/ip/${akun}" ]; then
            iplimit=$(cat /etc/kyt/limit/vless/ip/${akun})
            MAX=$((iplimit * 2))
        else
            MAX=2
            echo "2" > /etc/kyt/limit/vless/ip/${akun}
        fi

        if [ "$MAX" -eq 0 ]; then
            MAX=2
            echo "2" > /etc/kyt/limit/vless/ip/${akun}
        fi
        jum2=$(sort /tmp/ipvlessx.txt | uniq | wc -l)
        echo "Memproses User : [Login: $jum2, Limit: $((MAX / 2))] $akun"
        # Check if the number of logged-in IPs exceeds the limit
        if [ "$jum2" -gt "$MAX" ]; then
            exp=$(grep -w "^#& $akun" "/etc/xray/config.json" | cut -d ' ' -f 3 | sort | uniq)
            uuid=$(grep -w "^#& $akun $exp" -A 1 "/etc/xray/config.json" | awk -F'"' '/"id":/ {print $4}' | sort | uniq)

            echo "Mulog terdeteksi, memulai proses monitoring ke-2 VLESS."
            truncate -s 0 /var/log/xray/access.log
            echo "Persiapan, sleep 60 detik!"
            sleep 60
            jum3=$(grep "$akun" /var/log/xray/access.log | grep "accepted" | awk -F "from " '{print $2}' | sed 's/tcp://g' | cut -d ':' -f1 | sort -u | awk -F '.' '!seen[$1"."$2]++' | wc -l)
            if [ "$jum3" -gt "$MAX" ]; then
            echo "Mulog $akun valid, Login [$jum3 IP]"
            if [[ -z $exp || -z $uuid ]]; then
                continue  # Skip if exp or uuid is empty
            fi

            echo "$akun" >> /tmp/lockipxray.txt
        
            if [[ $(grep -c "$akun" /tmp/lockipxray.txt) -gt 3 ]]; then
exp=$(grep -wE "^#& $akun" "/etc/xray/config.json" | cut -d ' ' -f 3 | sort | uniq)
uuid=$(grep -w "^#& $akun $exp" -A 1 "/etc/xray/config.json" | awk -F'"' '/"id":/ {print $4}' | sort | uniq)
uuid2=$(grep -w "^#& $akun $exp" -A 1 "/etc/xray/config.json" | awk -F'"' '/"id":/ {print $4}' | sed 's/.*\(LOCKED\)/\1/' | sort | uniq)
uuid3="xrayvless$(LC_CTYPE=C tr -dc 'a-zA-Z0-9' < /dev/urandom | fold -w 15 | head -n 1)LOCKED"

if [[ "$uuid2" == "LOCKED" ]]; then
    echo -e "Account $akun has been locked, melewati proses."
    continue
fi

status=1

echo "Locked user $akun 4X Multilogin"
DATADB=$(cat /etc/vless/.vless.db | grep "^###" | grep -w "${akun}" | awk '{print $2}')
if [[ "${DATADB}" != '' ]]; then
sed -i "/^### $akun/d" /etc/vless/.vless.db
fi
echo "### ${akun} ${exp} ${uuid}" >> /etc/vless/.vless.db
sed -i "/^#& $akun $exp/,/^},{/d" /etc/xray/config.json
sed -i '/#vless$/a\#& '"$akun $exp"'\
},{"id": "'""$uuid3""'","email" : "'""$akun""'"' /etc/xray/config.json
sed -i '/#vlessgrpc$/a\#& '"$akun $exp"'\
},{"id": "'""$uuid3""'","email" : "'""$akun""'"' /etc/xray/config.json
send_logxx
sed -i "/$akun/d" /tmp/lockipxray.txt
truncate -s 0 /var/log/xray/access.log
                continue
            fi
            
            if [[ $(grep -c "$akun" /tmp/lockipxray.txt) -gt 2 ]]; then
exp=$(grep -wE "^#& $akun" "/etc/xray/config.json" | cut -d ' ' -f 3 | sort | uniq)
uuid=$(grep -w "^#& $akun $exp" -A 1 "/etc/xray/config.json" | awk -F'"' '/"id":/ {print $4}' | sort | uniq)
uuid2=$(grep -w "^#& $akun $exp" -A 1 "/etc/xray/config.json" | awk -F'"' '/"id":/ {print $4}' | sed 's/.*\(LOCKED\)/\1/' | sort | uniq)
uuid3="xrayvless$(LC_CTYPE=C tr -dc 'a-zA-Z0-9' < /dev/urandom | fold -w 15 | head -n 1)LOCKED"

if [[ "$uuid2" == "LOCKED" ]]; then
    echo -e "Account $akun has been locked, melewati proses."
    continue
fi

status=1

echo "Unlock user $akun dalam 15 menit."
echo "unlocklimitip vless $akun $exp $uuid" | at now + 15 minutes &> /dev/null
DATADB=$(cat /etc/vless/.vless.db | grep "^###" | grep -w "${akun}" | awk '{print $2}')
if [[ "${DATADB}" != '' ]]; then
sed -i "/^### $akun/d" /etc/vless/.vless.db
fi
echo "### ${akun} ${exp} ${uuid}" >> /etc/vless/.vless.db
sed -i "/^#& $akun $exp/,/^},{/d" /etc/xray/config.json
sed -i '/#vless$/a\#& '"$akun $exp"'\
},{"id": "'""$uuid3""'","email" : "'""$akun""'"' /etc/xray/config.json
sed -i '/#vlessgrpc$/a\#& '"$akun $exp"'\
},{"id": "'""$uuid3""'","email" : "'""$akun""'"' /etc/xray/config.json
send_logx
truncate -s 0 /var/log/xray/access.log
                continue
            fi

echo "User $akun melebihi batas login, send notif!"
jumx=$(grep -c "$akun" /tmp/lockipxray.txt)
send_log
truncate -s 0 /var/log/xray/access.log
        else
        echo "Mulog $akun tidak valid, Login [$jum3 IP]"
        fi
      fi
    fi 
    rm -rf /tmp/ipvlessx.txt
    sleep 3
done

if [[ "$status" -eq 1 ]]; then
    echo "Terjadi pelanggaran multilogin, restart layanan xray."
    systemctl restart xray > /dev/null 2>&1
fi
rm -rf /tmp/ipvlessx.txt
echo "Start vtrip"
sleep 10
echo "Siklus monitoring selesai. sleep 120 detik!"
sleep 120

        break
    fi
done