#TOREMOVE 
#!/usr/bin/bash
# NOTE Can be run outside a vagrant up, just to synchronize the .conf files
# NOTE UNDER a CRON JOB : Check log file to ensure it is running.
# TOHAVE a folder with files to push and a paths.txt file that will allow a source-destination in one line

# Change the working directory to the root directory
cd /

# Source the sourcer.sh file with specific arguments
source /vagrant/sourcer.sh variables.sh

# Define log directory and log file
LOG_FILE="$PATH_TO_LOG_DIR/config_manager.log"

# DESCRIPTION #
log $DEBUG_LEVEL $VERBOSE_INFO "Configuring manager ..."

# Log that the script was launched by a cron job
echo "$(date +"%Y-%m-%d %H:%M:%S") - Script launched by cron job" >> "/vagrant/$LOG_FILE"

# Initialize error flag
error_occurred=0

## HERE .conf files to push in correct location ##

# agent.conf files #
cd ../
# Define the source and destination paths using relative paths
SOURCE_PATH="vagrant/VM/configs/manager/conf/default/agent.conf"
DESTINATION_PATH="/var/ossec/etc/shared/default/agent.conf"

# Create the destination directory if it doesn't exist
sudo mkdir -p "$(dirname "$DESTINATION_PATH")"

# Copy the agent.conf file to the destination
sudo cp "$SOURCE_PATH" "$DESTINATION_PATH"
if [ $? -ne 0 ]; then
  log $DEBUG_LEVEL $VERBOSE_ERROR "Failed to copy agent.conf to $DESTINATION_PATH" >> "$LOG_FILE"
  error_occurred=1
fi

sudo chmod 640 "$DESTINATION_PATH"
if [ $? -ne 0 ]; then
  log $DEBUG_LEVEL $VERBOSE_ERROR "Failed to change permissions of agent.conf" >> "$LOG_FILE"
  error_occurred=1
fi

# Check if any errors occurred and decide what to do
if [ $error_occurred -eq 1 ]; then
  log $DEBUG_LEVEL $VERBOSE_ERROR "One or more errors occurred. - see at $LOG_FILE" 
  exit 0
else 
  log $DEBUG_LEVEL $VERBOSE_INFO "Successfully copied and set permissions for agent.conf - see at $LOG_FILE"
fi
