#!/bin/bash

# AutoNAS Manager - System integration for udev/systemd events
# This script is called by udev rules when disks are attached/detached
# Uses autonas-core.sh for all business logic

# Load the AutoNAS core library
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/autonas-core.sh" || {
    echo "Error: Cannot load AutoNAS core library" >&2
    exit 1
}

# Set LOG_TAG for this component
LOG_TAG="autonas-disk-handler"

# Main script logic
case "$1" in
    "attach")
        if [ -z "$2" ]; then
            log_message "Error: UUID required for attach operation" "err"
            exit 1
        fi
        log_message "AutoNAS attach operation started for UUID: $2" "info"
        handle_attach "$2"
        ;;
    "attach-deferred")
        if [ -z "$2" ]; then
            log_message "Error: UUID required for deferred attach operation" "err"
            exit 1
        fi
        log_message "AutoNAS deferred attach operation started for UUID: $2" "info"
        handle_attach "$2"
        ;;
    "detach")
        if [ -z "$2" ]; then
            log_message "Error: UUID, disk name, or mount point required for detach operation" "err"
            exit 1
        fi
        log_message "AutoNAS detach operation started for identifier: $2" "info"

        if ! handle_detach "$2"; then
            log_message "No configuration found for identifier: $2 - detach skipped" "info"
            log_message "This may be normal if the disk was not configured for AutoNAS" "info"
            exit 0
        fi
        ;;
    "import")
        if [ -z "$2" ] || [ -z "$3" ] || [ -z "$4" ]; then
            log_message "Error: UUID, mount_point, and destination required for import operation" "err"
            exit 1
        fi
        log_message "AutoNAS background import operation started for UUID: $2" "info"
        run_background_import "$2" "$3" "$4" "$5"
        ;;
    "reload")
        handle_reload
        ;;
    *)
        echo "Usage: $0 {attach|attach-deferred|detach|import|reload} <UUID|name|mount_point> [args...]"
        echo "  attach <UUID>         - Attach disk by UUID (direct)"
        echo "  attach-deferred <UUID> - Attach disk by UUID (via systemd)"
        echo "  detach <UUID|name|mount_point> - Detach configured disk"
        echo "  import <UUID> <mount> <dest> [script] - Run background camera import"
        echo "This script is typically called by udev rules or systemd"
        log_message "Invalid arguments provided: $*" "err"
        exit 1
        ;;
esac
