#!/usr/bin/bash
set -e

function usage {
    echo "usage: $0 -i <docker image> -p <program_folder> [-a <dpl_rtd_ip:port>] [OPTIONS]" >/dev/stderr
    echo "For example:" >/dev/stderr
    echo "$0 -i <docker image> -p /root/hello_packet/_out -a 192.168.1.100:9559 --device-id 1000" >/dev/stderr
}

parse_args() {
    OPTIONS=($@)
    mount_dirs=("$(realpath ${PWD})")
    . "$(dirname "$0")/scripts_config.sh"
    . "$(dirname "$0")/scripts_utils.sh"
    dev_image ${OPTIONS[@]}
    apply_program_folder ${OPTIONS[@]}
    p4rt_address ${OPTIONS[@]}

    CMD=("python3" "-m" "p4runtime_sh")
    if [ -n "${P4RT_ADDRESS}" ]; then
        CMD+=("--grpc-addr" "${P4RT_ADDRESS}")
    fi
    CMD+=("--election-id" "0,1" "--no-ssl")
    if [ -n "${PROGRAM_FOLDER}" ]
    then
        local CONFIG_P4INFO="$(ls "$PROGRAM_FOLDER"/*.p4info.txt | head -n 1)"
        if [ -z "${CONFIG_P4INFO}" ]
        then
            echo "ERROR: No p4info file found in ${PROGRAM_FOLDER}" >/dev/stderr
            exit 1
        fi

        local CONFIG_DPLCONFIG="$(ls "$PROGRAM_FOLDER"/*.dplconfig | head -n 1)"
        if [ -z "${CONFIG_DPLCONFIG}" ]
        then
            echo "ERROR: No dplconfig file found in ${PROGRAM_FOLDER}" >/dev/stderr
            exit 1
        fi

        CMD+=("--config" "${CONFIG_P4INFO},${CONFIG_DPLCONFIG}")
    fi
    CMD+=(${OPTIONS[@]})

    create_tmp_execution_script /venv/p4runtime-shell/bin ${CMD[@]}
    mount_dirs+=(${PROGRAM_FOLDER} ${TMPFILE})
}

parse_args "$@"
dev_volumes ${mount_dirs[@]}


ENVIRONMENTS=()

docker run -ti --rm --network host -w ${PWD} "${ENVIRONMENTS[@]}" "${VOLUMES[@]}" "${DEV_IMAGE}" ${TMPFILE}
rm ${TMPFILE}
