import sys
import os
import datetime

# You may need to modify this to your bluespy installation path
if sys.platform.startswith("win32"):
    sys.path.append("C:/Program Files/RFcreations/blueSPY")
elif sys.platform.startswith("darwin"):
    sys.path.append("/Applications/blueSPY.app/Contents/Resources")
elif sys.platform.startswith("linux"):
    sys.path.append("/opt/blueSPY")

import bluespy

if len(sys.argv) < 3:
    print("split_by_time.py file split_minutes [ltk...]")
    sys.exit(1)


def fname(t):
    # Create a name for the split file based on the timestamp
    name = os.path.splitext(sys.argv[1])[0]
    return "{}-{:%y-%m-%dT%H.%M.%S}.pcapng".format(name, datetime.datetime.fromtimestamp(t))


try:
    # Add link keys before loading the file
    for k in sys.argv[3:]:
        h = bytes.fromhex(k)
        if len(h) != 16:
            print("Expected a 16 byte key, not {}".format(k))
            sys.exit(1)
        bluespy.add_link_key(h)

    # Connect to a Moreph to ensure the new files are signed
    bluespy.connect()

    bluespy.load_file(sys.argv[1])
    print("Loaded {}, {} packets".format(sys.argv[1], len(bluespy.packets)))
    if len(bluespy.packets) == 0:
        sys.exit(0)

    start_time = bluespy.packets[0].time // 1_000_000_000  # time is in ns
    split_time = int(sys.argv[2]) * 60  # arg is in minutes

    # Create the first segment
    file = bluespy.create_filter_file(fname(start_time))

    for pkt in bluespy.packets:
        t = pkt.time // 1_000_000_000
        while t > start_time + split_time:
            # Create a new segment
            bluespy.close_filter_file(file)
            start_time += split_time
            file = bluespy.create_filter_file(fname(start_time))
        bluespy.add_to_filter_file(file, pkt)

    bluespy.close_filter_file(file)
    bluespy.close_file()
    bluespy.disconnect()

except bluespy.BluespyError as e:
    print(e)
    sys.exit(1)
