#!/bin/bash
# Version: 2.5.1
# Author: Tomi Eckert
# ==============================================================================
# Aurora Refresh Script
#
# Performs an automated refresh of a SAP HANA schema using hanatool.sh.
# It exports a production schema and re-imports it under a new name ("Aurora")
# to create an up-to-date, non-production environment for testing.
# ==============================================================================

# --- Configuration and Setup ---

# Find the script's own directory to locate the config file and hanatool.sh
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &> /dev/null && pwd)
CONFIG_FILE="${SCRIPT_DIR}/aurora.conf"
HANATOOL_PATH="${SCRIPT_DIR}/hanatool.sh"

# Check for config file and source it
if [[ -f "$CONFIG_FILE" ]]; then
    source "$CONFIG_FILE"
else
    echo "❌ Error: Configuration file not found at '${CONFIG_FILE}'"
    exit 1
fi

# Check if hanatool.sh executable exists
if [[ ! -x "$HANATOOL_PATH" ]]; then
    echo "❌ Error: hanatool.sh not found or not executable at '${HANATOOL_PATH}'"
    exit 1
fi

# --- Derived Variables ---
AURORA_SCHEMA="${SOURCE_SCHEMA}_AURORA"
EXPORT_DIR="${BACKUP_BASE_DIR}/${AURORA_SCHEMA}_TEMP_EXPORT"

# --- Main Execution ---
echo "🚀 Starting Aurora Refresh for '${SOURCE_SCHEMA}' using hanatool.sh..."

# 1. Drop the old Aurora schema if it exists.
echo "🗑️  Dropping old schema '${AURORA_SCHEMA}' (if it exists)..."
"$HDBSQL" -U "$DB_ADMIN_KEY" "DROP SCHEMA \"${AURORA_SCHEMA}\" CASCADE" >/dev/null 2>&1 || echo "   -> Schema did not exist. Continuing."

# 2. Prepare the temporary export directory.
echo "📁 Preparing temporary export directory..."
rm -rf "$EXPORT_DIR"
mkdir -p "$EXPORT_DIR"

# 3. Export the source schema using hanatool.sh
echo "⬇️  Exporting source schema '${SOURCE_SCHEMA}'..."
"$HANATOOL_PATH" "$DB_ADMIN_KEY" export "$SOURCE_SCHEMA" "$EXPORT_DIR" -t "$THREADS"
if [[ $? -ne 0 ]]; then
    echo "❌ Error: Export failed."
    exit 1
fi

# 4. Import the data into the new Aurora schema using hanatool.sh
echo "⬆️  Importing data and renaming schema to '${AURORA_SCHEMA}'..."
"$HANATOOL_PATH" "$DB_ADMIN_KEY" import-rename "$SOURCE_SCHEMA" "$AURORA_SCHEMA" "$EXPORT_DIR" -t "$THREADS"
if [[ $? -ne 0 ]]; then
    echo "❌ Error: Import failed."
    exit 1
fi

# 5. Update company name in CINF and OADM tables.
echo "✍️  Updating company name fields in the new schema..."

# First, get the original company name from the source schema.
echo "   -> Fetching original company name from '${SOURCE_SCHEMA}'..."
ORIGINAL_COMPNY_NAME=$("$HDBSQL" -U "$DB_ADMIN_KEY" "SELECT \"CompnyName\" FROM \"${SOURCE_SCHEMA}\".\"CINF\"" | sed -n '2p' | tr -d '"' | xargs)

# Construct the new name in the desired format.
DATE_STAMP=$(date "+%Y-%m-%d")
NEW_COMPNY_NAME="AURORA - ${ORIGINAL_COMPNY_NAME} - ${DATE_STAMP}"
echo "   -> New company name set to: '${NEW_COMPNY_NAME}'"

echo "   -> Updating CINF table..."
"$HDBSQL" -U "$DB_ADMIN_KEY" "UPDATE \"${AURORA_SCHEMA}\".CINF SET \"CompnyName\" = '${NEW_COMPNY_NAME}';" >/dev/null

echo "   -> Updating OADM table..."
"$HDBSQL" -U "$DB_ADMIN_KEY" "UPDATE \"${AURORA_SCHEMA}\".OADM SET \"CompnyName\" = '${NEW_COMPNY_NAME}', \"PrintHeadr\" = '${NEW_COMPNY_NAME}';" >/dev/null
echo "   -> Company info updated."

# 6. Grant privileges to the read/write user.
echo "🔑 Granting ALL privileges on '${AURORA_SCHEMA}' to '${AURORA_USER}'..."
"$HDBSQL" -U "$DB_ADMIN_KEY" "GRANT ALL PRIVILEGES ON SCHEMA \"${AURORA_SCHEMA}\" TO \"${AURORA_USER}\";" >/dev/null
echo "   -> Privileges granted."

# 7. Run post-import SQL scripts, if any are defined.
if [[ -n "$POST_IMPORT_SQL" ]]; then
    echo "⚙️  Running post-import SQL scripts..."
    for sql_file in $POST_IMPORT_SQL; do
        full_path="${SQL_SCRIPTS_ROOT}/${sql_file}"
        if [[ -f "$full_path" ]]; then
            echo "   -> Executing: ${sql_file}"
            "$HDBSQL" -U "$DB_ADMIN_KEY" -I "$full_path"
        else
            echo "   -> ⚠️ WARNING: Script not found: ${full_path}" >&2
        fi
    done
else
    echo "ℹ️  No post-import SQL scripts to run."
fi

# 8. Clean up the temporary export files.
echo "🧹 Cleaning up temporary directory '${EXPORT_DIR}'..."
rm -rf "$EXPORT_DIR"
echo "   -> Cleanup complete."

echo "--------------------------------------------------------"
echo "✅ Aurora Refresh finished successfully!"
echo

exit 0
