#!/usr/bin/env bash

# Copyright 2016 The Kubernetes Authors All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
set -euo pipefail

exit_code=0

if [[ -z "$@" ]] ; then
  DIRECTORIES=./...
else
  DIRECTORIES="$@"
fi

if ! hash gometalinter.v2 2>/dev/null ; then
  echo "run make setup to install gometalinter.v2" >&2
  exit 1
fi

ERRORS_ONLY=${ERRORS_ONLY:=""}
ONLY_LINT=${ONLY_LINT:=""}
ONLY_STATIC=${ONLY_STATIC:=""}

if [[ -z ${ONLY_LINT} ]] ; then
  if [[ -z ${ERRORS_ONLY} ]] ; then
    {
      echo
      echo "==> Running static validations <=="
    } 1>&2
  fi

# without this metalinter will look at go source
export CGO_ENABLED=0

# Run linters that should return errors
# TODO: add vetshadow
gometalinter.v2 \
  --disable-all \
  --enable gofmt \
  --enable ineffassign \
  --enable misspell \
  --enable vet \
  --enable vetshadow \
  --tests \
  --deadline 60s \
  $DIRECTORIES || exit_code=1
fi

if [[ -z ${ONLY_STATIC} ]] ; then
  if [[ -z ${ERRORS_ONLY} ]] ; then
    {
      echo
      echo "==> Running linters <=="
    } 1>&2
  fi

# Run linters that should return warnings
gometalinter.v2 \
  --disable-all \
  --deadline 60s \
  --enable golint \
  --tests \
  $DIRECTORIES || :
fi

exit $exit_code
