#!/usr/bin/env bash
set -exuo pipefail


if ! which mockgen > /dev/null; then
  if [ -z ${GOPATH+somewords} ]; then
    export GOPATH="$HOME"/go;
  fi

  echo "Try to install mockgen"
  GO111MODULE=on go install go.uber.org/mock/mockgen@latest
  export PATH=$PATH:$GOPATH/bin
fi

mockgen -source=./mail/v2/mail.go -destination ./mail/mock_mail/mock_v2.go -package mock_mail
mockgen -source=./pubsub/types.go -destination ./pubsub/mock_pubsub/mock.go -package mock_pubsub
mockgen -source=./db/interface.go -destination ./db/mock_db/mock.go -package mock_db
mockgen -source=./clusterproxy/clusterproxy.go -destination ./clusterproxy/mock_clusterproxy/mock.go -package mock_clusterproxy
mockgen -source=./secret/encrypt/encryptor.go -destination ./secret/encrypt/mock_encryptor/mock.go -package mock_encryptor

# Loop through all first-level subdirectories under ./import/
for dir in ./import/*/; do
  # Get the directory name to use as the package name
  pkg=$(basename "$dir")

  # Loop through all .go files in the current subdirectory
  for f in "$dir"*.go; do
    filename=$(basename "$f" .go)

    # Skip test files and existing mock files
    if [[ "$filename" == *_test ]] || [[ "$filename" == mock_* ]]; then
      continue
    fi

    # Skip files that don't contain any interface definitions
    if ! grep -qE '^\s*type\s+\w+\s+interface\s*{' "$f"; then
      continue
    fi

    # Generate the mock file using mockgen
    mockgen -source="$f" -destination="${dir}mock_$filename.go" -package="$pkg"
  done
done
