#!/bin/bash
set -e

function usage {
    echo "usage: $0 -i <docker image> [options] <program.p4>" >/dev/stderr
}

program() {
    # check if parameters is an array and not empty
    if [ ${#@} -eq 0 ]; then
        echo "ERROR: missing <program.p4> argument" >/dev/stderr
        usage
        exit 1
    fi
    # Just in case argument parsing gets out-of-sync,
    # validate it's really a file...
    if [[ -f "${@: -1}" ]]; then
        mount_dirs+=($(realpath $(dirname "${@: -1}")))
    fi
}

parse_args() {
    OPTIONS=($@)
    . "$(dirname "$0")/scripts_config.sh"
    . "$(dirname "$0")/scripts_utils.sh"
    dev_image ${OPTIONS[@]}
    program ${OPTIONS[@]}
    while [ $# -gt 0 ]; do
        arg="$1"
        shift
        case "$arg" in
        -I)
            if [[ $# -eq 0 ]]; then
                echo "ERROR: ${arg} option must be followed by <path> argument" >/dev/stderr
                usage
                exit 1
            fi
            arg2="$1"
            shift
            mount_dirs+=("$(realpath ${arg2})")
            ;;
        --arf | --log | --odir | --dump-*)
            if [[ $# -eq 0 ]]; then
                echo "ERROR: ${arg} option must be followed by <path> argument" >/dev/stderr
                usage
                exit 1
            fi
            arg2="$1"
            shift
            mount_dirs+=("$(realpath $(dirname "${arg2}"))")
            ;;
        esac
    done
    apply_extra_mount_folders ${OPTIONS[@]}
    dev_volumes ${mount_dirs[@]}
}

parse_args "$@"
set_docker_user_and_groups

ENVIRONMENTS=()

CMD=("nvp4c-doca" "${OPTIONS[@]}")
docker run --rm ${DOCKER_USER_AND_GROUPS[@]} -w ${PWD} "${ENVIRONMENTS[@]}" "${VOLUMES[@]}" "${DEV_IMAGE}" "${CMD[@]}"
