#!/usr/bin/env sh
set -eu

if ! set -o pipefail 2>/dev/null; then
  :
fi

SERVICE="${1:-}"
if [ -z "${SERVICE}" ]; then
  echo "usage: $0 <service-key>" >&2
  exit 2
fi

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/../../.." && pwd)"
cd "${REPO_ROOT}"

if bypass_reason="$(sh "${SCRIPT_DIR}/should_bypass_backend_check.sh" "${SERVICE}" lint)"; then
  echo "[backend-lint] ${bypass_reason}"
  exit 0
fi

if ! command -v golangci-lint >/dev/null 2>&1; then
  echo "[backend-lint] golangci-lint is required in PATH" >&2
  exit 1
fi

# shellcheck source=ci/scripts/common/backend_modules.sh
. "${SCRIPT_DIR}/backend_modules.sh"

if ! modules="$(backend_service_modules "${SERVICE}")"; then
  echo "[backend-lint] unknown service key: ${SERVICE}" >&2
  exit 2
fi

run_go_lint() {
  module="$1"
  if [ ! -f "${module}/go.mod" ]; then
    echo "[backend-lint] missing go.mod for module: ${module}" >&2
    exit 1
  fi
  if [ ! -f "${module}/.golangci.yml" ]; then
    echo "[backend-lint] missing .golangci.yml for module: ${module}" >&2
    exit 1
  fi

  echo "[backend-lint] running golangci-lint in ${module}"
  (
    cd "${module}"
    golangci-lint run --timeout=30m ./...
  )
}

for module in ${modules}; do
  run_go_lint "${module}"
done
