#!/usr/bin/env bash
# rename-upstream — rewrite EpsilonEridaniWorker names into ProcyonWorker names.
#
# ProcyonWorker is a fork of eic/EpsilonEridaniWorker. This script is the mechanical part of the
# fork: the substitutions that turn the upstream worker's names (package, command, environment
# prefix, repositories, the `roadmap` stage) into this one's. It was run once over the imported
# tree, and it is kept so that a later upstream change can be ported the same way:
#
#   git -C ../EpsilonEridaniWorker format-patch --stdout <old>..<new> | tools/rename-upstream - | git am -3
#
# With file arguments it rewrites those files in place; with `-` it filters stdin to stdout
# (a patch, including its paths). It knows nothing about meaning: what the Procyon worker does
# differently from upstream is hand-written, and a ported patch that touches those parts conflicts.
set -euo pipefail

SED=(
  # Repositories and the directory of plans inside the plans repository.
  -e 's#EpsilonEridaniRoadmaps#ProcyonAnalyses#g'
  -e 's#EpsilonEridaniRoadmap#ProcyonAnalyses#g'
  -e 's#epsiloneridani-claims#procyon-claims#g'
  # The plans checkout and the plans repository constant.
  -e 's#__ROADMAP_DIR__#__PLANS_DIR__#g'
  -e 's#ROADMAP_DIR#PLANS_DIR#g'
  -e 's#roadmap_dir#plans_dir#g'
  -e 's#roadmap-dir#plans-dir#g'
  -e 's#\bROADMAP\b#PLANS#g'
  # The authoring stage: `roadmap` upstream, `analysis` here.
  -e 's#roadmaps#analyses#g'
  -e 's#Roadmaps#Analyses#g'
  -e 's#ROADMAPS#ANALYSES#g'
  -e 's#roadmap#analysis#g'
  -e 's#Roadmap#Analysis#g'
  -e 's#ROADMAP#ANALYSIS#g'
  # The project, the package, the command and the environment prefix.
  -e 's#Tau Ceti#Procyon#g'
  -e 's#epsiloneridani_worker#procyon_worker#g'
  -e 's#EpsilonEridani#Procyon#g'
  -e 's#EPSILONERIDANI#PROCYON#g'
  -e 's#epsiloneridani#procyon#g'
)

if [ "$#" -eq 0 ]; then
  echo "usage: tools/rename-upstream - | <file>..." >&2
  exit 2
fi
if [ "$1" = "-" ]; then
  exec sed "${SED[@]}"
fi
for file in "$@"; do
  # Text files only; a symlink is left for its target.
  if [ -f "$file" ] && [ ! -L "$file" ] && grep -Iq . "$file"; then
    sed -i "${SED[@]}" "$file"
  fi
done
