#!/bin/bash

## Copyright (C) 2022 - 2025 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

#set -x
set -o errexit
set -o nounset
set -o pipefail
set -o errtrace
shopt -s inherit_errexit

## XXX: hardcoded path
cd -- "$HOME/derivative-maker"

## NOTE: does not support spaces
replace_list="\
exception_handler_shell exception_handler_shell
exception_handler_retry exception_handler_retry
exception_handler_process_shared exception_handler_process_shared
exception_handler_maybe_exit exception_handler_maybe_exit
exception_handler_general exception_handler_general
exception_handler_unmount exception_handler_unmount
"

# total=0
# while IFS= read -r -d '' file_name ; do
#    total=$(( total + 1 ))
# done < <( find . -type f -not -iwholename '*.git*' -print0 )

counter=0
export counter

while IFS= read -r -d $'\0' file_name; do
   counter=$(( counter + 1 ))

   basename_file_name="${file_name##*/}"

   if [ "$basename_file_name" = "changelog.upstream" ]; then
      continue
   fi
   if [ "$basename_file_name" = "dm-replace-list" ]; then
      continue
   fi

   while read -r line ; do
      if [ "$line" = "" ]; then
         error "ERROR! line is empty!"
      fi

      true "line: '$line'"
      read -r first second <<< "$line"

      if [ "$first" = "" ]; then
         error "ERROR! first is empty!"
      fi
      if [ "$second" = "" ]; then
         error "ERROR! second is empty!"
      fi

      str_replace "$first" "$second" "$file_name"

      #str_replace 'sudo $SUDO_OPTS' '$SUDO_TO_USER' "$file_name"

#       new_file_name="$(echo "$file_name" | str_replace "$first" "$second")"
#       if [ "$file_name" = "$new_file_name" ]; then
#          true
#       else
#          echo mv "$file_name" "$new_file_name"
#       fi

   ## $replace_list already ends with a newline; use printf '%s' (no
   ## extra newline) so the read loop does not see a trailing empty
   ## line and trip the `error "ERROR! line is empty!"` guard below.
   done < <( printf '%s' "$replace_list" )

   true "INFO: main loop end"

done < <( find . -type f -not -iwholename '*.git*' -print0 )

printf '%s\n' "$0: END."
