#!/usr/bin/env bash
#
# replace in files. uses ripgrep to find files, so all ripgrep arguments work.
# use `gr` command for dry-run, and then replace it with `wg`.
#
# - Replace a pattern in a file:
#
# `wg {{pattern}} {{filename}} --replace {{replacement}}`
#
# - Replace a pattern in all files:
#
# `wg {{pattern}} --replace {{replacement}}`

# ---
# see: https://github.com/lydell/dotfiles/blob/master/bin/pre
# source: https://github.com/sapegin/dotfiles

red='\e[0;31m'
no_color='\e[0m'
error() { printf '%b\n' "${red}$1${no_color}\n"; }

if [ "$1" = "-h" ]; then
  # print help/usage with no pattern/args
  sed -e '1d' -e '/^[^#]\|^$/,$d' -e 's/^# \?//' "$0"
fi

command -v rg > /dev/null 2>&1 || {
  error "ripgrep not installed: cargo install ripgrep"
  exit 1
}

seenReplace=''

for arg in "$@"; do
  if test "${arg}" = '--replace' -o "${arg}" = '-r'; then
    seenReplace='true'
    break
  fi
done

if test -z "${seenReplace}"; then
  error 'You should run wg with --replace or -r argument'
  exit 1
fi

currentFile=''
didChange=''

(
  rg \
    --context 999999 \
    --with-filename \
    --heading \
    --null \
    --color never \
    --no-line-number \
    --max-columns 0 \
    "$@"
  echo -e '\n\0'
) \
  | {
    while IFS= read -r -d '' part; do
      if test -n "${currentFile}"; then
        echo "${currentFile}"
        # write file without last two lines
        perl -ne 'push(@buf,$_);END{print @buf[0 ... $#buf-2]}' <<< "${part}" >"${currentFile}"
        didChange='true'
      fi
      currentFile="$(tail -n 1 <<<"${part}")"
    done

    if test -z "${didChange}"; then
      echo "No files were changed"
      exit 1
    fi
  }
