#!/bin/bash

# Author: Tomi Eckert
# ==============================================================================
# SAP Business One for HANA Silent Installation Configurator
# ==============================================================================
# This script interactively collects necessary details to customize the
# silent installation properties file for SAP Business One on HANA.
# It provides sensible defaults and generates the final 'install.properties'.
# ==============================================================================

# --- Function to display a welcome header ---
print_header() {
    echo "======================================================"
    echo "  SAP Business One for HANA Installation Configurator "
    echo "======================================================"
    echo "Please provide the following details. Defaults are in [brackets]."
    echo ""
}

# --- Function to read password securely (single entry) ---
read_password() {
    local prompt_text=$1
    local -n pass_var=$2 # Use a nameref to pass the variable name
    
    # Loop until the entered password is not empty
    while true; do
        read -s -p "$prompt_text: " pass_var
        echo
        if [ -z "$pass_var" ]; then
            echo "Password cannot be empty. Please try again."
        else
            break
        fi
    done
}

# --- Function to read and verify password securely ---
read_password_verify() {
    local prompt_text=$1
    local -n pass_var=$2 # Use a nameref to pass the variable name
    local pass_verify
    
    # Loop until the entered passwords match and are not empty
    while true; do
        read -s -p "$prompt_text: " pass_var
        echo
        if [ -z "$pass_var" ]; then
            echo "Password cannot be empty. Please try again."
            continue
        fi

        read -s -p "Confirm password: " pass_verify
        echo

        if [ "$pass_var" == "$pass_verify" ]; then
            break
        else
            echo "Passwords do not match. Please try again."
            echo ""
        fi
    done
}

# --- Main configuration logic ---
print_header

# --- Installation Type ---
echo "--- Installation Type ---"
read -p "Is this a new installation or are you reconfiguring an existing instance? (new/reconfigure) [new]: " install_type
install_type=${install_type:-new}

if [[ "$install_type" == "reconfigure" ]]; then
    LANDSCAPE_INSTALL_ACTION="connect"
    B1S_SHARED_FOLDER_OVERWRITE="false"
else
    LANDSCAPE_INSTALL_ACTION="create"
    B1S_SHARED_FOLDER_OVERWRITE="true"
fi
echo ""


# 1. Get Hostname/IP Details
# Default to the current machine's hostname.
DEFAULT_HOSTNAME=$(hostname)
read -p "Enter HANA Database Server Hostname or IP [${DEFAULT_HOSTNAME}]: " HANA_DATABASE_SERVERS
HANA_DATABASE_SERVERS=${HANA_DATABASE_SERVERS:-$DEFAULT_HOSTNAME}

# 2. Get HANA Instance Details
read -p "Enter HANA Database Instance Number [00]: " HANA_DATABASE_INSTANCE
HANA_DATABASE_INSTANCE=${HANA_DATABASE_INSTANCE:-00}

# 3. Get HANA SID to construct the admin user
read -p "Enter HANA SID (Tenant Name) [NDB]: " HANA_SID
HANA_SID=${HANA_SID:-NDB}
# Convert SID to lowercase and append 'adm'
HANA_DATABASE_ADMIN_ID=$(echo "${HANA_SID}" | tr '[:upper:]' '[:lower:]')adm

# 4. Get Passwords
echo ""
echo "--- Secure Password Entry ---"
read_password "Enter password for HANA Admin ('${HANA_DATABASE_ADMIN_ID}')" HANA_DATABASE_ADMIN_PASSWD

# 5. Get HANA Database User
read -p "Enter HANA Database User ID [SYSTEM]: " HANA_DATABASE_USER_ID
HANA_DATABASE_USER_ID=${HANA_DATABASE_USER_ID:-SYSTEM}

# 6. Get HANA User Password
read_password "Enter password for HANA User ('${HANA_DATABASE_USER_ID}')" HANA_DATABASE_USER_PASSWORD

# 7. Get SLD and Site User Details
echo ""
echo "--- System Landscape Directory (SLD) ---"
read -p "Enter SLD Service Port [40000]: " SERVICE_PORT
SERVICE_PORT=${SERVICE_PORT:-40000}

