#!/usr/bin/env python3
"""
Try different bit groupings and approaches
"""

import struct

def parse_pcap(filename):
    with open(filename, 'rb') as f:
        f.read(24)
        packets = []
        while True:
            packet_header = f.read(16)
            if len(packet_header) < 16:
                break
            ts_sec, ts_usec, incl_len, orig_len = struct.unpack('IIII', packet_header)
            packet_data = f.read(incl_len)
            if len(packet_data) < incl_len:
                break
            packets.append(incl_len)
        return packets

lengths = parse_pcap('sniffed.pcap')

# Find where the repetitive small packets start (all the 56's at the end)
last_varied = 0
for i in range(len(lengths)-1, 0, -1):
    if lengths[i] != 56:  # Find last non-56 packet
        last_varied = i + 1
        break

print(f"Total packets: {len(lengths)}")
print(f"Last varied packet: {last_varied}")
print(f"Packets after that are repetitive: {lengths[last_varied:]}")
print()

# Use only packets up to where variation stops
meaningful_lengths = lengths[:last_varied]
print(f"Using first {len(meaningful_lengths)} packets with variation")
print()

# Create pattern
pattern = ""
for l in meaningful_lengths:
    pattern += "L" if l >= 256 else "S"

binary = pattern.replace('S', '0').replace('L', '1')

print(f"Pattern: {pattern}")
print(f"Binary: {binary}")
print(f"Length: {len(binary)} bits")
print()

# Try 7-bit ASCII
print("=" * 80)
print("TRYING 7-BIT ASCII:")
print("=" * 80)

message_7bit = ""
for i in range(0, len(binary) - 6, 7):
    byte_str = binary[i:i+7]
    if len(byte_str) == 7:
        decimal = int(byte_str, 2)
        char = chr(decimal) if 32 <= decimal <= 126 else f"[{decimal}]"
        message_7bit += char if 32 <= decimal <= 126 else ""
        if i < 140:  # Print first 20 bytes
            print(f"Bits {i:3d}-{i+6:3d}: {byte_str} -> {decimal:3d} -> {char}")

print(f"\nDecoded (7-bit): {message_7bit}")

if "HTB" in message_7bit or "HTB{" in message_7bit:
    print("✓ Found HTB!")
    if "{" in message_7bit:
        start = message_7bit.find("HTB{" if "HTB{" in message_7bit else "{")
        end = message_7bit.find("}", start) + 1 if "}" in message_7bit[start:] else len(message_7bit)
        print(f"🚩 FLAG: {message_7bit[start:end]}")

# Try 8-bit on just the meaningful part
print("\n" + "=" * 80)
print("TRYING 8-BIT ASCII (meaningful packets only):")
print("=" * 80)

message_8bit = ""
for i in range(0, len(binary) - 7, 8):
    byte_str = binary[i:i+8]
    if len(byte_str) == 8:
        decimal = int(byte_str, 2)
        char = chr(decimal) if 32 <= decimal <= 126 else f"[{decimal}]"
        message_8bit += char if 32 <= decimal <= 126 else ""
        if i < 80:
            print(f"Byte {i//8:2d}: {byte_str} -> {decimal:3d} -> {char}")

print(f"\nDecoded (8-bit): {message_8bit}")

if "HTB" in message_8bit or "HTB{" in message_8bit:
    print("✓ Found HTB!")
    if "{" in message_8bit:
        start = message_8bit.find("HTB{" if "HTB{" in message_8bit else "{")
        end = message_8bit.find("}", start) + 1 if "}" in message_8bit[start:] else len(message_8bit)
        print(f"🚩 FLAG: {message_8bit[start:end]}")

# Try opposite encoding (L=0, S=1) with 7-bit
print("\n" + "=" * 80)
print("TRYING OPPOSITE (L=0, S=1) with 7-BIT:")
print("=" * 80)

binary_opp = pattern.replace('L', '0').replace('S', '1')
message_opp7 = ""
for i in range(0, len(binary_opp) - 6, 7):
    byte_str = binary_opp[i:i+7]
    if len(byte_str) == 7:
        decimal = int(byte_str, 2)
        char = chr(decimal) if 32 <= decimal <= 126 else f"[{decimal}]"
        message_opp7 += char if 32 <= decimal <= 126 else ""
        if i < 70:
            print(f"Bits {i:3d}-{i+6:3d}: {byte_str} -> {decimal:3d} -> {char}")

print(f"\nDecoded (opposite, 7-bit): {message_opp7}")

if "HTB" in message_opp7 or "HTB{" in message_opp7:
    print("✓ Found HTB!")
    if "{" in message_opp7:
        start = message_opp7.find("HTB{" if "HTB{" in message_opp7 else "{")
        end = message_opp7.find("}", start) + 1 if "}" in message_opp7[start:] else len(message_opp7)
        print(f"🚩 FLAG: {message_opp7[start:end]}")
