#!/bin/bash

# Source the variables.sh file to get environment variables, including DEBUG_LEVEL
source variables.sh
source logging.sh  # Assuming the logging function is defined here

# Define the log file
LOG_FILE="$PATH_TO_LOG_DIR/setup_host.log"

# Clear the log file at the start
: > "$LOG_FILE"

# Determine the script's directory
SCRIPT_DIR="$(dirname "$(readlink -f "$0")")/$EPHEMERE_FOLDER_PATH"

# NOTE Check if the "SETTED" tag is present to execute one time after a RUN #
BIN_FILE="$SCRIPT_DIR/bin.txt"
if grep -q "SETTED" "$BIN_FILE"; then
  log $DEBUG_LEVEL $VERBOSE_INFO "bin.txt has already been set. Skipping setting up the machine."

  # Extract the current count of "MACHINE PROVISIONNED" from bin.txt
  provisioned_count=$(grep -oP '(?<=MACHINE PROVISIONNED : )\d+' "$BIN_FILE" | tail -n 1)

  # If no count is found, start from 0
  provisioned_count=${provisioned_count:-0}

  # Set node_count to the length of NODES array
  node_count=${#NODES[@]}

  # Check if all nodes are provisioned
  if [[ "$provisioned_count" -ge "$node_count" ]]; then
    log $DEBUG_LEVEL $VERBOSE_INFO "All machines were set up...skipping setting up of the host."
    exit 0
  fi

  # Increment the count
  provisioned_count=$((provisioned_count + 1))

  # Log the incremented count
  log $DEBUG_LEVEL $VERBOSE_INFO "Incrementing MACHINE PROVISIONNED count to $provisioned_count"

  # Update or append the count to bin.txt
  sed -i "/MACHINE PROVISIONNED : /c\MACHINE PROVISIONNED : $provisioned_count" "$BIN_FILE" || echo "MACHINE PROVISIONNED : $provisioned_count" >> "$BIN_FILE"

  exit 0
fi

# NOTE VERY Initialisation scripts #
log $DEBUG_LEVEL $VERBOSE_INFO "Starting initialization scripts."
./make_executable.sh

# Generate SSH keys (#INFO ed25519 & ~ folder) on the host machine if they don't exist
# NOTE ssh key on host machine: HOME folder -> This is to connect via VSCode, key specified in the config file generated at the end.
if [ ! -f "$SSH_HOME_FOLDER/$KEY_TYPE_SSH" ]; then
  log $DEBUG_LEVEL $VERBOSE_INFO "Host computer does not have a public key, creating it..."

  # Generate the key at the default location in SSH_HOME_FOLDER
  ssh-keygen -t "$KEY_TYPE_SSH" -b 2048 -f "$SSH_HOME_FOLDER/$KEY_TYPE_SSH" -C "$HOSTNAME" -N ""
fi

# Copy the host machine's public key to the specified path
sudo cp "$SSH_HOME_FOLDER/$KEY_TYPE_SSH.pub" "$PATH_TO_SSH_HOST_KEY"
log $DEBUG_LEVEL $VERBOSE_INFO "Added host public key to $PATH_TO_SSH_HOST_KEY"

# HERE CREATING TOP DIRECTORY FILES #
# Creating txt files if they do not exist with appropriate permissions
for file in "${EPHEMERE_FILE_NAMES[@]}"; do
  if [ ! -f "$SCRIPT_DIR/$file" ]; then
    touch "$SCRIPT_DIR/$file"
    chmod 644 "$SCRIPT_DIR/$file"
    log $DEBUG_LEVEL $VERBOSE_INFO "Created $file with permissions 644."
  fi
done

# HERE CREATING FOLDERS #
# Creating ephemere folders if they do not exist
for folder in "${EPHEMERE_FOLDER_NAMES[@]}"; do
  if [ ! -d "$SCRIPT_DIR/$folder" ]; then
    mkdir "$SCRIPT_DIR/$folder"
    chmod 755 "$SCRIPT_DIR/$folder"
    log $DEBUG_LEVEL $VERBOSE_INFO "Created $folder directory with permissions 755."
  fi
done

# Ensure the backup folder exists with appropriate permissions
if [ ! -d "$PATH_TO_BACKUP_FOLDER" ]; then
    log $DEBUG_LEVEL $VERBOSE_DEBUG "Creating backup folder at $PATH_TO_BACKUP_FOLDER"
    sudo mkdir -p "$PATH_TO_BACKUP_FOLDER"  # Create the directory, including any necessary parent directories
    sudo chmod 700 "$PATH_TO_BACKUP_FOLDER"  # Set permissions to 700 (owner can read, write, and execute)
    log $DEBUG_LEVEL $VERBOSE_INFO "Backup folder created with permissions set to 700"
else
    log $DEBUG_LEVEL $VERBOSE_INFO "Backup folder already exists at $PATH_TO_BACKUP_FOLDER"
fi

# NOTE Create files after creating folders ...

# HERE CREATING CSV #

# Call the Python script to generate the CSV, passing the CSV file path and nodes list
log $DEBUG_LEVEL $VERBOSE_INFO "Running Python script to generate CSV..."
python3 "$PATH_TO_BUILD_INITIAL_CSV" "$PATH_TO_CSV_NODES_INFO" "$NODES_STR"

# Check if Python script was successful
if [ $? -eq 0 ]; then
    log $DEBUG_LEVEL $VERBOSE_INFO "Python script executed successfully."
else
    log $DEBUG_LEVEL $VERBOSE_ERROR "Python script execution failed."
fi

# HERE HEADERS for .txt files  , # INFO begin with // ! #
echo "// Please, check the IP's to ensure there isn't any conflict" >> "$PATH_TO_CREDENTIALS"
#BUG IP not printing in credentials -> Failing tests at the end , why ?
echo "Node: host - IP: $(hostname -I | awk '{print $4}') - SSH_IP: None" >> "$PATH_TO_CREDENTIALS"
log $DEBUG_LEVEL $VERBOSE_INFO "Headers added to $PATH_TO_CREDENTIALS"

# Remove the "CLEARED" tag from the bin.txt file if it exists
sed -i '/CLEARED/d' "$BIN_FILE"
log $DEBUG_LEVEL $VERBOSE_INFO "Removed 'CLEARED' tag from bin.txt if it existed."

# Add the "SETTED" tag to the bin.txt file
echo "SETTED" >> "$BIN_FILE"
echo "MACHINE PROVISIONNED : 1" >> "$BIN_FILE"
log $DEBUG_LEVEL $VERBOSE_INFO "Added 'SETTED' tag to bin.txt."
