#!/usr/bin/env python3

"""
This example configures CSP on the host machine and establishes a CSP route to
a Polaris receiver via KISS. Some of the BTP functions are then demonstrated.

Refer to lib/btp-client/python/bindings/btp_client_python.c for a complete list
of available BTP bindings.

Prerequisites:

Python bindings shall be enabled when building ``satctl`` and installed on the
system or in a virtual environment. See the ``README`` file for details.

The routing table on the DUT shall be configured to respond to node 5 via KISS,
the routing table below routes traffic to node 5 via KISS, and traffic to all
other nodes via CAN.

    [polaris] prop list sys
    Property        Type  Stat  Flag  Value
    ...
    csp.routes      str   B     -     0/0 CAN, 5/5 KISS
    ...

Create a 100kb file in the same directory as this script is executed from.

    dd if=/dev/urandom of=100kb.bin bs=1024 count=100
"""

import argparse

import csp


def example(args):
    if args.dut == 'ais':
        from satlab import polaris_ais_client
        dut_addr = polaris_ais_client.DEFAULT_ADDRESS  # 20
        client = polaris_ais_client.PolarisAIS()
    elif args.dut == 'adsb':
        from satlab import polaris_adsb_client
        dut_addr = polaris_adsb_client.DEFAULT_ADDRESS  # 23
        client = polaris_adsb_client.PolarisADSB()
    else:
        raise NotImplementedError(f"DUT {args.dut} not supported")

    host_csp_addr = 5

    csp.init(host_csp_addr)
    csp.kiss_init(args.kiss_device, args.kiss_rate)

    csp.route_start_task()
    # Route all packets to DUT via KISS
    csp.rtable_set(dut_addr, 5, 'KISS')

    # Use the prop bindings to mount the file system on the Polaris
    client.prop.set('conf.fs.mount', True)

    # Make a new directory on remote
    client.btp.mkdir(remotepath='/bindingtest')
    # Push the 100kb file to remote
    client.btp.push(localpath='100kb.bin', remotepath='/bindingtest/100kb.bin')
    # List the contents of the new directory on remote
    print(client.btp.list(remotepath='/bindingtest'))
    # Pull the file from remote, forcing an overwrite
    client.btp.pull(remotepath='/bindingtest/100kb.bin', localpath='100kbpull.bin', force=True)
    # Remove the file and test folder
    client.btp.remove(remotepath='/bindingtest/100kb.bin')
    client.btp.rmdir(remotepath='/bindingtest')


def main():
    # Parse arguments
    parser = argparse.ArgumentParser()

    parser.add_argument('--dut', help='Target DUT', type=str, choices=['ais', 'adsb'], required=True)
    parser.add_argument('--kiss-device', help='Path to KISS device on host PC', type=str, default='/dev/ttyUSB1')
    parser.add_argument('--kiss-rate', help='Data rate of the KISS device, must match sys.uart.rate on DUT',
                        type=int, default=3000000)

    args = parser.parse_args()

    example(args)


if __name__ == '__main__':
    main()
