#!/bin/bash
###############################################################################################
# Created by CVI                                                                              #
# Version 1.2 Nginx Deploy ment script for infinity                                           #
# - support Nginx deploiment from sources                                                     #
# - suport Infinity deployment 10.4.0 +                                                       #
# - Slots in use 5xx90 - nginx(https) 5xx91 Infinity(http) Infinity 5xx92 Infinity (https)    #
# - Custom certificate update for the local installation                                      #
# - TS-1036 Replace name of Infinity application (from abs to infinity) - maintain both names #
#                                                                                             #
###############################################################################################
# Define variables
NGINX_VERSION=1.28.0  # Replace with the desired version
# Set the home directory
export HOME=/abs 
# Prompt the user to enter the application slot number
echo -n "Enter the Application Slot number (e.g.:01...99): "
read input_ABS_SLOT
# Use the input or default to 01 if no input is provided
export ABS_SLOT=${input_ABS_SLOT:-01}
# Set the installation directory
export INSTALL_DIR=$HOME/$ABS_SLOT/nginx_infinity
# Display the installation directory
echo "You are now on the $INSTALL_DIR Slot"
export HOST=$(hostname)
WORKER_PROCESSES=1

# Default port values for the single instance
NGX_HTTPS_PORT=50190  # HTTP port for the instance
HTTP_PORT=50191       # HTTP port for the instance
HTTPS_PORT=50192      # HTTPS port for the instance

