#!/bin/bash
# Typical Bash Script running in provisionning 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

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

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

# -------------------------------------------------
# HERE: Define paths and other local constants
# -------------------------------------------------

LOG_FILE="$PATH_TO_LOG_DIR/${BASENAME}.log"
initialize_log_file "$LOG_FILE"
ERROR_COUNT=0
# -------------------------------------------------
# HERE: Beginning of script
# -------------------------------------------------

# Activate SSH password configuration if not already activated
log $DEBUG_LEVEL $VERBOSE_DEBUG "Checking SSH password configuration..."
if grep -q "^PasswordAuthentication yes" /etc/ssh/sshd_config.d/60-cloudimg-settings.conf; then
    log $DEBUG_LEVEL $VERBOSE_DEBUG "SSH password configuration is already activated."
else
    log $DEBUG_LEVEL $VERBOSE_DEBUG "Activating SSH password configuration..."
    sudo sed -i 's/^#PasswordAuthentication yes/PasswordAuthentication yes/' /etc/ssh/sshd_config.d/60-cloudimg-settings.conf
    sudo sed -i 's/^PasswordAuthentication no/PasswordAuthentication yes/' /etc/ssh/sshd_config.d/60-cloudimg-settings.conf
    if [ $? -eq 0 ]; then
        log $DEBUG_LEVEL $VERBOSE_DEBUG "SSH password configuration activated successfully."
    else
        log $DEBUG_LEVEL $VERBOSE_ERROR "Failed to activate SSH password configuration."
        ERROR_COUNT=$((ERROR_COUNT + 1))
    fi
fi

# Restart SSHD service
sudo systemctl restart sshd

# -------------------------------------------------
# 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

