#!/usr/bin/env bash
# CLEANER FILE - REMOVE EVERY FILE THAT MAY CREATE CONFLICT IF NOT REMOVED BEFORE BUILDING MACHINES #
source logging.sh
source variables.sh

# NOTE Check if the "CLEARED" marker is present to execute the cleaner only once.
# if grep -q "CLEARED" "$PATH_TO_BIN"; then
#   echo "bin.txt has already been cleared. Skipping the process."
#   exit 0
# else 
#   > "$PATH_TO_BIN"
#   echo "Previous credentials:" >> "$PATH_TO_BIN"
# fi

# Do a backup of authorized keys#
TIMESTAMP=$(date +%Y%m%d_%H%M%S)  # Timestamp for uniqueness
BACKUP_FILE="$PATH_TO_BACKUP_FOLDER/authorized_keys_$TIMESTAMP"

# Create backup folder if it doesn't exist
if [ -d "$PATH_TO_BACKUP_FOLDER" ]; then
  # Backup the SSH configuration file
  if [ -f "$SSH_CONFIG_FILE" ]; then
    cp "$SSH_ROOT_FOLDER/authorized_keys" "$BACKUP_FILE"
    log $DEBUG_LEVEL $VERBOSE_INFO "authorized_keys cleaned in $SSH_ROOT_FOLDER"
    chmod 777 "$BACKUP_FILE"  # Set permissions for the backup file
    log $DEBUG_LEVEL $VERBOSE_INFO "Backup of SSH configuration file created at $BACKUP_FILE"
  else
    log $DEBUG_LEVEL $VERBOSE_WARNING "SSH configuration file not found. No backup created."
  fi
else
  log $DEBUG_LEVEL $VERBOSE_ERROR "No Backup folder found - ensure to create a backup folder here: $PATH_TO_BACKUP_FOLDER"
fi

# Clear the contents of all .txt files and append .pub file contents in the script's directory and subdirectories (excluding tmp* files) 
find "$EPHEMERE_FOLDER_PATH" -type f \( -name "*.txt" -o -name "*.pub" \) ! -name "tmp*" | while read -r file; do
  if [[ "$file" == "$PATH_TO_BIN" ]]; then
    continue
  elif [ -f "$file" ]; then
    if [[ "$file" == *.txt ]]; then
      # Append the content of the .txt file to the bin.txt file
      cat "$file" >> "$PATH_TO_BIN"
      > $file
      echo "Content of $file appended to $PATH_TO_BIN."
    elif [[ "$file" == *.pub ]]; then
      # Append the content of the .pub file to the bin.txt file
      echo "Appending content of $file:" >> "$PATH_TO_BIN"
      cat "$file" >> "$PATH_TO_BIN"
      echo "Content of $file appended to $PATH_TO_BIN."
      sudo rm "$file"
      echo "$file removed"
    fi
  else
    echo "$file does not exist."
  fi
done

# Clear tar files in the current working directory and log it
# find . -maxdepth 1 -type f -name "*.tar" | while read -r tar_file; do
#   if [ -f "$tar_file" ]; then
#     sudo rm "$tar_file"
#     log $DEBUG_LEVEL $VERBOSE_INFO "$tar_file removed."
#   fi
# done

#HERE Cleaning the logs
# sudo rm $PATH_TO_LOG_DIR/*.log
# log $DEBUG_LEVEL $VERBOSE_INFO "$PATH_TO_LOG_DIR cleared."

# Making difference between vagrant up & destroy #

# Remove the "SETTED" tag from the bin.txt file if it exists
sed -i '/SETTED/d' "$PATH_TO_BIN"
# Add the "CLEARED" marker to the bin.txt file
echo "CLEARED" >> "$PATH_TO_BIN"
