/**
 * Network Packet & Connection Sniffer
 * Menangkap SEMUA koneksi & packet dari mesin 192.168.0.50 di semua port
 */
require('dotenv').config({ path: require('path').resolve(__dirname, '../.env') });
const net   = require('net');
const dgram = require('dgram');
const http  = require('http');

const TARGET_IP = process.env.FINGERSPOT_DEVICE_IP || '192.168.0.50';
const PORTS_TO_LISTEN = [8088, 8080, 8000, 3000, 80, 4370, 5005, 7788];

console.log('=======================================================');
console.log(` SNIFFER AKTIF — MENUNGGU SIGNAL DARI ${TARGET_IP}`);
console.log('=======================================================');

// 1. Buat HTTP Listeners di semua port candidate
PORTS_TO_LISTEN.forEach(port => {
    try {
        const server = http.createServer((req, res) => {
            const remoteIp = req.socket.remoteAddress?.replace('::ffff:', '');
            console.log(`\n🎉 [HTTP INCOMING] Port ${port} menerima ${req.method} ${req.url} dari IP: ${remoteIp}`);
            let body = '';
            req.on('data', chunk => body += chunk.toString());
            req.on('end', () => {
                console.log(`   Headers:`, req.headers);
                console.log(`   Body: ${body.substring(0, 300)}`);
            });
            res.writeHead(200, { 'Content-Type': 'text/plain' });
            res.end('OK');
        });

        server.listen(port, '0.0.0.0', () => {
            console.log(`  ☑ HTTP Server listening on port ${port}`);
        });
        server.on('error', () => {});
    } catch (_) {}
});

// 2. Buat UDP Listeners di port 4370 & 8088
[4370, 8088, 8080, 5005].forEach(port => {
    try {
        const udp = dgram.createSocket('udp4');
        udp.on('message', (msg, rinfo) => {
            console.log(`\n🎉 [UDP INCOMING] Port ${port} menerima ${msg.length} bytes dari ${rinfo.address}:${rinfo.port}`);
            console.log(`   Hex: ${msg.toString('hex').toUpperCase()}`);
        });
        udp.bind(port, '0.0.0.0', () => {
            console.log(`  ☑ UDP Socket listening on port ${port}`);
        });
        udp.on('error', () => {});
    } catch (_) {}
});

console.log('\nTekan Ctrl+C untuk menghentikan sniffer.\n');
