#!/bin/bash

set -e

if [[ $2 = true ]]
then
  target=$1
else
  target="origin/$1"
fi

changed_ruby_files=$(git diff-tree -r --no-commit-id --name-only $target..HEAD | grep '\.rb$' || :)

if [ -z "$changed_ruby_files" ]
then
  echo "✅ No Ruby files changed compared to $target. Skipping rubocop."
  exit 0
fi

result_info="bundle exec rubocop --force-exclusion --format simple $changed_ruby_files"
files_inspected=`$result_info | grep "files inspected\|file inspected" | cut -d " " -f1`
warning_count=`$result_info | grep "offenses detected\|offense detected" | cut -d " " -f4`

if [ $warning_count == 'no' ]
then
  echo "✅ Clean code! No rubocop offenses detected in $files_inspected changed file(s). Compared to $target. Great job ಠ_ಠ"
  exit 0
elif [ $warning_count -ge '1' ]
then
  echo -e "❌ Inspected $files_inspected file(s) and detected $warning_count offense(s). Compared to $target"
  $result_info
  exit 1
else
  echo -e "❌ Something went wrong"
  exit 1
fi