read -p "Enter SLD Site User ID [B1SiteUser]: " SITE_USER_ID
SITE_USER_ID=${SITE_USER_ID:-B1SiteUser}

read_password_verify "Enter password for Site User ('${SITE_USER_ID}')" SITE_USER_PASSWORD

# --- SLD Single Sign-On (SSO) Settings ---
echo ""
echo "--- SLD Single Sign-On (SSO) Settings ---"
read -p "Do you want to configure Active Directory SSO? [y/N]: " configure_sso

if [[ "$configure_sso" =~ ^[yY]$ ]]; then
    SLD_WINDOWS_DOMAIN_ACTION="use"
    read -p "Enter AD Domain Controller: " SLD_WINDOWS_DOMAIN_CONTROLLER
    read -p "Enter AD Domain Name: " SLD_WINDOWS_DOMAIN_NAME
    read -p "Enter AD Domain User ID: " SLD_WINDOWS_DOMAIN_USER_ID
    read_password "Enter password for AD Domain User ('${SLD_WINDOWS_DOMAIN_USER_ID}')" SLD_WINDOWS_DOMAIN_USER_PASSWORD
else
    SLD_WINDOWS_DOMAIN_ACTION="skip"
    SLD_WINDOWS_DOMAIN_CONTROLLER=""
    SLD_WINDOWS_DOMAIN_NAME=""
    SLD_WINDOWS_DOMAIN_USER_ID=""
    SLD_WINDOWS_DOMAIN_USER_PASSWORD=""
fi

# 10. & 11. Get Service Layer Load Balancer Details
echo ""
echo "--- Service Layer ---"
read -p "Enter Service Layer Load Balancer Port [50000]: " SL_LB_PORT
SL_LB_PORT=${SL_LB_PORT:-50000}

read -p "How many Service Layer member nodes should be configured? [2]: " SL_MEMBER_COUNT
SL_MEMBER_COUNT=${SL_MEMBER_COUNT:-2}

# Generate the SL_LB_MEMBERS string
SL_LB_MEMBERS=""
for (( i=1; i<=SL_MEMBER_COUNT; i++ )); do
    port=$((50000 + i))
    member="${HANA_DATABASE_SERVERS}:${port}"
    if [ -z "$SL_LB_MEMBERS" ]; then
        SL_LB_MEMBERS="$member"
    else
        SL_LB_MEMBERS="$SL_LB_MEMBERS,$member"
    fi
done

# 12. Display Summary and Ask for Confirmation
clear
echo "======================================================"
echo "              Configuration Summary"
echo "======================================================"
echo ""
echo " --- Installation & System Details ---"
echo " INSTALLATION_FOLDER=/usr/sap/SAPBusinessOne"
echo " LANDSCAPE_INSTALL_ACTION=${LANDSCAPE_INSTALL_ACTION}"
echo " B1S_SHARED_FOLDER_OVERWRITE=${B1S_SHARED_FOLDER_OVERWRITE}"
echo ""
echo " --- SAP HANA Database Server Details ---"
echo " HANA_DATABASE_SERVERS=${HANA_DATABASE_SERVERS}"
echo " HANA_DATABASE_INSTANCE=${HANA_DATABASE_INSTANCE}"
echo " HANA_DATABASE_ADMIN_ID=${HANA_DATABASE_ADMIN_ID}"
echo " HANA_DATABASE_ADMIN_PASSWD=[hidden]"
echo ""
echo " --- SAP HANA Database User ---"
echo " HANA_DATABASE_USER_ID=${HANA_DATABASE_USER_ID}"
echo " HANA_DATABASE_USER_PASSWORD=[hidden]"
echo ""
echo " --- System Landscape Directory (SLD) Details ---"
echo " SERVICE_PORT=${SERVICE_PORT}"
echo " SITE_USER_ID=${SITE_USER_ID}"
echo " SITE_USER_PASSWORD=[hidden]"
echo ""
echo " --- SLD Single Sign-On (SSO) ---"
echo " SLD_WINDOWS_DOMAIN_ACTION=${SLD_WINDOWS_DOMAIN_ACTION}"
if [ "$SLD_WINDOWS_DOMAIN_ACTION" == "use" ]; then
    echo " SLD_WINDOWS_DOMAIN_CONTROLLER=${SLD_WINDOWS_DOMAIN_CONTROLLER}"
    echo " SLD_WINDOWS_DOMAIN_NAME=${SLD_WINDOWS_DOMAIN_NAME}"
    echo " SLD_WINDOWS_DOMAIN_USER_ID=${SLD_WINDOWS_DOMAIN_USER_ID}"
    echo " SLD_WINDOWS_DOMAIN_USER_PASSWORD=[hidden]"
