#!/bin/sh -e
#
# find-replace - with regex (sd rg perl sed). prefers faster alternative
#
# source: https://git.sr.ht/~seirdy/dotfiles

progname="$(basename "${0}")"
help_text="Usage:
  ${progname} [options] <find> <replace-with> <file

A simple wrapper around various find-replace programs with fallbacks.
Prefers the fastest available program and falls back to slower, more
advanced programs for less commonly available regex features.

Options:
  -h, --help
      Print this help and exit
"

usage() {
  printf '%s' "${help_text}"
}

# parse arguments
while [ "$#" -gt 0 ]; do
  case "$1" in
    -h | --help)
      usage
      exit 0
      ;;
    -*)
      printf '%s: invalid option: %s\n' "${progname}" "$1" >&2
      usage >&2
      exit 1
      ;;
    *)
      break
      ;;
  esac
done

find_regex="$1"
replace_regex="$2"

# functions to replace $1 with $2, with fallbacks if it doesn't work.
sed_fr() {
  sed -E "s/${find_regex}/${replace_regex}/g"
}

perl_fr() {
  # use perl's sed-like regex support; fall back to GNU sed with PCRE2 support if perl isn't installed.
  if command -v perl >/dev/null; then
    perl -p -e"s/${find_regex}/${replace_regex}/g"
  else
    sed_fr
  fi
}

ripgrep_fr() {
  # if my regex uses features like variable-length lookarounds
  # then even PCRE2 won't support it; in that case, fall back to
  # actual perl
  rg -a --engine=auto --passthru "${find_regex}" -r "${replace_regex}" || perl_fr
}

sd_fr() {
  # send stderr to /dev/null since this fails with some PCRE features
  # and I don't need to see that error message when it can just fall back
  # to ripgrep with --engine-auto, built with PCRE support
  sd -p "${find_regex}" "${replace_regex}" 2>/dev/null || ripgrep_fr
}

# I sometimes use this with huge logs, so I try to use the fastest regex
# find-replace program available, acc. to my benchmarks

# figure out which program to use for find-replace
find_alt() {
  for i; do
    if command -v "${i}" >/dev/null; then
      echo "${i}"
      return 0
    fi
  done
}
find_replace_prg="$(find_alt sd rg perl sed)"
case "${find_replace_prg}" in
  sd)
    sd_fr
    ;;
  rg)
    ripgrep_fr
    ;;
  perl)
    perl_fr
    ;;
  sed)
    sed_fr
    ;;
  *)
    echo "no suitable find-replace program found" >&2
    exit 1
    ;;
esac
