#!/bin/bash
# UniSASE Agent Migration Functions
# This file contains migration functions to be sourced by afterinstall script.
# It migrates files from old installation to new directory structure.

#==============================================================================
# Old Directory Paths (for migration from previous versions)
#==============================================================================

OLD_AGENT_BIN_DIR="/usr/bin"
OLD_AGENT_CONF_DIR="/etc/unisase-agent"
OLD_AGENT_CERTS_DIR="/etc/unisase-agent/certs"
OLD_AGENT_LOG_DIR="/var/log/unisase-agent"
OLD_AGENT_RUNTIME_DIR="/run/unisase-agent"

#==============================================================================
# Migration Check Functions
#==============================================================================

# Check if old installation exists
is_old_installation_exists() {
    [ -f "${OLD_AGENT_BIN_DIR}/unisase-agent" ] || \
    [ -d "${OLD_AGENT_CONF_DIR}" ] || \
    [ -d "${OLD_AGENT_LOG_DIR}" ]
}

#==============================================================================
# Migration Functions
#==============================================================================

# migrate_binaries migrates binary files from old location to new location.
# It copies the unisase-agent binary.
migrate_binaries() {
    echo "Migrating binary files..."

    local old_agent="${OLD_AGENT_BIN_DIR}/unisase-agent"

    if [ -f "$old_agent" ]; then
        echo "  Migrating unisase-agent..."
        cp -p "$old_agent" "${AGENT_BIN_DIR}/" || {
            echo "  Warning: Failed to migrate unisase-agent"
            return 1
        }
    fi

    echo "  Binary migration completed"
    return 0
}

# migrate_config migrates configuration files from old location to new location.
# It preserves existing configuration and creates backup.
# It also migrates backup directory if it exists.
# It also updates paths in the configuration file to match new directory structure.
# After migration, it updates log settings based on current system resources.
migrate_config() {
    echo "Migrating configuration files..."

    local old_config="${OLD_AGENT_CONF_DIR}/config.yaml"

    # Migrate main config file
    if [ -f "$old_config" ]; then
        echo "  Migrating config.yaml..."

        # Create backup directory if it doesn't exist
        mkdir -p "${AGENT_CONF_BACKUP_DIR}"

        # If new config exists, back it up first
        if [ -f "${AGENT_CONF_FILE}" ]; then
            local backup_name="config_$(date +%Y%m%d_%H%M%S).yaml"
            cp -p "${AGENT_CONF_FILE}" "${AGENT_CONF_BACKUP_DIR}/${backup_name}"
            echo "  Backed up existing config to ${backup_name}"
        fi

        # Copy old config to new location
        cp -p "$old_config" "${AGENT_CONF_FILE}" || {
            echo "  Warning: Failed to migrate config.yaml"
            return 1
        }

        echo "  Config file migrated (path normalization will be handled by agent during v2 migration)"

        # Update log settings for migrated configuration
        echo "  Updating log settings for migrated configuration based on current system..."
        local max_size=$(calculate_max_size "${AGENT_DEFAULT_LOG_DIR}")
        local max_backups=$(calculate_max_backups "${AGENT_ARCHIVE_LOG_DIR}" "$max_size")

        update_log_config "${AGENT_CONF_FILE}" "$max_size" "$max_backups"
        log_calculation_details "${AGENT_DEFAULT_LOG_DIR}" "${AGENT_ARCHIVE_LOG_DIR}" \
                                "$max_size" "$max_backups"
    else
        echo "  No old configuration found, skipping config.yaml migration"
    fi

    return 0
}

