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

usage() {
  cat <<'EOF'
Usage: fix_numeric_apostrophes.sh [--dry-run] FILE

Fix malformed numeric literals like:
  200 '345L
  1'000'000

It removes apostrophes (and surrounding spaces) only when they are between digits.

Options:
  --dry-run   Print diff, do not modify file
  -h, --help  Show this help
EOF
}

dry_run=0

if [[ $# -lt 1 || $# -gt 2 ]]; then
  usage
  exit 1
fi

if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
  usage
  exit 0
fi

if [[ "${1:-}" == "--dry-run" ]]; then
  dry_run=1
  shift
fi

if [[ $# -ne 1 ]]; then
  usage
  exit 1
fi

file="$1"
if [[ ! -f "$file" ]]; then
  echo "error: file not found: $file" >&2
  exit 1
fi

tmp="$(mktemp)"
trap 'rm -f "$tmp"' EXIT

# Remove apostrophes only when they are between digits, optionally with spaces.
perl -pe "s/(?<=\\d)\\s*'\\s*(?=\\d)//g" "$file" > "$tmp"

if cmp -s "$file" "$tmp"; then
  echo "no changes: $file"
  exit 0
fi

if [[ "$dry_run" -eq 1 ]]; then
  diff -u "$file" "$tmp" || true
else
  mv "$tmp" "$file"
  echo "updated: $file"
fi
