if ! command -v gitleaks >/dev/null 2>&1; then
  echo "Skipping gitleaks pre-push scan because gitleaks is not installed."
  echo "Install gitleaks locally to enable secret scanning on push."
  exit 0
fi

zero_oid="0000000000000000000000000000000000000000"
remote_name="${1:-origin}"
remote_default_ref=$(git symbolic-ref "refs/remotes/$remote_name/HEAD" 2>/dev/null || true)

if [ -z "$remote_default_ref" ]; then
  remote_head_branch=$(git remote show "$remote_name" 2>/dev/null | sed -n '/HEAD branch/s/.*: //p' | head -n 1)

  if [ -n "$remote_head_branch" ]; then
    remote_default_ref="$remote_name/$remote_head_branch"
  fi
else
  remote_default_ref=${remote_default_ref#refs/remotes/}
fi

if [ -z "$remote_default_ref" ]; then
  remote_default_ref="$remote_name/main"
fi

while read -r local_ref local_oid remote_ref remote_oid
do
  if [ -z "$local_ref" ] || [ "$local_oid" = "$zero_oid" ]; then
    continue
  fi

  if [ "$remote_oid" = "$zero_oid" ]; then
    merge_base=$(git merge-base "$local_oid" "$remote_default_ref" 2>/dev/null)

    if [ -n "$merge_base" ]; then
      log_opts="$merge_base..$local_oid"
    else
      log_opts="$local_oid^!"
    fi
  else
    log_opts="$remote_oid..$local_oid"
  fi

  commit_count=$(git rev-list --count "$log_opts" 2>/dev/null)
  if [ -z "$commit_count" ] || [ "$commit_count" = "0" ]; then
    continue
  fi

  echo "Running gitleaks on $local_ref ($commit_count commit(s))..."
  if ! gitleaks git --no-banner --redact --log-opts="$log_opts" .; then
    echo "Push blocked by gitleaks."
    exit 1
  fi
done
