#!/usr/bin/env bash

# NB only check for duplicated -L or -I arguments because that’s the
# primary source of duplication. Some minor duplicates can also occur,
# like -Wl,--no-as-needed but there’s not too many of them yet to
# cause command line overflow.

# Quadratic algorithm because darwin CI doesn’t seem to have bash that
# supports associative arrays.
check_duplicate() {
    local test_arg="$1"
    local occurs="0"

    if ! [[ "$test_arg" == -L* || "$test_arg" == -I* ]]; then
        return 0
    fi

    shift
    for tmp in "${@}"; do
        if [[ "$tmp" == @* ]]; then
            while IFS= read -d $'\n' -r arg ; do
                if [[ "$arg" == "$test_arg" ]]; then
                    occurs=$((occurs + 1))
                fi
            done <"${tmp#@}"
        else
            if [[ "$tmp" == "$test_arg" ]]; then
                occurs=$((occurs + 1))
            fi
        fi
    done

    if [[ "$occurs" -gt 1 ]]; then
        return 1
    else
        return 0
    fi
}

i=1
for x in "${@}"; do
    if [[ "$x" == @* ]]; then
        file=
        while IFS= read -d $'\n' -r arg ; do
            y="$arg"
            if ! check_duplicate "$arg" "${@:$i}"; then
                echo "Duplicate argument detected: '$y'"
                echo "All args: ${@}"
                exit 1
            fi
        done <"${x#@}"
    else
        if ! check_duplicate "$x" "${@:$i}"; then
            echo "Duplicate argument detected: '$x'"
            echo "All args: ${@}"
            exit 1
        fi
    fi

    i=$((i + 1))
done

if which cc >/dev/null 2>&1; then
    cc -DNOERROR6 "${@}"
elif which gcc >/dev/null 2>&1; then
    gcc -DNOERROR6 "${@}"
elif which clang >/dev/null 2>&1; then
    clang -DNOERROR6 "${@}"
else
    echo "Cannot find C compiler" >&2
    exit 1
fi
