#!/usr/bin/env bash

set -e

export GO111MODULE=on

# For the check step concourse will set the following environment variables:
# SOURCE_PATH - path to component repository root directory.

# not all platforms support readlink -f
# SOURCE_PATH must be set, and treat it as absolute path
rlink=""
set +e
readlink -f /tmp >/dev/null 2>&1
if [ $? -eq 0 ]; then
  # do not support readlink -f, so need alternative
  rlink="readlink -f"
fi
set -e


if [[ -z "${SOURCE_PATH}" ]]; then
  if [ -z "$rlink" ]; then
    echo "ERROR: system does not support 'readlink -f' and SOURCE_PATH not set, exiting." >&2
    exit 1
  fi
  export SOURCE_PATH="$($rlink "$(dirname ${0})/..")"
else
  if [ -z "$rlink" ]; then
    echo "warning: system does not support 'readlink -f', treating SOURCE_PATH as absolute path with symlinks resolved." >&2
  else
    export SOURCE_PATH="$($rlink ${SOURCE_PATH})"
  fi
fi

cd "${SOURCE_PATH}"

# Build Golint.
go install -mod=vendor ./vendor/golang.org/x/lint/golint

# Install Helm (see https://docs.helm.sh/using_helm/#from-script).
if ! which helm 1>/dev/null; then
  export DESIRED_VERSION=v2.14.3
  echo -n "Installing helm... "
  install_helm_path="./get_helm.sh"
  curl https://raw.githubusercontent.com/helm/helm/master/scripts/get > "${install_helm_path}"
  chmod 700 "${install_helm_path}"
  bash "${install_helm_path}"
  rm ./"${install_helm_path}"
  echo "done."
fi

###############################################################################

PACKAGES="$(go list -mod=vendor -e ./... | grep -vE '/pkg/apis|/pkg/controllermanager/apis|/pkg/scheduler/apis|/pkg/gardenlet/apis|/pkg/openapi')"
PACKAGES_DIRS="$(echo ${PACKAGES} | sed "s|github.com/gardener/gardener|.|g")"

# Execute static code checks.
echo "Running go vet..."
go vet -mod=vendor ${PACKAGES}

# go fmt ignores -mod=vendor and performs module lookup (https://github.com/golang/go/issues/27841).
# Also go fmt is just alias for gofmt -l -w and does not support flags that gofmt does.
# That is why gofmt is used.

# Execute automatic code formatting directive.
echo "Running gofmt..."
gofmt -l -w -s ${PACKAGES_DIRS}

# Execute lint checks.
echo "Running golint..."
for dir in ${PACKAGES_DIRS}; do
  golint -set_exit_status $(find $dir -maxdepth 1 -name "*.go" | grep -vE 'zz_generated|_test.go')
done

# Check for chart symlink errors
BROKEN_SYMLINKS=$(find -L ${SOURCE_PATH}/charts -type l)
if [[ -n ${BROKEN_SYMLINKS} ]]; then
  echo "Found broken symlinks:"
  echo ${BROKEN_SYMLINKS}
  exit 1
fi

# Render chart dirs
ALL_CHART_DIRS=$(find ${SOURCE_PATH}/charts -type f -name "Chart.yaml" -exec dirname {} \; | sort -r)
for dir in ${ALL_CHART_DIRS}
do
  helm template ${dir} 1> /dev/null
done
