#!/bin/bash

# ────────────────────────────────────────────────────────────────────────
# Startup Tomcat
# ────────────────────────────────────────────────────────────────────────

# ========= CONFIGURATION ==========
TOOLS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BASE_DIR="$(dirname "$TOOLS_DIR")"
USER_BASH_PROFILE="$HOME/.bash_profile"

# --- Determine ORACLE_HOME based on existing .bash_profile ---
# Try to extract ORACLE_HOME from user's bash profile
ORACLE_HOME=""

if [[ -f "$USER_BASH_PROFILE" ]]; then
  # Extract the last ORACLE_HOME assignment (with or without 'export')
  ORACLE_HOME=$(grep -E '^(export[[:space:]]+)?ORACLE_HOME=' "$USER_BASH_PROFILE" | \
                tail -n 1 | \
                sed -E 's/^(export[[:space:]]+)?ORACLE_HOME=//' | \
                tr -d '"'\'' ')
  
  if [[ -n "$ORACLE_HOME" ]]; then
    echo -e "\033[1;32m✅ Found ORACLE_HOME in .bash_profile: $ORACLE_HOME\033[0m"
  else
    echo -e "\033[1;33m⚠ ORACLE_HOME not defined in .bash_profile.\033[0m"
  fi
else
  echo -e "\033[1;33m⚠ .bash_profile not found. Proceeding without ORACLE_HOME.\033[0m"
fi

# Warn if no ORACLE_HOME was found
if [[ -z "$ORACLE_HOME" ]]; then
  echo -e "\033[1;33m⚠ No valid ORACLE_HOME found in .bash_profile. Continuing anyway...\033[0m"
fi

# ========= ENV PATH SETUP ==========
JAVA_HOME="$BASE_DIR/jre"
CATALINA_HOME="$BASE_DIR/tomcat9"
ORDS_INSTALLER="$BASE_DIR/installer"
ORDS_CONFIG="$BASE_DIR/config"
ORDS_LOGS="$BASE_DIR/logs"
ORACLE_HOME="$ORACLE_HOME"
JAVA_OPTS="-Dconfig.url=${ORDS_CONFIG} -Xms1024M -Xmx1024M"

PATH="$ORACLE_HOME:$ORACLE_HOME/lib:$ORACLE_HOME/bin:$HOME/bin:$PATH:$ORDS_INSTALLER/bin:$PATH:$JAVA_HOME/bin:$PATH"
LD_LIBRARY_PATH="$ORACLE_HOME/lib"

export PATH ORACLE_HOME LD_LIBRARY_PATH JAVA_HOME CATALINA_HOME ORDS_CONFIG JAVA_OPTS
export TNS_ADMIN="$ORACLE_HOME/network/admin"

export JAVA_OPTS="-Dconfig.url=${ORDS_CONFIG} -Xms1024M -Xmx1024M"
chmod 775 "$CATALINA_HOME/bin/startup.sh"
"$CATALINA_HOME/bin/startup.sh"
echo "🚀 Tomcat application started... 🚀"

