#!/bin/bash

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

#set -x
set -e

cd ~/derivative-maker

## NOTE: does not support spaces
replace_list=$(echo "\
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=$(( total + 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

      LANG=C str_replace "$first" "$second" "$file_name"

      #LANG=C 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

   done < <( echo "$replace_list" )

   true "INFO: main loop end"

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

echo "$0: END."
