#!/bin/bash

# -------------------------------------------------
# NOTE: Typical Bash Script running on host machine
# -------------------------------------------------

# HACK For debug
cd /home/koraty/Documenti/master_thesis/vagrant/

# HERE Sourcing
source logging.sh
source variables.sh
source utils.sh
# -------------------------------------------------
# -------------------------------------------------
# HERE: Beginning of script
# -------------------------------------------------
# -------------------------------------------------

# Initialize error count
ERROR_COUNT=0

# Usage: verify_conf_file.sh <remote_host> <script> <args_list>
REMOTE_HOST=$1
SCRIPT=$2
ARGS_LIST=("${@:3}")  # Capture all arguments starting from the 3rd argument onward

# Convert the array to a space-separated string if arguments are provided
if [ ${#ARGS_LIST[@]} -gt 0 ]; then
    ARGS_STRING=$(printf "%s " "${ARGS_LIST[@]}")
else
    ARGS_STRING=""  # No arguments, so ARGS_STRING is empty
fi

# Debug logs
log $DEBUG_LEVEL $VERBOSE_DEBUG "Starting verification script"
log $DEBUG_LEVEL $VERBOSE_DEBUG "Remote host: $REMOTE_HOST"
log $DEBUG_LEVEL $VERBOSE_DEBUG "Script to run: $SCRIPT"
log $DEBUG_LEVEL $VERBOSE_DEBUG "Arguments list: ${ARGS_LIST[*]}"
log $DEBUG_LEVEL $VERBOSE_DEBUG "Arguments string: $ARGS_STRING"

# Execute the shell script remotely with the arguments (if any)
if [ -z "$ARGS_STRING" ]; then
    # If no arguments, run the script without arguments
    if ! ssh "root@$REMOTE_HOST" "bash -s" < "$SCRIPT"; then
        log $DEBUG_LEVEL $VERBOSE_ERROR "SSH connection failed or script execution failed for node $REMOTE_HOST. Operation aborted."
        exit 1
    fi
else
    # Run the script with arguments
    if ! ssh "root@$REMOTE_HOST" "bash -s $ARGS_STRING" < "$SCRIPT"; then
        log $DEBUG_LEVEL $VERBOSE_ERROR "SSH connection failed or script execution failed for node $REMOTE_HOST. Operation aborted."
        exit 1
    fi
fi

