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

# Get the script filename (without the path) for dynamic naming
if [[ -z "$1" ]]; then
  SCRIPT_NAME="${0##*/}"
else
  SCRIPT_NAME="$1"
fi
BASENAME="yara_setup"  # Remove the file extension

# Go to root
cd /

# -------------------------------------------------
# HERE: Source necessary variables
# -------------------------------------------------
source /vagrant/sourcer.sh variables.sh

# -------------------------------------------------
# HERE: Define paths and other local constants
# -------------------------------------------------
LOG_FILE="$PATH_TO_LOG_DIR/${BASENAME}.log"
initialize_log_file "$LOG_FILE"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="$PATH_TO_BACKUP_FOLDER/${BASENAME}_$TIMESTAMP.bak"
ERROR_COUNT=0
YARA_DIR="/usr/local/bin/yara-4.2.3/"
YARA_ARCHIVE="v4.2.3.tar.gz"
YARA_RULES_FILE= $PATH_TO_YARA_RULES

log $DEBUG_LEVEL $VERBOSE_INFO "Starting script execution: $SCRIPT_NAME"
log $DEBUG_LEVEL $VERBOSE_DEBUG "Checking if YARA is already installed..."

# Check if YARA is already installed
if command -v yara >/dev/null 2>&1; then
    log $DEBUG_LEVEL $VERBOSE_DEBUG "YARA is already installed. Checking for rules..."

    # Check if YARA rules file is present
    if [ -f "$YARA_RULES_FILE" ]; then
        log $DEBUG_LEVEL $VERBOSE_DEBUG "YARA rules already exist. Skipping installation."
        exit 0
    else
        log $DEBUG_LEVEL $VERBOSE_INFO "YARA rules not found. Proceeding to download rules..."
    fi
else
    log $DEBUG_LEVEL $VERBOSE_INFO "YARA not found. Proceeding with installation."
fi

# -------------------------------------------------
# Begin YARA Installation
# -------------------------------------------------

# Cleanup function
cleanup() {
    log $DEBUG_LEVEL $VERBOSE_DEBUG "Cleaning up residual files from failed installation..."
    
    sudo rm -f /usr/local/bin/yara /usr/local/bin/yara* /usr/local/lib/libyara* && \
    sudo rm -rf /tmp/yara /usr/local/include/yara && \
    sudo rm -f /usr/local/bin/v4.2.3.tar.gz /var/ossec/active-response/bin/yara.sh && \
    sudo ldconfig
    sudo rm -rf /usr/local/bin/yara-4.2.3

    log $DEBUG_LEVEL $VERBOSE_DEBUG "Cleanup completed."
    exit 1
}

log $DEBUG_LEVEL $VERBOSE_DEBUG "Updating package lists..."
sudo apt update >> "$LOG_FILE" 2>&1

log $DEBUG_LEVEL $VERBOSE_DEBUG "Installing required dependencies..."
sudo apt install -y make gcc autoconf libtool libssl-dev pkg-config jq curl >> "$LOG_FILE" 2>&1

log $DEBUG_LEVEL $VERBOSE_DEBUG "Downloading YARA source code..."
sudo curl -LO https://github.com/VirusTotal/yara/archive/$YARA_ARCHIVE >> "$LOG_FILE" 2>&1

log $DEBUG_LEVEL $VERBOSE_DEBUG "Extracting YARA archive..."
sudo tar -xvzf $YARA_ARCHIVE -C /usr/local/bin/ >> "$LOG_FILE" 2>&1 && rm -f $YARA_ARCHIVE

if [ ! -d "$YARA_DIR" ]; then
    log $DEBUG_LEVEL $VERBOSE_ERROR "YARA extraction failed. Aborting installation."
    exit 1
fi

log $DEBUG_LEVEL $VERBOSE_DEBUG "Starting YARA build process..."

cd $YARA_DIR || {
    log $DEBUG_LEVEL $VERBOSE_ERROR "Failed to navigate to YARA source directory."
    exit 1
}

# Execute all sudo commands in a loop
for cmd in "./bootstrap.sh" "./configure" "make" "make install" "make check"; do
    log $DEBUG_LEVEL $VERBOSE_DEBUG "Running: $cmd"
    sudo $cmd >> "$LOG_FILE" 2>&1
    if [ $? -ne 0 ]; then
        log $DEBUG_LEVEL $VERBOSE_ERROR "Command failed: $cmd"
        exit 1
    fi
done

log $DEBUG_LEVEL $VERBOSE_INFO "YARA build process completed successfully."

# Check if libyara.so.9 is found
if ! ldconfig -p | grep libyara.so.9 >/dev/null 2>&1; then
    log $DEBUG_LEVEL $VERBOSE_ERROR "libyara.so.9 not found. Adding /usr/local/lib to /etc/ld.so.conf."
    sudo sh -c "echo '/usr/local/lib' >> /etc/ld.so.conf"
    sudo ldconfig >> "$LOG_FILE" 2>&1
else
    log $DEBUG_LEVEL $VERBOSE_DEBUG "libyara.so.9 found."
fi

# Verify YARA installation
log $DEBUG_LEVEL $VERBOSE_DEBUG "Verifying YARA installation..."
if yara --version >/dev/null 2>&1; then
    log $DEBUG_LEVEL $VERBOSE_DEBUG "YARA installed successfully. Version: $(yara --version)"
else
    log $DEBUG_LEVEL $VERBOSE_ERROR "YARA installation failed."
    ERROR_COUNT=$((ERROR_COUNT + 1))
    cleanup
fi

# Download YARA detection rules
log $DEBUG_LEVEL $VERBOSE_DEBUG "Downloading YARA detection rules..."
sudo mkdir -p /tmp/yara/rules
sudo curl 'https://valhalla.nextron-systems.com/api/v1/get' \
-H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' \
-H 'Accept-Language: en-US,en;q=0.5' \
--compressed \
-H 'Referer: https://valhalla.nextron-systems.com/' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-H 'DNT: 1' -H 'Connection: keep-alive' -H 'Upgrade-Insecure-Requests: 1' \
--data 'demo=demo&apikey=1111111111111111111111111111111111111111111111111111111111111111&format=text' \
-o "$YARA_RULES_FILE" >> "$LOG_FILE" 2>&1

if [ $? -eq 0 ]; then
    log $DEBUG_LEVEL $VERBOSE_INFO "YARA rules downloaded successfully."
else
    log $DEBUG_LEVEL $VERBOSE_ERROR "Failed to download YARA rules."
    ERROR_COUNT=$((ERROR_COUNT + 1))
    cleanup
fi

log $DEBUG_LEVEL $VERBOSE_DEBUG "Copying yara.sh file to the correct location..."
sudo cp "$PATH_TO_YARA_SCRIPT" /var/ossec/active-response/bin/
sudo chmod +x /var/ossec/active-response/bin/$(basename "$PATH_TO_YARA_SCRIPT")

log $DEBUG_LEVEL $VERBOSE_DEBUG "Changing yara.sh ownership and permissions..."
sudo chown root:wazuh /var/ossec/active-response/bin/yara.sh
sudo chmod 750 /var/ossec/active-response/bin/yara.sh

# -------------------------------------------------
# End of Script
# -------------------------------------------------
if [ $ERROR_COUNT -eq 0 ]; then
    log $DEBUG_LEVEL $VERBOSE_DEBUG "$SCRIPT_NAME completed successfully."
else
    log $DEBUG_LEVEL $VERBOSE_ERROR "Errors encountered during script execution: $SCRIPT_NAME. Total errors: $ERROR_COUNT"
    cleanup
fi
