#!/usr/bin/env bash

set -e

# run with bazel if launched directly
if [ -z ${BUILD_WORKSPACE_DIRECTORY+x} ]; then
    bazel run -- //firmware/can_eth_gateway:launch_vcan "$@"
    exit $?
fi

usage() {
    echo "Forward messages to/from a CAN gateway to linux SocketCAN interface."
    echo "usage: $0 [--l3]"
}

# process options
OPT_L3= # default to vh6b mode expecting EMU forwarding
while [ "$1" != "" ]; do
    case $1 in
        --l3 )          shift
                        OPT_L3="--l3"
                        ;;
        -h | --help )   shift
                        usage
                        exit 1
    esac
done

PEER_IP=$(dig can-gateway +short)
LOCAL_IP='0.0.0.0' # listen on all interfaces

sleep 1

function cleanup {
    echo "Cleaning up."
    firmware/tools/can_gateway/vcan_down
}
trap cleanup EXIT

firmware/tools/can_gateway/vcan_up

echo "Started forwarding. (Press Ctrl+C to terminate.)"
firmware/tools/can_gateway/can_gateway -l ${LOCAL_IP} -p 8675 -r ${PEER_IP} -q 8675 ${OPT_L3} || true
