#!/bin/bash
# Script for running rubocop-git locally
# This creates a minimal bundle environment and runs the script

set -e

BUNDLE_DIR="./.tmp/rubocop-git"

# Check if bundle directory and Gemfile already exist
# with installed gems
if [ -f "$BUNDLE_DIR/Gemfile" ] && \
   [ -d "$BUNDLE_DIR/vendor/bundle/ruby" ]; then
    : # Bundle already exists, proceed silently
else
    echo "Setting up bundle in $BUNDLE_DIR..."

    # Create test directory
    mkdir -p "$BUNDLE_DIR"
    pushd "$BUNDLE_DIR" > /dev/null

    # Create minimal Gemfile
    cat > Gemfile <<'EOF'
source 'https://rubygems.org'

gem 'rubocop', '~> 1.0'
gem 'rubocop-rails'
gem 'rubocop-rspec'
gem 'rubocop-rspec_rails'
gem 'rubocop-factory_bot'
EOF
    echo "Created minimal Gemfile"

    # Install gems
    echo "Installing gems (this may take a minute)..."
    bundle config set --local path 'vendor/bundle'
    # Use ld.bfd instead of mold to avoid linker issues
    # on Fedora 43. Configure build options to use ld.bfd
    # for all gems
    bundle config set --local build.bigdecimal \
        "--with-ldflags=-fuse-ld=bfd"
    bundle config set --local build.json \
        "--with-ldflags=-fuse-ld=bfd"
    bundle config set --local build.racc \
        "--with-ldflags=-fuse-ld=bfd"
    bundle config set --local build.prism \
        "--with-ldflags=-fuse-ld=bfd"
    bundle install
    echo "Gems installed successfully"

    # Go back to project directory for git operations
    popd > /dev/null
fi

# Run the script with the test bundle
BUNDLE_GEMFILE="$BUNDLE_DIR/Gemfile" \
    bundle exec bin/rubocop-git "$@"