fi
echo ""
echo " --- Service Layer ---"
echo " SL_LB_PORT=${SL_LB_PORT}"
echo " SL_LB_MEMBERS=${SL_LB_MEMBERS}"
echo ""
echo "======================================================"
read -p "Save this configuration to 'install.properties'? [y/N]: " confirm
echo ""

if [[ ! "$confirm" =~ ^[yY]$ ]]; then
    echo "Configuration cancelled by user."
    exit 1
fi

# --- Write the final install.properties file ---
# Using a HEREDOC to write the configuration file with the variables collected.
cat > install.properties << EOL
# SAP Business One for HANA Silent Installation Properties
# Generated by configuration script on $(date)

INSTALLATION_FOLDER=/usr/sap/SAPBusinessOne

HANA_DATABASE_SERVERS=${HANA_DATABASE_SERVERS}
HANA_DATABASE_INSTANCE=${HANA_DATABASE_INSTANCE}
HANA_DATABASE_ADMIN_ID=${HANA_DATABASE_ADMIN_ID}
HANA_DATABASE_ADMIN_PASSWD=${HANA_DATABASE_ADMIN_PASSWD}

HANA_DATABASE_USER_ID=${HANA_DATABASE_USER_ID}
HANA_DATABASE_USER_PASSWORD=${HANA_DATABASE_USER_PASSWORD}

SERVICE_PORT=${SERVICE_PORT}
SLD_DATABASE_NAME=SLDDATA
SLD_CERTIFICATE_ACTION=self
CONNECTION_SSL_CERTIFICATE_VERIFICATION=false
SLD_DATABASE_ACTION=create
SLD_SERVER_PROTOCOL=https
SITE_USER_ID=${SITE_USER_ID}
SITE_USER_PASSWORD=${SITE_USER_PASSWORD}

# --- SLD Single Sign-On (SSO) Settings ---
SLD_WINDOWS_DOMAIN_ACTION=${SLD_WINDOWS_DOMAIN_ACTION}
SLD_WINDOWS_DOMAIN_CONTROLLER=${SLD_WINDOWS_DOMAIN_CONTROLLER}
SLD_WINDOWS_DOMAIN_NAME=${SLD_WINDOWS_DOMAIN_NAME}
SLD_WINDOWS_DOMAIN_USER_ID=${SLD_WINDOWS_DOMAIN_USER_ID}
SLD_WINDOWS_DOMAIN_USER_PASSWORD=${SLD_WINDOWS_DOMAIN_USER_PASSWORD}

SL_LB_MEMBER_ONLY=false
SL_LB_PORT=${SL_LB_PORT}
SL_LB_MEMBERS=${SL_LB_MEMBERS}
SL_THREAD_PER_SERVER=10

SELECTED_FEATURES=B1ServerTools,B1ServerToolsLandscape,B1ServerToolsSLD,B1ServerToolsLicense,B1ServerToolsJobService,B1ServerToolsXApp,B1SLDAgent,B1BackupService,B1Server,B1ServerSHR,B1ServerHelp,B1AnalyticsPlatform,B1ServerCommonDB,B1ServiceLayerComponent,B1WebClient

B1S_SAMBA_AUTOSTART=true
B1S_SHARED_FOLDER_OVERWRITE=${B1S_SHARED_FOLDER_OVERWRITE}
LANDSCAPE_INSTALL_ACTION=${LANDSCAPE_INSTALL_ACTION}
EOL

echo "Success! The configuration file 'install.properties' has been created in the current directory."
exit 0

