import sys
from scapy.all import sniff, send, IP, IPv6, TCP, Packet, Raw, Ether, sendp, wrpcap, PacketList, HTTPResponse
from datetime import datetime

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

def modify_packet(packet: Packet):
    global modifications
    global seen
    if packet.haslayer(IP) and packet.haslayer(TCP) and packet.haslayer(HTTPResponse):
        if packet[IP].ttl != 65:
            packet[IP].ttl = 65
            modifications += 1
    elif packet.haslayer(IPv6):
        if packet[IPv6].ttl != 65:
            packet[IPv6].ttl = 65
            modifications += 1
    seen += 1
    #Can be extented with other protocols which have TTL
    sendp(packet, iface='eth0')


if __name__ == "__main__":
    modifications = 0
    seen = 0
    if len(sys.argv) != 2:
        print(f"Usage: {sys.argv[0]} <interface>")
        sys.exit(1)

    interface = sys.argv[1]

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

    packets: PacketList = sniff(filter="ip or ip6", iface='eth1', timeout=5*1, prn=modify_packet)
    # save_packets(packets, "final_1.pcap")
    end_time = datetime.now()
    print(f"Script ended at: {end_time.strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"{modifications} ip(v6) packets modified")
    print(f"{seen} total ip(v6) packets seen")