#Created with some assitance from ChatGPT for event handling mechanism
import os
import signal
import sys
import time
import socket
from scapy.all import sniff, wrpcap
from datetime import datetime
from threading import Event

def signal_handler(sig, frame):
    global stop_event
    stop_event.set()

def capture_traffic(interface, ip='192.168.0.56', port=5000):
    global stop_event

    stop_event = Event()
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)

    def create_filename(interface):
        now = datetime.now()
        return f"captures/{now.strftime('%Y%m%d_%H%M')}_{interface}_{int(time.time())}.pcap"

    def save_packets(packets, filename):
        wrpcap(filename, packets)
        print(f"Saved {len(packets)} packets to {filename}")
        send_file(filename, ip, port)

    #on the netcat server, run `nc -l -p 5000 > received_file.pcap`
    def send_file(filename, ip, port):
        with open(filename, 'rb') as f:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((ip, port))
            data = f.read(1024)
            while data:
                s.send(data)
                data = f.read(1024)
            s.close()
            print(f"Sent {filename} to {ip}:{port}")

    while not stop_event.is_set():
        filename = create_filename(interface)
        packets = sniff(iface=interface, timeout=30*1, stop_filter=lambda x: stop_event.is_set())
        save_packets(packets, filename)

if __name__ == "__main__":
    if len(sys.argv) < 2 or len(sys.argv) > 4:
        print(f"Usage: {sys.argv[0]} <interface> [ip] [port]")
        sys.exit(1)

    interface = sys.argv[1]
    ip = sys.argv[2] if len(sys.argv) > 2 else '192.168.0.56'
    port = int(sys.argv[3]) if len(sys.argv) > 3 else 5000

    start_time = datetime.now()
    print(f"Script started at: {start_time.strftime('%Y-%m-%d %H:%M:%S')}")

    capture_traffic(interface, ip, port)

    end_time = datetime.now()
    print(f"Script ended at: {end_time.strftime('%Y-%m-%d %H:%M:%S')}")
