#!/bin/bash
# Typical Bash Script running in provisioning machine

# Get the script filename (without the path) for dynamic naming
if [[ -z "$1" ]]; then
  # If no argument is provided, use $0 to get the script name
  SCRIPT_NAME="${0##*/}"
else
  # If an argument is provided, use it as the script name
  SCRIPT_NAME="$1"
fi

BASENAME="${SCRIPT_NAME%.*}"  # Remove the file extension

# Go to root
cd /

# -------------------------------------------------
# HERE: Source necessary variables
# -------------------------------------------------

# This loads the DEBUG_LEVEL and other variables from sourcer.sh and variables.sh
source /vagrant/sourcer.sh variables.sh utils.sh

# -------------------------------------------------
# HERE: Description
# -------------------------------------------------

log $DEBUG_LEVEL $VERBOSE_INFO "Starting script execution: $SCRIPT_NAME"

# HERE: Define paths for logs and backups
LOG_FILE="$PATH_TO_LOG_DIR/${BASENAME}.log"
initialize_log_file "$LOG_FILE"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)  # Timestamp for uniqueness

# Initialize error count
ERROR_COUNT=0

# -------------------------------------------------
# HERE: Requirements & existence
# -------------------------------------------------

# Install apache & netstat
log $DEBUG_LEVEL $VERBOSE_DEBUG "Installing necessary packages..."
check_and_install_package "apache2"
check_and_install_package "netstat"

# Create logs directory if not already exists
log $DEBUG_LEVEL $VERBOSE_DEBUG "Creating logs directory..."

check_folder_existence $PATH_TO_APACHE2_DIR "tmp"
check_file_existence $PATH_TO_APACHE2_LOGS

log $DEBUG_LEVEL $VERBOSE_DEBUG "Cleaning Apache2 logs..."
# Clean the logs
> $PATH_TO_APACHE2_LOGS

# -------------------------------------------------
# HERE: Beginning of script
# -------------------------------------------------

# Starting apache
log $DEBUG_LEVEL $VERBOSE_DEBUG "Starting target server"
sudo systemctl start apache2
curl 127.0.0.1
sudo netstat -ntaup


# Configure Wazuh agent to collect Apache logs
log $DEBUG_LEVEL $VERBOSE_DEBUG "Configuring Wazuh agent to collect Apache logs..."
add_local_file "syslog" "$PATH_TO_APACHE2_LOGS"


# Restart Wazuh agent
log $DEBUG_LEVEL $VERBOSE_DEBUG "Restarting Wazuh agent..."
sudo systemctl restart wazuh-agent

# -------------------------------------------------
# End of Script
# -------------------------------------------------

if [ $ERROR_COUNT -eq 0 ]; then
    log $DEBUG_LEVEL $VERBOSE_INFO "$SCRIPT_NAME successfully realized."
else
    log $DEBUG_LEVEL $VERBOSE_INFO "Errors encountered during script execution: $SCRIPT_NAME. Total errors: $ERROR_COUNT"
fi
