#!/bin/bash

# Define paths
ROOT_DIR="/abs"
REPO_PATH="/abs/repo_consolace"
INSTALL_PATH="/abs/ConnSolace"
CONF_PATH="$INSTALL_PATH/config"
START_SCRIPT="$INSTALL_PATH/bin/start_application.sh"
STOP_SCRIPT="$INSTALL_PATH/bin/stop_application.sh"
START_ALL_SCRIPT="/abs/StartAll.sh"
DB_SCRIPT="$INSTALL_PATH/tools/run_connsolace_scripts.sh"

# Function to add a script to StartAll.sh
add_to_start_all() {
    if ! grep -q "$1" "$START_ALL_SCRIPT"; then
        echo "### ConnSolace Start at server startup ###" >> "$START_ALL_SCRIPT"
        echo "$1" >> "$START_ALL_SCRIPT"
        echo "Added $1 to $START_ALL_SCRIPT"
    else
        echo "$1 is already present in $START_ALL_SCRIPT"
    fi
}

# Function to install ConnSolace
install_connsolace() {
mkdir $INSTALL_PATH
    if [ ! -d "$REPO_PATH" ] || [ ! -d "$INSTALL_PATH" ]; then
        echo "Required paths are missing. Check configuration."
        exit 1
    fi

    echo "Available ConnSolace versions:"
    AVAILABLE_VERSIONS=($(ls "$REPO_PATH"/*.zip | xargs -n 1 basename | sed 's/\.zip$//'))

    if [ ${#AVAILABLE_VERSIONS[@]} -eq 0 ]; then
        echo "No ConnSolace zip files found in $REPO_PATH. Exiting."
        exit 1
    fi

    for i in "${!AVAILABLE_VERSIONS[@]}"; do
        echo "$((i + 1))) ${AVAILABLE_VERSIONS[$i]}"
    done

    read -p "Enter the version to install (e.g., ConnSolace-1.0): " SELECTED_VERSION

    if [[ ! " ${AVAILABLE_VERSIONS[@]} " =~ " $SELECTED_VERSION " ]]; then
        echo "Invalid version selected. Exiting."
        exit 1
    fi

    ZIP_FILE="$REPO_PATH/$SELECTED_VERSION.zip"

    echo "Extracting $ZIP_FILE to $INSTALL_PATH..."
    if ! unzip -o "$ZIP_FILE" -d "$INSTALL_PATH"; then
        echo "Error extracting zip file. Exiting."
        exit 1
    fi

    SAMPLE_PROPERTIES="$CONF_PATH/sample_application.properties"
    APPLICATION_PROPERTIES="$CONF_PATH/application.properties"

    if [ -f "$SAMPLE_PROPERTIES" ]; then
        cp "$SAMPLE_PROPERTIES" "$APPLICATION_PROPERTIES"
        echo "Created $APPLICATION_PROPERTIES from $SAMPLE_PROPERTIES"
    else
        echo "Sample properties file not found!"
        exit 1
    fi

    echo "Please enter configuration values:"
    read -p "ConnSolace server.port(e. g. 8080): " SERVER_PORT
    read -p "ConnSolace Host (e.g. tcps://solace.internal.abslbs.com:55443): " SOLACE_HOST
    read -p "ConnSolace SOLACE_MSGVPN: " SOLACE_MSGVPN
    read -p "SOLACE_USERNAME: " SOLACE_USERNAME
    read -p "SOLACE_PASSWORD: " SOLACE_PASSWORD
    read -p "SOLACE_GROUP (e. g. queue_to_consume): " SOLACE_GROUP
    read -p "datasource.url e. g. jdbc:oracle:thin:@//abs-srv16:1521/ABSS19): " DATASOURCE_URL
    read -p "New ConnSolace Databse  user: " DATASOURCE_USERNAME
    read -p "New ConnSolace Databse  password: " DATASOURCE_PASSWORD

    sed -i "s/^server.port=.*/server.port=$SERVER_PORT/" "$APPLICATION_PROPERTIES"
    sed -i "s|^spring.cloud.stream.binders.solace.environment.solace.java.host=.*|spring.cloud.stream.binders.solace.environment.solace.java.host=$SOLACE_HOST|" "$APPLICATION_PROPERTIES"
    sed -i "s/^spring.cloud.stream.binders.solace.environment.solace.java.msgVpn=.*/spring.cloud.stream.binders.solace.environment.solace.java.msgVpn=$SOLACE_MSGVPN/" "$APPLICATION_PROPERTIES"
    sed -i "s/^spring.cloud.stream.binders.solace.environment.solace.java.clientUsername=.*/spring.cloud.stream.binders.solace.environment.solace.java.clientUsername=$SOLACE_USERNAME/" "$APPLICATION_PROPERTIES"
    sed -i "s/^spring.cloud.stream.binders.solace.environment.solace.java.clientPassword=.*/spring.cloud.stream.binders.solace.environment.solace.java.clientPassword=$SOLACE_PASSWORD/" "$APPLICATION_PROPERTIES"
    sed -i "s/^spring.cloud.stream.bindings.solaceConsumer-in-0.group=.*/spring.cloud.stream.bindings.solaceConsumer-in-0.group=$SOLACE_GROUP/" "$APPLICATION_PROPERTIES"
    sed -i "s|^spring.datasource.url=.*|spring.datasource.url=$DATASOURCE_URL|" "$APPLICATION_PROPERTIES"
    sed -i "s/^spring.datasource.username=.*/spring.datasource.username=$DATASOURCE_USERNAME/" "$APPLICATION_PROPERTIES"
    sed -i "s/^spring.datasource.password=.*/spring.datasource.password=$DATASOURCE_PASSWORD/" "$APPLICATION_PROPERTIES"

    dos2unix $INSTALL_PATH/bin/*.sh
	dos2unix $INSTALL_PATH/database_objects/*.sh
	chmod 775 $INSTALL_PATH/bin/*.sh
	chmod 775 $INSTALL_PATH/database_objects/*.sh

    if [ -f "$START_SCRIPT" ]; then
        echo "Start file exist $START_SCRIPT"
    else
        echo "Start file not found!"
        exit 1
    fi
	
    # Prompt user for manual configuration values with defaults
    read -p "ConnSolace Home Directory (default: $INSTALL_PATH): " input_ABS_SLOT
    APP_HOME=${input_ABS_SLOT:-$INSTALL_PATH}
    
    # Ensure STARTUP_SCRIPT is set correctly
    STARTUP_SCRIPT="$START_SCRIPT"
    
    # Debug: Verify the file path
    echo "Attempting to modify $STARTUP_SCRIPT"
    
    # Check if the startup script exists
    if [ ! -f "$STARTUP_SCRIPT" ]; then
        echo "Error: Startup script $STARTUP_SCRIPT not found."
        exit 1
    fi
    
    # Export the variables
    export APP_HOME
    
    # Update the STARTUP_SCRIPT with the new values using sed
    sed -i "s|^APP_HOME=.*|APP_HOME=$APP_HOME|" "$STARTUP_SCRIPT"
    
    # Confirm changes
    echo "Updated $STARTUP_SCRIPT with APP_HOME=$APP_HOME and JAVA_HOME=$JAVA_HOME"

    echo "Installation and configuration complete."
	read -p "Press enter to continue"
	# Add to OS startup after install if it is not added
	add_to_start_all "$START_SCRIPT"
	read -p "Press enter to continue"
	return
}

# Function to run database scripts
run_database_scripts() {
    if [ -f "$DB_SCRIPT" ]; then
        echo "Running database scripts..."
        if ! bash "$DB_SCRIPT"; then
            echo "Error running database scripts."
        fi
    else
        echo "Database script not found!"
    fi
	read -p "Press enter to continue"
	return
}

# Function to start ConnSolace
start_connsolace() {
    echo "Running $START_SCRIPT..."
    if ! bash "$START_SCRIPT"; then
        echo "Error starting ConnSolace."
        exit 1
    fi
	read -p "Press enter to continue"
	return
}

# Function to stop ConnSolace
stop_connsolace() {
    echo "Running $STOP_SCRIPT..."
    if ! bash "$STOP_SCRIPT"; then
        echo "Error stoping ConnSolace."
        return
    fi
	read -p "Press enter to continue"
	return
}

############################################
# Menu options
############################################
show_menu() {
echo " ----------------------------------------------------------------------------------"
echo -e "| ConnSolace isntallation for Linux -\e[92m script version 1.0 \e[0m                          |"
echo "| Select in order what you want to install:                                        |"
echo "| Install the application where you will have the application structure            |"
echo "| Run the ConnSolace Scripts to create or update the -ABSSOLUTE_JSM- Database User |"
echo "| Stop/Start and restart the Serives                                               |"
echo "| Application require java directory                                               |"
echo " ---------------------------------------------------------------------------------- "
    echo "Please select an option:"
	echo
    echo "1. Install ConnSolace"
    echo "2. Run Database Scripts"
	echo
    echo "3. Start ConnSolace"
	echo "4. Stop ConnSolace"
	echo "5. Restart ConnSolace"
	echo
    echo "0. Quit"
  echo "-------------------------------"
  read -p "Choose an option [1-5] 0 to exit: " choice

    case $choice in
    1)
        install_connsolace
        ;;
    2)
        run_database_scripts
        ;;
    3)
        start_connsolace
        ;;
	4)
        stop_connsolace
        ;;
    5)
        stop_connsolace
		start_connsolace
        ;;
    0)
      echo "Exiting..."
      exit 0
      ;;
    *)
      echo "Invalid option!"
      ;;
  esac
}

# Loop the menu until the user chooses to exit
while true; do
  clear
  show_menu
done