# System dependencies (for reference, they are commented out)
select_slot() {
# Prompt the user to enter the application slot number
echo -n "Enter the Application Slot number (e.g.:01...99): "
read input_ABS_SLOT
# Use the input or default to 01 if no input is provided
export ABS_SLOT=${input_ABS_SLOT:-01}
# Set the installation directory
export INSTALL_DIR=$HOME/$ABS_SLOT/nginx_infinity
# Display the installation directory
echo "You are now on the $INSTALL_DIR Slot"
read -p "Press enter to continue"
}
############################################
# Function to compare versions and cleanup/uninstall
############################################
clean_oldversion() {
    BACKUP_DIR="$HOME/tmp/nginx-backup_slot$ABS_SLOT"
    read -p "This will update and backup to $BACKUP_DIR the nginx to latest version:$NGINX_VERSION"

    # Get the currently installed NGINX version (if installed)
    if [ -x "${INSTALL_DIR}/sbin/nginx" ]; then
        INSTALLED_NGINX_VERSION=$($INSTALL_DIR/sbin/nginx -v 2>&1 | grep -o '[0-9.]*')
        echo "Currently installed NGINX version: $INSTALLED_NGINX_VERSION"
    else
        INSTALLED_NGINX_VERSION="0"
        echo "No NGINX installation detected."
    fi

    # Debugging output
    echo "Installed NGINX version: $INSTALLED_NGINX_VERSION"
    echo "New NGINX version: $NGINX_VERSION"

    # Compare installed version with the new version
    if [ "$(printf '%s\n' "$NGINX_VERSION" "$INSTALLED_NGINX_VERSION" | sort -V | head -n1)" != "$NGINX_VERSION" ]; then
        echo "New version available. Backing up and removing the old installation..."
        # Stop the NGINX service (if running)
        stop_nginx_infinity

        # Create backup directory
        echo "Backing up current NGINX installation to $BACKUP_DIR..."
		rm -rf $BACKUP_DIR
        mkdir -p $BACKUP_DIR
        cp -r $INSTALL_DIR/* $BACKUP_DIR/ || { echo "Backup failed. Exiting."; return 1; }

        # Delete the current installation
        echo "Deleting the current NGINX installation..."
        rm -rf $INSTALL_DIR || { echo "Failed to remove NGINX. Exiting."; return 1; }

        echo "Backup and removal complete. Proceed with new installation."
    else
        echo "NGINX is already up-to-date (version $INSTALLED_NGINX_VERSION)."
		read -p "Press enter to continue"
		exit 1
    fi	
}

############################################
# System dependencies (for reference, they are commented out)
############################################
install_dependencies() {
  echo "---------------------------------------------------------------------------------"
  echo "-           💻OS: Oracle Enterprise Linux 8 (OEL8)                              -"
  echo "- To install necessary OS package dependencies for NGINX on OEL8                -" 
  echo "-uncomment the following commands or run as root the last line:                 -"
  echo "-Dependencies required: gcc, make, openssl-devel, zlib-devel, pcre, pcre-devel  -"
  echo -e "\e[31m- sudo dnf -y install gcc make openssl-devel zlib-devel pcre pcre-devel         -\e[0m"
  echo "---------------------------------------------------------------------------------"
  # Uncomment the lines below to install dependencies if sudo access is granted
  # sudo dnf -y install gcc make openssl-devel zlib-devel pcre pcre-devel
  
}
############################################
# Reinstallation of existing NginX software - this will remove the old installation
############################################
clean_reinstall() {
  stop_nginx_infinity
  echo "Cleaning up old NGINX version..."
  rm -rf $INSTALL_DIR
  echo "Old NGINX version cleaned up."
  read -p "Press enter to continue"
}

############################################
# Function to download, build, and install NGINX from source with common modules
############################################
install_nginx_from_source() {
  if [ -d "$INSTALL_DIR" ]; then
    read -p "NGINX is already installed. Do you want to reinstall? (yes/no): " choice
    if [ "$choice" != "yes" ]; then
      echo "NGINX installation was not modified."
	  read -p "Press enter to continue"
      exit 1
    else
      clean_reinstall
    fi
  fi
  
  echo "Downloading and Installing NGINX version $NGINX_VERSION..."
  cd $HOME/tmp
  wget https://nginx.org/download/nginx-$NGINX_VERSION.tar.gz
  tar -zxvf nginx-$NGINX_VERSION.tar.gz

  echo "Building NGINX with commonly used modules..."
  cd nginx-$NGINX_VERSION
  ./configure --prefix=$INSTALL_DIR \
    --with-http_ssl_module \
	--with-http_stub_status_module \
    --with-http_v2_module \
	--with-pcre \
    --with-http_secure_link_module \

  make
  make install

    # Clean up downloaded file after installation
    echo "Cleaning up downloaded files..."
    rm -rf $HOME/tmp/nginx-${NGINX_VERSION}*
}	
############################################
# Function to generate self-signed SSL certificates
############################################
generate_ssl_certificates() {
  SSL_DIR=$INSTALL_DIR/ssl
  
# Define the original strings, where 'xx' is the placeholder for the slot
PORT="5xx90"
PORT2="5xx93"
# Replace 'xx' with the provided slot value
NGX_HTTPS_PORT="${PORT//xx/$ABS_SLOT}"
MON_HTTP_PORT="${PORT2//xx/$ABS_SLOT}"
# Print the updated strings
echo "Updated HTTPS: $NGX_HTTPS_PORT"
echo "Updated HTTP: $MON_HTTP_PORT"

# Display the HTTPS port
echo "NGINX will use HTTPS port: $NGX_HTTPS_PORT"
# Display the HTTP STATUS port
echo "NGINX STATUS will use HTTP port: $MON_HTTP_PORT"


  echo "Generating self-signed SSL certificates for NGINX..."
  mkdir -p $SSL_DIR
  openssl req -x509 -nodes -days 3650 -newkey rsa:2048 \
    -keyout $SSL_DIR/nginx_infinity.key \
    -out $SSL_DIR/nginx_infinity.crt \
    -subj "/CN=localhost"
}

############################################
# Function to configure NGINX instance with HTTP and HTTPS
############################################
configure_nginx_infinity() {
  echo "Configuring NGINX instance to listen on HTTPS port $NGX_HTTPS_PORT..."
  mkdir -p $INSTALL_DIR/conf $INSTALL_DIR/html

  cat > $INSTALL_DIR/conf/nginx.conf <<EOF
worker_processes $WORKER_PROCESSES;

events {
    worker_connections 1024;
}
http {
	
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  $INSTALL_DIR/logs/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    keepalive_timeout   65;
    types_hash_max_size 4096;
	
	include       mime.types;
    default_type  application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include $INSTALL_DIR/conf.d/*.conf;
	
    server {
        listen $NGX_HTTPS_PORT ssl;
        server_name $HOST;

        ssl_certificate $INSTALL_DIR/ssl/nginx_infinity.crt;
        ssl_certificate_key $INSTALL_DIR/ssl/nginx_infinity.key;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-CHACHA20-POLY1305";
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_prefer_server_ciphers on;

        location / {
            root $INSTALL_DIR/html;
            index index.html;
        }
    }
}
EOF

  echo "Creating test index.html for NGINX instance on port $NGX_HTTPS_PORT..."
  cat > $INSTALL_DIR/html/index.html <<EOF
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
        <head>
                <title>Test Page for the HTTP Server on Oracle Linux</title>
                <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
                <style type="text/css">
                        /*<![CDATA[*/
                        body {
                                background-color: #fff;
                                color: #000;
                                font-size: 0.9em;
                                font-family: sans-serif,helvetica;
                                margin: 0;
                                padding: 0;
                        }
                        :link {
                                color: #c00;
                        }
                        :visited {
                                color: #c00;
                        }
                        a:hover {
                                color: #f50;
                        }
                        h1 {
                                text-align: center;
                                margin: 0;
                                padding: 0.6em 2em 0.4em;
                                background-color: #900;
                                color: #fff;
                                font-weight: normal;
                                font-size: 1.75em;
                                border-bottom: 2px solid #000;
                        }
                        h1 strong {
                                font-weight: bold;
                        }
                        h2 {
                                font-size: 1.1em;
                                font-weight: bold;
                        }
                        hr {
                                display: none;
                        }
                        .content {
                                padding: 1em 5em;
                        }
                        .content-columns {
                                /* Setting relative positioning allows for
                                absolute positioning for sub-classes */
                                position: relative;
                                padding-top: 1em;
                        }
                        .content-column-left {
                                /* Value for IE/Win; will be overwritten for other browsers */
                                width: 47%;
                                padding-right: 3%;
                                float: left;
                                padding-bottom: 2em;
                        }
                        .content-column-left hr {
                                display: none;
                        }
                        .content-column-right {
                                /* Values for IE/Win; will be overwritten for other browsers */
                                width: 47%;
                                padding-left: 3%;
                                float: left;
                                padding-bottom: 2em;
                        }
                        .content-columns>.content-column-left, .content-columns>.content-column-right {
                                /* Non-IE/Win */
                        }
                        .logos {
                                text-align: center;
                                margin-top: 2em;
                        }
                        img {
                                border: 2px solid #fff;
                                padding: 2px;
                                margin: 2px;
                        }
                        a:hover img {
                                border: 2px solid #f50;
                        }
                        /*]]>*/
                </style>
        </head>

        <body>
                <h1>Oracle Linux <strong>Test Page</strong></h1>

                <div class="content">
                        <div class="content-middle">
                                <p>This page is used to test the proper operation of the HTTP server after it has been installed. If you can read this page, it means that the HTTP server installed at this site is working properly.</p>
                        </div>
                        <hr />

                        <div class="content-columns">
                                <div class="content-column-left">
                                        <h2>If you are a member of the general public:</h2>

                                        <p>The fact that you are seeing this page indicates that the website you just visited is either experiencing problems, or is undergoing routine maintenance.</p>

                                        <p>If you would like to let the administrators of this website know that you've seen this page instead of the page you expected, you should send them e-mail. In general, mail sent to the name "webmaster" and directed to the website's domain should reach the appropriate person.</p>

                                        <p>For example, if you experienced problems while visiting www.example.com, you should send e-mail to "webmaster@example.com".</p>

                                        <p>For information on Oracle Linux, please visit the <a href="https://www.oracle.com/linux/">Oracle Linux website</a>. The documentation for Oracle Linux is <a href="https://docs.oracle.com/en/operating-systems/oracle-linux/">available on the Oracle Docs website</a>.</p>
                                        <hr />
                                </div>

                                <div class="content-column-right">
                                        <h2>If you are the website administrator:</h2>

                                        <p>You may now add content to the webroot directory. Note
                                        that until you do so, people visiting your website will see
                                        this page, and not your content.</p>

                                        <p>For systems using the Apache HTTP Server:
                                        You may now add content to the directory <tt>/var/www/html/</tt>. Note that until you do so, people visiting your website will see this page, and not your content. To prevent this page from ever being used, follow the instructions in the file <tt>/etc/httpd/conf.d/welcome.conf</tt>.</p>

                                        <p>For systems using NGINX:
                                        You should now put your content in a location of your
                                        choice and edit the <code>root</code> configuration directive
                                        in the <strong>nginx</strong> configuration file
                                        <code>/etc/nginx/nginx.conf</code>.</p>

                                        <div class="logos">
                                                <a href="https://www.oracle.com/linux/"><img src= "/icons/poweredby.png" alt="[ Powered by Oracle Linux ]" /></a>
                                                <img src= "poweredby.png" alt="[ Powered by Oracle Linux ]" />
                                        </div>
                                </div>
                        </div>
                </div>
        </body>
</html>
EOF
   
   mkdir -p $INSTALL_DIR/conf.d
   
   SERVER_IP="$(hostname -I | awk '{print $1}')"
   echo Server IP is: $SERVER_IP Hostname is: $HOST	

  cat > $INSTALL_DIR/conf.d/stub_status.conf <<EOF
server {
    listen $MON_HTTP_PORT;
    server_name $HOST;
    location /nginx_status {
        stub_status on;
        access_log off;
        allow $SERVER_IP;
        deny all;
        }
        location = /basic_status {
            stub_status;
            allow $SERVER_IP;
            allow ::1;
            deny all;
        }
}
EOF

   cp $INSTALL_DIR/html/50x.html $INSTALL_DIR/html/404.html
}

