#!/usr/bin/env bash

# Copyright 2021 The Kubernetes Authors.
#
# 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.

# This script generates mock files using mockgen.
# Usage: `hack/update-mocks.sh`.

set -o errexit
set -o nounset
set -o pipefail

KUBE_ROOT=$(dirname "${BASH_SOURCE[0]}")/..
source "${KUBE_ROOT}/hack/lib/init.sh"

kube::golang::setup_env

echo 'installing mockery'
GOTOOLCHAIN="$(kube::golang::hack_tools_gotoolchain)" go -C "${KUBE_ROOT}/hack/tools" install github.com/vektra/mockery/v2

function git_grep() {
  git grep --untracked --exclude-standard \
      "$@" \
      ':!:vendor/*'        `# catches vendor/...` \
      ':!:*/vendor/*'      `# catches any subdir/vendor/...` \
      ':!:third_party/*'   `# catches third_party/...` \
      ':!:*/third_party/*' `# catches third_party/...` \
      ':!:*/testdata/*'    `# catches any testdata` \
      ':(glob)**/*.go'
}

cd "${KUBE_ROOT}"

GENERATED_MOCK_FILE_REGEX="^// Code generated by mockery v[0-9.]\+. DO NOT EDIT.$"

git_grep -l -z "${GENERATED_MOCK_FILE_REGEX}" | xargs -0 rm -f

echo 'executing go generate command on below files'

git_grep -l -z "//go:generate mockery" | while read -r -d $'\0' file; do
  echo "- ${file}"
  temp_file_name="$(kube::realpath "$(mktemp -t "$(basename "$0").XXXXXX")")"

  # search for build tag used in file
  build_tag_string=$(grep -o '+build.*$' "$file") || true

  # if the file does not have build string
  if [ -n "$build_tag_string" ]; then
    # write the build tag in the temp file
    echo -n "$build_tag_string" > "$temp_file_name"

    # if +build tag is defined in interface file
    BUILD_TAG_FILE=$temp_file_name go generate -v "$file"
  else
    # if no +build tag is defined in interface file
    # NOTE: This works around a bug in `go generate` with workspaces, which
    # should be fixed in Go 1.22.1.
    go -C "$(dirname "$file")" generate "$(basename "$file")"
  fi
done
