#!/usr/bin/env bash
# to find all creatures with diseased/infected etc in name:
# ./tes3cmd dump "*.{esm,ESM,esp,ESP,omwaddon}" --list --type CREA --match "FNAM:.*diseased |FNAM:.*blighted |FNAM:.*plague |FNAM:.*infected |FNAM:.*plaguebearer "
tes3cmd="./tes3cmd"
dirty_dump=yandl_dirty_dump_list.txt
dirty_modify=yandl_dirty_modify_list.txt
if [ -s "${dirty_dump}" ]; then mv -v "${dirty_dump}" "backup_${dirty_dump}"; fi
if [ -s "${dirty_modify}" ]; then mv -v "${dirty_modify}" "backup_${dirty_modify}"; fi
for plugin in\
 "Morrowind.esm"\
 "Tribunal.esm"\
 "Bloodmoon.esm"\
 "Patch for Purists.esm"\
 "BlightedAnimalsRetextured.esp"\
 "Tribunal Rebalance.ESP"\
 "Bloodmoon Rebalance.esp"\
 "Tamriel_Data.esm"\
 "TR_Mainland.esm"\
 "Ttooth Ecology.esp"\
 "Ttooth Ecology - BMR Patch.ESP"\
 "Ttooth Ecology - TR Patch.ESP"\
  ; do
      echo >> "${dirty_dump}"
      echo "# YANDL - ${plugin%.*}.esp" | tee -a "${dirty_dump}" >> "${dirty_modify}"
      $tes3cmd dump "${plugin}" --type CREA --match "FNAM:.*diseased |FNAM:.*blighted |FNAM:.*plague |FNAM:.*infected |FNAM:.*plaguebearer " --list | \
       sed "s/ CREA: \(.*\) (\(.*\))/\1|\2|${plugin}/" | while read -r line; do
         cid="$(echo "${line}" | cut -d '|' -f 1)"
         cnm="$(echo "${line}" | cut -d '|' -f 2)"
         prev_pid="${pid:-empty}"
         pid="$(echo "${line}" | cut -d '|' -f 3)"
         case "$cid" in
           "rat_plague_hall1") continue ;;
           "rat_plague_hall1a") continue ;;
           "rat_plague_hall2") continue ;;
           "rat_cave_hhte2") continue ;;
           "shalk_diseased_hram") continue ;;
           "kwama warrior shurdan") continue ;;
        esac
        if [ "${pid}" != "${prev_pid}" ]; then
           # shellcheck disable=SC2016
           printf '$tes3cmd dump "%s" --raw "${result}" --type CREA' "${pid}" >> "${dirty_dump}"
        fi
        new_cnm="$(echo "${cnm}" | sed -e 's/[dD]iseased //' -e 's/[bB]lighted //' -e 's/[pP]lague //' -e 's/[iI]nfected //' -e 's/[pP]laguebearer //')"
        printf '\\\n --exact-id "%s"' "${cid}" >> "${dirty_dump}"
        echo "\$tes3cmd modify \"\${result}\" --hide-backups --type CREA --exact-id \"${cid}\" --run \"\\\$R->set({t=>'FNAM', f=>'Name'}, '${new_cnm}')\"" >> "${dirty_modify}"
  done
done