############################################
# Function to add the NginX Infinity in startAll.sh
############################################
startAll_nginx_infinity() {
    if [ -z "$ABS_SLOT" ]; then
        echo "Error: ABS_SLOT is not set."
        return 1
    fi

    local start_file="/abs/startAll.sh"

    if [ -f "$start_file" ]; then
        # Check if the lines are already present
        if ! grep -q "# Startup NginX Infinity on slot $ABS_SLOT" "$start_file" || \
           ! grep -q "/abs/$ABS_SLOT/nginx_infinity/sbin/nginx" "$start_file"; then

            # Ensure the file ends with a newline before appending
            awk 'NF {p=1} END {if (p) print ""}' "$start_file" >> "$start_file"

            {
                echo "# Startup NginX Infinity on slot $ABS_SLOT"
                echo "/abs/$ABS_SLOT/nginx_infinity/sbin/nginx"
            } >> "$start_file"

            echo "Startup NginX Infinity on slot $ABS_SLOT was added to $start_file."
        else
            echo "The slot $ABS_SLOT is already set to start in $start_file."
        fi
    else
        echo "Error: $start_file does not exist."
        return 1
    fi
}

############################################
# Function to deploy the application version
############################################
deploy_application() {
    echo "📂 Deploying abs_infinity application version..."

    REPO_PATH="$HOME/repo_infinity"
    echo "📦 All available versions in $REPO_PATH:"

    # Find and list all available .zip files matching abs_v.* or infinity_v.*
    for file in "$REPO_PATH"/*_v.*.zip; do
        [[ -e "$file" ]] || continue
        BASE_FILE=$(basename "$file")
        vers=$(echo "$BASE_FILE" | grep -oP '\d+(\.\d+)+')
		echo -e " \e[33m🗂️ Version: → $vers\e[0m"
    done

    echo
    read -p "🔢 Enter the version of the application to deploy (e.g., 10.0.0): " APP_VERSION

    # Try both zip patterns
    ZIP_ABS="$REPO_PATH/abs_v.$APP_VERSION.zip"
    ZIP_INFINITY="$REPO_PATH/infinity_v.$APP_VERSION.zip"

    if [[ -f "$ZIP_ABS" ]]; then
        APP_ZIP="$ZIP_ABS"
        echo "📎 Using archive: $(basename "$APP_ZIP")"
    elif [[ -f "$ZIP_INFINITY" ]]; then
        APP_ZIP="$ZIP_INFINITY"
        echo "📎 Using archive: $(basename "$APP_ZIP")"
    else
        echo "❌ Error: No zip archive found for version $APP_VERSION in $REPO_PATH"
        return 1
    fi

    DEPLOY_DIR="$INSTALL_DIR/html"
    mkdir -p "$DEPLOY_DIR"

    echo "🧹 Cleaning old application files from $DEPLOY_DIR/apps..."
    rm -rf "$DEPLOY_DIR/apps"

    echo "📦 Extracting $APP_ZIP to $DEPLOY_DIR..."
    unzip -o "$APP_ZIP" -d "$DEPLOY_DIR"

    echo "✅ Deployment files extracted successfully!"
}

############################################
# Function to configure the application
############################################
config_application() {
    # Detect the correct app structure
    if [[ -d "$DEPLOY_DIR/apps/abs-root" ]]; then
        APP_NAME="abs"
        APP_DIR="abs-root"
        CONFIG_BASENAME="absConfig.json"
        SAMPLE_BASENAME="sample_absConfig.json"
    elif [[ -d "$DEPLOY_DIR/apps/infinity-root" ]]; then
        APP_NAME="infinity"
        APP_DIR="infinity-root"
        CONFIG_BASENAME="infinityConfig.json"
        SAMPLE_BASENAME="sample_infinityConfig.json"
    else
        echo "❌ Error: Neither abs-root nor infinity-root found in $DEPLOY_DIR/apps/"
        exit 1
    fi

    CONFIG_DIR="$DEPLOY_DIR/apps/$APP_DIR/assets/general/config"
    SAMPLE_CONFIG="$CONFIG_DIR/$SAMPLE_BASENAME"
    ABS_CONFIG="$CONFIG_DIR/$CONFIG_BASENAME"

    # 🔧 Port config
    PORT1="5xx91"
    PORT2="5xx92"
    PORT3="5xx90"
    HTTP_PORT="${PORT1//xx/$ABS_SLOT}"
    HTTPS_PORT="${PORT2//xx/$ABS_SLOT}"
    NGX_HTTPS_PORT="${PORT3//xx/$ABS_SLOT}"

    echo "📦 Using structure: $APP_DIR"
    echo "🌐 HTTP port: $HTTP_PORT | 🔐 HTTPS port: $HTTPS_PORT | 🌍 NGINX HTTPS: $NGX_HTTPS_PORT"

    if [[ ! -f "$SAMPLE_CONFIG" ]]; then
        echo "❌ Error: Sample config file $SAMPLE_CONFIG not found!"
        read -p "Press enter to continue"
        return 1
    fi

    cp "$SAMPLE_CONFIG" "$ABS_CONFIG"
    echo "📄 Copied sample config to active config: $CONFIG_BASENAME"
	
    read -p "🔗 Enter the new URL to replace in $CONFIG_BASENAME (default: https://abs.abssolute.net): " NEW_URL
    NEW_URL=${NEW_URL:-https://abs.abssolute.net}

    sed -i -E "s#\"http://[^\"]*\"#\"$NEW_URL\"#g; s#\"https://[^\"]*\"#\"$NEW_URL\"#g" "$ABS_CONFIG"
    echo "✅ Updated URL references to: $NEW_URL"
	 
    read -p "🛡️ Enable peripheralAgentSecureConnection? (true/false, leave empty to keep current): " SECURE_CONNECTION
    if [[ -n "$SECURE_CONNECTION" ]]; then
        sed -i -E "s#(\"peripheralAgentSecureConnection\"\s*:\s*)(true|false)#\1$SECURE_CONNECTION#g" "$ABS_CONFIG"
        echo "🔐 Updated peripheralAgentSecureConnection to $SECURE_CONNECTION."
    else
        echo "ℹ️ No changes made to peripheralAgentSecureConnection."
    fi

    echo "✅ Deployment of ${APP_NAME}_infinity version $APP_VERSION completed."
    read -p "Press enter to continue"

    SERVER_IP="$(hostname -I | awk '{print $1}')"
    echo "🖥️ Server IP: $SERVER_IP | 🏷️ Hostname: $HOST"

    mkdir -p "$INSTALL_DIR/conf.d"

    # Generate unified NGINX config (no matter the app name, always reference $APP_DIR)
    cat > "$INSTALL_DIR/conf.d/absinfinity_$ABS_SLOT.conf" <<EOF
server {
  listen       $HTTPS_PORT ssl;
  server_name  $HOST,$SERVER_IP;

  ssl_certificate $INSTALL_DIR/ssl/nginx_infinity.crt;
  ssl_certificate_key $INSTALL_DIR/ssl/nginx_infinity.key;

  ssl_protocols TLSv1.2 TLSv1.3;
  ssl_ciphers "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-CHACHA20-POLY1305";
  ssl_session_cache shared:SSL:10m;
  ssl_session_timeout 10m;
  ssl_prefer_server_ciphers on;

  location / {
    root        $INSTALL_DIR/html/apps/$APP_DIR;
    try_files \$uri \$uri/ /index.html\$is_args\$args;
    index       index.html index.htm;
    expires     -1;
    add_header  Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
  }
}

server {
  listen       $HTTP_PORT;
  server_name  $HOST,$SERVER_IP;

  location / {
    root        $INSTALL_DIR/html/apps/$APP_DIR;
    try_files \$uri \$uri/ /index.html\$is_args\$args;
    index       index.html index.htm;
    expires     -1;
    add_header  Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
  }
}
EOF

    # NGINX reload
    NGINX_PATH="$INSTALL_DIR/sbin/nginx"
    if [[ -f "$NGINX_PATH" ]]; then
        echo "🧪 Testing NGINX config..."
        $NGINX_PATH -t
        read -p "🔁 Press enter to continue"
        echo "🔄 Reloading NGINX..."
        $NGINX_PATH -s reload
        echo "🚀 NGINX and $APP_NAME loaded successfully"
    else
        echo "❌ Error: NGINX not found at $NGINX_PATH"
        exit 1
    fi

    echo "✅ Deployment complete!"
}

############################################
# Function to configure the application localy
############################################
config_application_local() {
    read -p "Enter the first application server (e.g., oci-ams.internal.com:50117): " APPServer1
    read -p "Enter the second application server (or leave blank if not present): " APPServer2
    [[ -z "$APPServer2" ]] && APPServer2="$APPServer1"

    PORT1="5xx91"
    PORT2="5xx92"
    PORT3="5xx90"
    PORT1="${PORT1/xx/$ABS_SLOT}"
    PORT2="${PORT2/xx/$ABS_SLOT}"
    PORT3="${PORT3/xx/$ABS_SLOT}"

    HTTP_PORT="$PORT1"
    HTTPS_PORT="$PORT2"
    NGX_HTTPS_PORT="$PORT3"

    echo "🌐 Updated HTTP port: $HTTP_PORT"
    echo "🔐 Updated HTTPS port: $HTTPS_PORT"
    echo "🧭 NGINX will use HTTPS port: $NGX_HTTPS_PORT"

    # 🔍 Try to find abs-root or infinity-root
    ABS_PATH="$DEPLOY_DIR/apps/abs-root/assets/general/config"
    INFINITY_PATH="$DEPLOY_DIR/apps/infinity-root/assets/general/config"

    if [[ -d "$ABS_PATH" ]]; then
        CONFIG_DIR="$ABS_PATH"
        SAMPLE_CONFIG="$CONFIG_DIR/sample_absConfig.json"
        ABS_CONFIG="$CONFIG_DIR/absConfig.json"
        ROOT_DIR="abs-root"
    elif [[ -d "$INFINITY_PATH" ]]; then
        CONFIG_DIR="$INFINITY_PATH"
        SAMPLE_CONFIG="$CONFIG_DIR/sample_infinityConfig.json"
        ABS_CONFIG="$CONFIG_DIR/infinityConfig.json"
        ROOT_DIR="infinity-root"
    else
        echo "❌ Error: Could not find abs-root or infinity-root config directories."
        read -p "Press enter to continue"
        return 1
    fi

    if [[ ! -f "$SAMPLE_CONFIG" ]]; then
        echo "❌ Error: Sample config file not found: $SAMPLE_CONFIG"
        read -p "Press enter to continue"
        return 1
    fi

    cp "$SAMPLE_CONFIG" "$ABS_CONFIG"
    echo "✅ Configuration copied from: $(basename "$SAMPLE_CONFIG")"

    # 🔌 Choose connection type
    while true; do
        read -p "Choose your configuration connection (http/https): " CONNECTION_TYPE
        CONNECTION_TYPE=$(echo "$CONNECTION_TYPE" | tr '[:upper:]' '[:lower:]')

        if [[ "$CONNECTION_TYPE" == "https" ]]; then
            read -p "Enter the local server URL (default: $CONNECTION_TYPE://$HOST:$HTTPS_PORT): " NEW_URL
            NEW_URL=${NEW_URL:-"$CONNECTION_TYPE://$HOST:$HTTPS_PORT"}
            break
        elif [[ "$CONNECTION_TYPE" == "http" ]]; then
            read -p "Enter the local server URL (default: $CONNECTION_TYPE://$HOST:$HTTP_PORT): " NEW_URL
            NEW_URL=${NEW_URL:-"$CONNECTION_TYPE://$HOST:$HTTP_PORT"}
            break
        else
            echo "❌ Invalid option. Please enter 'http' or 'https'."
        fi
    done

    # 🛠 Replace URLs in config
    sed -i -E "s#\"http://[^\"]*\"#\"$NEW_URL\"#g; s#\"https://[^\"]*\"#\"$NEW_URL\"#g" "$ABS_CONFIG"

    read -p "Enable peripheralAgentSecureConnection? (true/false, leave empty to keep current): " SECURE_CONNECTION
    if [[ -n "$SECURE_CONNECTION" ]]; then
        sed -i -E "s#(\"peripheralAgentSecureConnection\"\s*:\s*)(true|false)#\1$SECURE_CONNECTION#g" "$ABS_CONFIG"
        echo "🔐 Updated peripheralAgentSecureConnection to $SECURE_CONNECTION"
    else
        echo "🔄 No change to peripheralAgentSecureConnection"
    fi

    SERVER_IP="$(hostname -I | awk '{print $1}')"
    echo "🌍 Server IP is: $SERVER_IP"

    mkdir -p "$INSTALL_DIR/conf.d"
    CONF_FILE="$INSTALL_DIR/conf.d/absinfinity_$ABS_SLOT.conf"

    echo "🔧 Generating NGINX config at: $CONF_FILE"

    # Upstream block
    cat > "$CONF_FILE" <<EOF
upstream backend_endpoint {
    server $APPServer1;
    server $APPServer2;
}
EOF

    # 🔁 Main config
    if [[ "$CONNECTION_TYPE" == "https" ]]; then
        cat >> "$CONF_FILE" <<EOF
server {
    listen       $HTTPS_PORT ssl;
    server_name  $HOST $SERVER_IP;

    ssl_certificate $INSTALL_DIR/ssl/nginx_infinity.crt;
    ssl_certificate_key $INSTALL_DIR/ssl/nginx_infinity.key;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-CHACHA20-POLY1305";
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_prefer_server_ciphers on;

    location / {
      root        $INSTALL_DIR/html/apps/$ROOT_DIR;
      try_files \$uri \$uri/ /index.html\$is_args\$args;
      index       index.html index.htm;
      expires     -1;
      add_header  Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
    }

   resolver 8.8.8.8 valid=10s; # Ensure proper DNS resolution for upstream

    location /client {
        proxy_pass https://backend_endpoint;
        proxy_ssl_verify off;
        proxy_ssl_protocols TLSv1.2 TLSv1.3;
        proxy_ssl_ciphers "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-CHACHA20-POLY1305";
        proxy_ssl_trusted_certificate /abs/12/nginx_infinity/ssl/nginx_infinity.crt;
        proxy_ssl_name $HOST;
        proxy_ssl_server_name on;
        proxy_set_header Host \$host;
        proxy_set_header Connection "keep-alive";
        proxy_http_version 1.1;
    }

    location /authentication {
        proxy_pass https://backend_endpoint;
        proxy_ssl_verify off;
        proxy_ssl_protocols TLSv1.2 TLSv1.3;
        proxy_ssl_ciphers "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-CHACHA20-POLY1305";
        proxy_ssl_trusted_certificate /abs/12/nginx_infinity/ssl/nginx_infinity.crt;
        proxy_ssl_name $HOST;
        proxy_ssl_server_name on;
        proxy_set_header Host \$host;
        proxy_set_header Connection "keep-alive";
        proxy_http_version 1.1;
    }

    location /monitoring {
        proxy_pass https://backend_endpoint;
        proxy_ssl_verify off;
        proxy_ssl_protocols TLSv1.2 TLSv1.3;
        proxy_ssl_ciphers "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-CHACHA20-POLY1305";
        proxy_ssl_trusted_certificate /abs/12/nginx_infinity/ssl/nginx_infinity.crt;
        proxy_ssl_name $HOST;
        proxy_ssl_server_name on;
        proxy_set_header Host \$host;
        proxy_set_header Connection "keep-alive";
        proxy_http_version 1.1;
    }

    location /printing {
        proxy_pass https://backend_endpoint;
        proxy_ssl_verify off;
        proxy_ssl_protocols TLSv1.2 TLSv1.3;
        proxy_ssl_ciphers "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-CHACHA20-POLY1305";
        proxy_ssl_trusted_certificate /abs/12/nginx_infinity/ssl/nginx_infinity.crt;
        proxy_ssl_name $HOST;
        proxy_ssl_server_name on;
        proxy_set_header Host \$host;
        proxy_set_header Connection "keep-alive";
        proxy_http_version 1.1;
    }

    location /localPrintServer {
        proxy_pass https://backend_endpoint;
        proxy_ssl_verify off;
        proxy_ssl_protocols TLSv1.2 TLSv1.3;
        proxy_ssl_ciphers "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-CHACHA20-POLY1305";
        proxy_ssl_trusted_certificate /abs/12/nginx_infinity/ssl/nginx_infinity.crt;
        proxy_ssl_name $HOST;
        proxy_ssl_server_name on;
        proxy_set_header Host \$host;
        proxy_set_header Connection "keep-alive";
        proxy_http_version 1.1;
    }
}
EOF
        echo "🔒 HTTPS configuration added."
    else
        cat >> "$CONF_FILE" <<EOF
server {
    listen       $HTTP_PORT;
    server_name  $HOST $SERVER_IP;

    location / {
      root        $INSTALL_DIR/html/apps/$ROOT_DIR;
      try_files \$uri \$uri/ /index.html\$is_args\$args;
      index       index.html index.htm;
      expires     -1;
      add_header  Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
    }

  location /client {
    proxy_pass http://backend_endpoint;
    proxy_set_header Host \$host;
    proxy_set_header X-Real-IP \$remote_addr;
    proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto http;
  }
  
  location /authentication {
    proxy_pass http://backend_endpoint;
    proxy_set_header Host \$host;
    proxy_set_header X-Real-IP \$remote_addr;
    proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto http;
  }

  location /monitoring { 
    proxy_pass http://backend_endpoint;
    proxy_set_header Host \$host;
    proxy_set_header X-Real-IP \$remote_addr;
    proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto http;
  }
  
  location /printing { 
    proxy_pass http://backend_endpoint;
    proxy_set_header Host \$host;
    proxy_set_header X-Real-IP \$remote_addr;
    proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto http;
  }
  
  location /localPrintServer { 
    proxy_pass http://backend_endpoint;
    proxy_set_header Host \$host;
    proxy_set_header X-Real-IP \$remote_addr;
    proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto http;
  }
}
EOF
        echo "🌐 HTTP configuration added."
    fi

    # 🔁 Reload NGINX if available
    NGINX_PATH="$INSTALL_DIR/sbin/nginx"
    if [[ -f "$NGINX_PATH" ]]; then
        echo "🔍 Testing NGINX configuration..."
        "$NGINX_PATH" -t
        read -p "Press enter to continue"
        echo "🔄 Reloading NGINX..."
        "$NGINX_PATH" -s reload
        echo "✅ NGINX reloaded successfully."
    else
        echo "⚠️ NGINX binary not found at $NGINX_PATH"
        exit 1
    fi

    echo "🎉 Deployment complete!"
}

############################################
# Function to Update custom certificate
############################################
update_nginx_certificates() {
    CERT_DIR="$HOME/repo_infinity/cert"
    DEST_DIR="$INSTALL_DIR/ssl"

    # Ensure destination directory exists
    mkdir -p "$DEST_DIR"

    # Find .crt and .key files
    CRT_FILE=$(find "$CERT_DIR" -maxdepth 1 -type f -name "*.crt" | head -n 1)
    KEY_FILE=$(find "$CERT_DIR" -maxdepth 1 -type f -name "*.key" | head -n 1)

    # Check if both .crt and .key files exist
    if [[ -f "$CRT_FILE" && -f "$KEY_FILE" ]]; then
        echo "Found certificate and key files. Copying to $DEST_DIR..."

        # Copy and rename files
        cp "$CRT_FILE" "$DEST_DIR/nginx_infinity.crt"
        cp "$KEY_FILE" "$DEST_DIR/nginx_infinity.key"

        echo "Certificates updated successfully!"
    else
        echo "No custom certificate found. Continuing..."
    fi
}

############################################
# Function to start NGINX instance
############################################
start_nginx_infinity() {
  echo "▶️ Starting NGINX..."
  $INSTALL_DIR/sbin/nginx
  echo "NGINX and Infinity Started"
}

############################################
# Function to stop NGINX instance
############################################
stop_nginx_infinity() {
  echo "⏹ Stopping NGINX..."
  $INSTALL_DIR/sbin/nginx -s stop || { echo "Failed to stop NGINX. Already stopped."; }
  echo "NGINX and Infinity Stoped"
}

############################################
# Function to status NGINX instance
############################################
reload_nginx_infinity() {
  echo "Check loaded configuration NGINX..."
  $INSTALL_DIR/sbin/nginx -t
  if [ $? -eq 0 ]; then
    echo "Reload NGINX..."
    $INSTALL_DIR/sbin/nginx -s reload
    echo "🚀 NGINX Reloaded"
  else
    echo "⚠️ Warning: NGINX configuration test failed. return to menu..."
  fi
  # Return to menu or call the menu function here
  return 1
}

############################################
# Menu options
############################################
show_menu() {
  echo "|----------------------------------------------------------------------------------------|"
  echo "|NGINX Single Instance Setup for INFINITY - release date 13.06.2025                      |"
  echo  -e "|Dedicated for ABSSolute slot setup -\e[92m script version 1.2 \e[0m                                |"
  echo "|Verify latest NGINX version from http://nginx.org/download                              |"
  echo "|Option3 - will install Infinity on the server and will require Apache redirector link   |"
  echo "|Option4 - will install Infinity on the server and it will create HTTP or HTTPS not both,|"
  echo "|redirect in NginX. This will require backend link or links of the application server.   |"
  echo "|The Infinity link that will be used will be the local one in NginX                      |"
  echo "|----------------------------------------------------------------------------------------|"
  echo
  echo "📦 1. Select application slot number (e.g.: 01...99)"
  echo "🌐 2. Install and configure NGINX (HTTPS: 5${ABS_SLOT}90)"
  echo
  echo "🚀 3. Deploy Infinity Application with Apache redirect (HTTP: 5${ABS_SLOT}91, HTTPS: 5${ABS_SLOT}92)"
  echo "🧩 4. Deploy Infinity Application locally with NGINX redirect (HTTP: 5${ABS_SLOT}91 or HTTPS: 5${ABS_SLOT}92) [only one option]"
  echo
  echo "Start/Stop/Reload NginX from slot $ABS_SLOT"
  echo "▶️  5. Start NGINX"
  echo "⏹️  6. Stop NGINX"
  echo "🔁 7. Reload NGINX"
  echo
  echo
  echo "🔐 c. Update Customer SSL certificate (used in option 4)"
  echo "🧰 d. Show system dependencies (OEL8 compatible)"
  echo "⬆️  u. Update to latest version"
  echo
  echo "❌ Enter. Exit"
  echo "-------------------------------"
  read -p "Choose an option [1-6]/[c,d,u] or Enter to exit: " choice
  
  case $choice in
    1)
      select_slot
      ;;
    2)
      install_nginx_from_source
      generate_ssl_certificates
      configure_nginx_infinity
	  start_nginx_infinity
	  startAll_nginx_infinity
      ;;
	3)
      deploy_application
	  config_application
      ;;
	4)
      deploy_application
	  update_nginx_certificates
	  config_application_local
      ;;
    5)
      start_nginx_infinity
      ;;
    6)
      stop_nginx_infinity
      ;;
    7)
      reload_nginx_infinity
      ;;
	C|c)
      update_nginx_certificates
	  reload_nginx_infinity
      ;;
	D|d)
      install_dependencies
      ;;
	U|u)
      clean_oldversion
	  install_nginx_from_source
      generate_ssl_certificates
      configure_nginx_infinity
	  deploy_application
	  config_application
	  start_nginx_infinity
	  startAll_nginx_infinity
      ;;
    "") echo "❌ Exiting..." && exit 0
      ;;
    *)
      echo "❓ Invalid option!"
	  sleep 1
      ;;
  esac
}

# Loop the menu until the user chooses to exit
while true; do
  clear
  show_menu
  read -p "Press [Enter] to continue..." dummy
done
