#!/bin/bash

# AutoNAS udev wrapper - runs the manager script in background to avoid udev timeout
# Usage: autonas-udev-wrapper.sh attach <uuid>

# Global configuration
LOG_TAG="autonas-wrapper"

# Set comprehensive environment for udev context
export PATH="/usr/local/bin:/usr/bin:/bin:/sbin:/usr/sbin"
export HOME="/root"
export USER="root"
export LOGNAME="root"
export SHELL="/bin/bash"

# Set proper umask for mount operations
umask 022

UUID="$2"
ACTION="$1"

# Validate arguments
if [ -z "$ACTION" ] || [ -z "$UUID" ]; then
    logger -p local0.err -t "$LOG_TAG" "Invalid arguments: ACTION='$ACTION', UUID='$UUID'"
    exit 1
fi

# Log the call with device info
logger -p local0.info -t "$LOG_TAG" "Called with action: $ACTION, UUID: $UUID"

# Get device info for logging
if [ -n "$UUID" ]; then
    DEVICE_PATH="/dev/disk/by-uuid/$UUID"
    if [ -e "$DEVICE_PATH" ]; then
        ACTUAL_DEVICE=$(readlink -f "$DEVICE_PATH" 2>/dev/null)
        logger -p local0.info -t "$LOG_TAG" "Device path: $ACTUAL_DEVICE"
    fi
fi

# Run the actual script through systemd for reliable execution
(
    # Additional delay for device stabilization
    sleep 3
    
    # Ensure we're running as root with full privileges
    if [ "$(id -u)" != "0" ]; then
        logger -p local0.err -t "$LOG_TAG" "Not running as root, UID: $(id -u)"
        exit 1
    fi
    
    # Use systemd service directly for reliable execution
    if [ "$ACTION" = "attach" ]; then
        systemctl start "autonas-attach@${UUID}.service"
        logger -p local0.info -t "$LOG_TAG" "Started systemd service for UUID: $UUID"
    else
        logger -p local0.warning -t "$LOG_TAG" "Detach operations not supported through systemd wrapper"
    fi
    
) &

# Log background job started
logger -p local0.info -t "$LOG_TAG" "Started background job for $ACTION $UUID (PID: $!)"

# Exit immediately so udev doesn't wait
exit 0