# migrate_certs migrates certificate files from old location to new location.
migrate_certs() {
    echo "Migrating certificate files..."
    
    if [ ! -d "$OLD_AGENT_CERTS_DIR" ]; then
        echo "  No old certificates directory found, skipping"
        return 0
    fi
    
    # Migrate all certificate files
    local cert_count=0
    for cert_file in "${OLD_AGENT_CERTS_DIR}"/*; do
        if [ -f "$cert_file" ]; then
            local cert_name=$(basename "$cert_file")
            echo "  Migrating ${cert_name}..."
            cp -p "$cert_file" "${AGENT_CERTS_DIR}/" || {
                echo "  Warning: Failed to migrate ${cert_name}"
                continue
            }
            cert_count=$((cert_count + 1))
        fi
    done
    
    if [ $cert_count -gt 0 ]; then
        echo "  Migrated ${cert_count} certificate file(s)"
    else
        echo "  No certificate files found"
    fi
    
    return 0
}

# migrate_logs migrates log files from old location to new log directory.
# All log files (agent.log, crash.log, panic.log, and rotated logs) are moved.
# Archiving will be handled by the agent at runtime.
migrate_logs() {
    echo "Migrating log files..."

    if [ ! -d "$OLD_AGENT_LOG_DIR" ]; then
        echo "  No old log directory found, skipping"
        return 0
    fi

    # Ensure new log directory exists
    if [ ! -d "${AGENT_DEFAULT_LOG_DIR}" ]; then
        echo "  Warning: New log directory does not exist: ${AGENT_DEFAULT_LOG_DIR}"
        return 1
    fi

    local log_count=0

    # Migrate all log files to new log directory
    for log_file in "${OLD_AGENT_LOG_DIR}"/*; do
        if [ -f "$log_file" ]; then
            local log_name=$(basename "$log_file")
            chmod 644 "$log_file"

            echo "  Migrating log: ${log_name}..."
            mv "$log_file" "${AGENT_DEFAULT_LOG_DIR}/" || {
                echo "  Warning: Failed to migrate ${log_name}"
                continue
            }
            log_count=$((log_count + 1))
        fi
    done

    if [ $log_count -gt 0 ]; then
        echo "  Migrated ${log_count} log file(s)"
    else
        echo "  No log files found"
    fi

    return 0
}

# cleanup_old_directories removes old installation directories and files after successful migration.
# All old directories and files are removed without checking if they are empty,
# since migration has already preserved all necessary files.
cleanup_old_directories() {
    echo "Cleaning up old directories and files..."

    # Remove old binary files from /usr/bin
    if [ -f "${OLD_AGENT_BIN_DIR}/unisase-agent" ]; then
        echo "  Removing old binary: ${OLD_AGENT_BIN_DIR}/unisase-agent"
        rm -f "${OLD_AGENT_BIN_DIR}/unisase-agent" || {
            echo "  Warning: Failed to remove ${OLD_AGENT_BIN_DIR}/unisase-agent"
        }
    fi

    if [ -f "${OLD_AGENT_BIN_DIR}/unisase-agent-debug-client" ]; then
        echo "  Removing old binary: ${OLD_AGENT_BIN_DIR}/unisase-agent-debug-client"
        rm -f "${OLD_AGENT_BIN_DIR}/unisase-agent-debug-client" || {
            echo "  Warning: Failed to remove ${OLD_AGENT_BIN_DIR}/unisase-agent-debug-client"
        }
    fi

    # Remove old runtime directory
    if [ -d "$OLD_AGENT_RUNTIME_DIR" ]; then
        echo "  Removing old runtime directory: ${OLD_AGENT_RUNTIME_DIR}"
        rm -rf "$OLD_AGENT_RUNTIME_DIR" || {
            echo "  Warning: Failed to remove ${OLD_AGENT_RUNTIME_DIR}"
        }
    fi

    # Remove old log directory
    if [ -d "$OLD_AGENT_LOG_DIR" ]; then
        echo "  Removing old log directory: ${OLD_AGENT_LOG_DIR}"
        rm -rf "$OLD_AGENT_LOG_DIR" || {
            echo "  Warning: Failed to remove ${OLD_AGENT_LOG_DIR}"
        }
    fi

    # Remove old certs directory
    if [ -d "$OLD_AGENT_CERTS_DIR" ]; then
        echo "  Removing old certs directory: ${OLD_AGENT_CERTS_DIR}"
        rm -rf "$OLD_AGENT_CERTS_DIR" || {
            echo "  Warning: Failed to remove ${OLD_AGENT_CERTS_DIR}"
        }
    fi

    # Remove old config directory
    if [ -d "$OLD_AGENT_CONF_DIR" ]; then
        echo "  Removing old config directory: ${OLD_AGENT_CONF_DIR}"
        rm -rf "$OLD_AGENT_CONF_DIR" || {
            echo "  Warning: Failed to remove ${OLD_AGENT_CONF_DIR}"
        }
    fi

    echo "  Cleanup completed"
    return 0
}

# perform_migration executes the complete migration process.
# Returns 0 on success, 1 on failure.
perform_migration() {
    # Check if old installation exists
    if ! is_old_installation_exists; then
        echo "No old installation found, skipping migration."
        return 0
    fi

    echo "========================================="
    echo "Starting migration from old installation"
    echo "========================================="

    local migration_failed=0

    # Migrate binaries
    migrate_binaries || migration_failed=1

    # Migrate configuration
    migrate_config || migration_failed=1

    # Migrate certificates
    migrate_certs || migration_failed=1

    # Migrate logs
    migrate_logs || migration_failed=1

    # Only cleanup old directories if all migrations succeeded
    if [ $migration_failed -eq 0 ]; then
        echo "All migrations completed successfully, cleaning up old directories..."
        cleanup_old_directories || {
            echo "Warning: Cleanup failed, but migration was successful"
        }
        echo "========================================="
        echo "Migration completed successfully"
        echo "========================================="
        return 0
    else
        echo "========================================="
        echo "Migration completed with warnings"
        echo "Old directories were NOT cleaned up due to migration errors"
        echo "========================================="
        return 1
    fi
}
