#!/usr/bin/env bash

set -euo pipefail

GREEN=$'\E[00;32m'
RED=$'\E[00;31m'
RESET=$'\E[0m'
if [ ! -t 1 ]; then
    GREEN=''
    RED=''
    RESET=''
fi

VETTOOLS=(
    # fieldalignment: noisy and not useful here
    findcall
    ifaceassert
    lostcancel
    nilness
    shadow
    stringintconv
    unmarshal
    unusedresult
)

DIR="$(mktemp -d -t 'go-vet-')"
trap 'rm -r $DIR' EXIT

touch "$DIR/vet"
go vet ./... >"$DIR/vet" 2>&1 &

for tool in "${VETTOOLS[@]}"; do
    touch "$DIR/$tool"
    "$tool" ./... >"$DIR/$tool" 2>&1 &
done

wait

if hash escape-regex 2>/dev/null; then
    REPLACE="$(escape-regex -s "$(pwd)"/)"
else
    REPLACE=''
fi

VETTOOLS+=(vet)
ERRORS=0
for tool in "${VETTOOLS[@]}"; do
    if [[ -s "$DIR/$tool" ]]; then
        printf "%s: ${RED}error${RESET}\n" "$tool"
        if [[ -n $REPLACE ]]; then
            sed "s/$REPLACE//g" "$DIR/$tool" | pr -o4 -t -
        else
            pr -o4 -t - "$DIR/$tool"
        fi
        ERRORS=1
    else
        printf "%s: ${GREEN}pass${RESET}\n" "$tool"
    fi
done

exit $ERRORS
