#!/bin/bash
# Version: 1.1.0
# Author: Tomi Eckert
# ==============================================================================
# SAP HANA Backup Script
#
# Performs schema exports for one or more schemas and/or tenant backups for a
# SAP HANA database using hanatool.sh. Designed to be executed via a cronjob.
# Reads all settings from the backup.conf file in the same directory.
# ==============================================================================

# --- 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}/backup.conf"
HANATOOL_PATH="${SCRIPT_DIR}/hanatool.sh" # Assuming hanatool.sh is in the parent directory

# 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

# --- Main Execution ---

echo "⚙️  Starting HANA backup process using hanatool.sh..."

mkdir -p "$BACKUP_BASE_DIR"

SCHEMA_EXPORT_OPTIONS=""

case "$BACKUP_TYPE" in
    schema)
        if [[ -z "$SCHEMA_NAMES" ]]; then
            echo "   ⚠️  Warning: SCHEMA_NAMES variable is not set in config. Skipping schema export."
        else
            echo "🔎 Found schemas to export: ${SCHEMA_NAMES}"
            for schema in $SCHEMA_NAMES; do
                echo "⬇️  Starting schema export for '${schema}'..."
                SCHEMA_EXPORT_OPTIONS="$COMMON_OPTIONS"
                if [[ -n "$THREADS" ]]; then
                    SCHEMA_EXPORT_OPTIONS+=" -t $THREADS"
                fi
                if [[ "$COMPRESS_SCHEMA" == "true" ]]; then
                    SCHEMA_EXPORT_OPTIONS+=" --compress"
                fi
                "$HANATOOL_PATH" "$USER_KEY" export "$schema" "${BACKUP_BASE_DIR}/schema" $SCHEMA_EXPORT_OPTIONS
                if [[ $? -ne 0 ]]; then
                    echo "❌ Error: Schema export for '${schema}' failed."
                fi
                echo "--------------------------------------------------"
            done
        fi
        ;;
    tenant)
        echo "⬇️  Starting Tenant backup..."
        TENANT_BACKUP_OPTIONS="$COMMON_OPTIONS"
        if [[ "$COMPRESS_TENANT" == "true" ]]; then
            TENANT_BACKUP_OPTIONS+=" --compress"
        fi
        "$HANATOOL_PATH" "$USER_KEY" backup "${BACKUP_BASE_DIR}/tenant" $TENANT_BACKUP_OPTIONS
        if [[ $? -ne 0 ]]; then
            echo "❌ Error: Tenant backup failed."
        fi
        ;;
    all)
        if [[ -z "$SCHEMA_NAMES" ]]; then
            echo "   ⚠️  Warning: SCHEMA_NAMES variable is not set in config. Skipping schema export."
        else
            echo "🔎 Found schemas to export: ${SCHEMA_NAMES}"
            for schema in $SCHEMA_NAMES; do
                echo "⬇️  Starting schema export for '${schema}'..."
                SCHEMA_EXPORT_OPTIONS="$COMMON_OPTIONS"
                if [[ -n "$THREADS" ]]; then
                    SCHEMA_EXPORT_OPTIONS+=" -t $THREADS"
                fi
                if [[ "$COMPRESS_SCHEMA" == "true" ]]; then
                    SCHEMA_EXPORT_OPTIONS+=" --compress"
                fi
                "$HANATOOL_PATH" "$USER_KEY" export "$schema" "${BACKUP_BASE_DIR}/schema" $SCHEMA_EXPORT_OPTIONS
                if [[ $? -ne 0 ]]; then
                    echo "❌ Error: Schema export for '${schema}' failed."
                fi
                echo "--------------------------------------------------"
            done
        fi

        echo "⬇️  Starting Tenant backup..."
        TENANT_BACKUP_OPTIONS="$COMMON_OPTIONS"
        if [[ "$COMPRESS_TENANT" == "true" ]]; then
            TENANT_BACKUP_OPTIONS+=" --compress"
        fi
        "$HANATOOL_PATH" "$USER_KEY" backup "${BACKUP_BASE_DIR}/tenant" $TENANT_BACKUP_OPTIONS
        if [[ $? -ne 0 ]]; then
            echo "❌ Error: Tenant backup failed."
        fi
        ;;
    *)
        echo "   ❌ Error: Invalid BACKUP_TYPE '${BACKUP_TYPE}' in config. Use 'schema', 'tenant', or 'all'."
        ;;
esac

# Check if SYSTEMDB backup is enabled, regardless of BACKUP_TYPE (as long as it's not 'schema' only)
if [[ "$BACKUP_TYPE" == "tenant" || "$BACKUP_TYPE" == "all" ]]; then
    if [[ "$BACKUP_SYSTEMDB" == "true" ]]; then
        echo "--------------------------------------------------"
        if [[ -z "$SYSTEMDB_USER_KEY" ]]; then
            echo "   ❌ Error: BACKUP_SYSTEMDB is true, but SYSTEMDB_USER_KEY is not set in config."
        else
            echo "⬇️  Starting SYSTEMDB backup..."
            SYSTEMDB_BACKUP_OPTIONS="$COMMON_OPTIONS"
            if [[ "$COMPRESS_TENANT" == "true" ]]; then # SYSTEMDB compression uses COMPRESS_TENANT setting
                SYSTEMDB_BACKUP_OPTIONS+=" --compress"
            fi
            "$HANATOOL_PATH" "$SYSTEMDB_USER_KEY" backup "${BACKUP_BASE_DIR}/tenant" $SYSTEMDB_BACKUP_OPTIONS
            if [[ $? -ne 0 ]]; then
                echo "❌ Error: SYSTEMDB backup failed."
            fi
        fi
    fi
fi

echo "📦 Backup process complete."
echo "👋 Exiting."