#!/bin/bash

#TOTEST : OK until suricat-update, but after not sure that the yaml file is correctly modified
#TODO Use a shared yaml file configuration
# Source the sourcer.sh file with specific arguments
source /vagrant/sourcer.sh variables.sh
# DESCRIPTION #
log $DEBUG_LEVEL $VERBOSE_INFO "Configuring the agent ..."
## HERE Configuration scripts for agents ##
# Initialize error flag
error_occurred=0

# Update before installing
sudo apt-get update
# Install Suricata
sudo add-apt-repository ppa:oisf/suricata-stable
if [ $? -ne 0 ]; then
  log $DEBUG_LEVEL $VERBOSE_ERROR "Failed to add Suricata repository"
  error_occurred=1
fi

sudo apt-get update
if [ $? -ne 0 ]; then
  log $DEBUG_LEVEL $VERBOSE_ERROR "Failed to update package list"
  error_occurred=1
fi

sudo apt-get install suricata -y
if [ $? -ne 0 ]; then
  log $DEBUG_LEVEL $VERBOSE_ERROR "Failed to install Suricata"
  error_occurred=1
fi

# Update Suricata rules
sudo suricata-update
if [ $? -ne 0 ]; then
  log $DEBUG_LEVEL $VERBOSE_ERROR "Failed to update Suricata rules"
  error_occurred=1
fi

# Define the source and destination paths for suricata.yml
SOURCE_PATH=$PATH_TO_SURICATA_YML
DESTINATION_PATH=$PATH_TO_VM_SURICATA_YML
SIGNATURES_PATH=$PATH_TO_VM_SURICATA_SIGNATURES
# Create the destination directory if it doesn't exist
sudo mkdir -p $(dirname $DESTINATION_PATH)

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

sudo chmod 644 $DESTINATION_PATH
if [ $? -ne 0 ]; then
  log $DEBUG_LEVEL $VERBOSE_ERROR "Failed to change permissions of suricata.yml"
  error_occurred=1
fi

#DRAFT Need signatures to work
# Test Suricata with the new configuration
# sudo suricata -c $DESTINATION_PATH -s $SIGNATURES_PATH -i $NETWORK_INTERFACE
# if [ $? -ne 0 ]; then
#   log $DEBUG_LEVEL $VERBOSE_ERROR "Failed to test Suricata with the new configuration"
#   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 in Suricata installation."
  return 1
else
  log $DEBUG_LEVEL $VERBOSE_INFO "Successfully installed, updated, and tested Suricata with the new configuration"
fi
