Tutorial

New updates and improvements to Macfleet.

System Preferences Management on macOS

Manage and control System Preferences access on your MacFleet devices with comprehensive preference pane management, user restriction controls, and enterprise configuration solutions. This tutorial covers hiding, disabling, and controlling System Preferences for enhanced security and compliance.

Understanding System Preferences Management

System Preferences on macOS provides access to system configuration settings:

  • Preference Panes - Individual configuration modules (Network, Security, Users, etc.)
  • Bundle Identifiers - Unique identifiers for each preference pane
  • Hidden vs Disabled - Different levels of access restriction
  • Enterprise Control - Centralized management of user access to system settings

Enterprise Use Cases

System Preferences management benefits enterprise environments:

  • Security Hardening - Prevent unauthorized configuration changes
  • Compliance - Ensure devices meet regulatory requirements
  • User Experience - Simplify interfaces by hiding irrelevant options
  • Administrative Control - Centralize configuration management
  • Data Protection - Restrict access to sensitive system settings

Basic System Preferences Control

Hide Profiles Pane

#!/bin/bash

# Hide Profiles pane from System Preferences
hide_profiles_pane() {
    echo "=== Hiding Profiles Pane ==="
    
    # Check macOS version (hiding requires macOS 13.0+)
    local macos_version=$(sw_vers -productVersion | cut -d. -f1)
    if [[ $macos_version -lt 13 ]]; then
        echo "Warning: Hiding panes requires macOS 13.0 or later"
        echo "Current version: $(sw_vers -productVersion)"
        echo "Using disable instead of hide..."
        disable_profiles_pane
        return
    fi
    
    # Hide the Profiles pane
    defaults write "/Library/Preferences/com.apple.systempreferences" \
        HiddenPreferencePanes -array "com.apple.preferences.configurationprofiles"
    
    if [[ $? -eq 0 ]]; then
        echo "✓ Profiles pane hidden successfully"
        echo "Users will no longer see the Profiles pane in System Preferences"
    else
        echo "✗ Failed to hide Profiles pane"
        return 1
    fi
}

# Disable Profiles pane (alternative for older macOS)
disable_profiles_pane() {
    echo "=== Disabling Profiles Pane ==="
    
    # Disable the Profiles pane (works on macOS 10.2+)
    defaults write "/Library/Preferences/com.apple.systempreferences" \
        DisabledPreferencePanes -array "com.apple.preferences.configurationprofiles"
    
    if [[ $? -eq 0 ]]; then
        echo "✓ Profiles pane disabled successfully"
        echo "Profiles pane will appear greyed out in System Preferences"
    else
        echo "✗ Failed to disable Profiles pane"
        return 1
    fi
}

# Usage
hide_profiles_pane

Unhide/Re-enable Profiles Pane

#!/bin/bash

# Restore Profiles pane access
restore_profiles_pane() {
    echo "=== Restoring Profiles Pane Access ==="
    
    # Remove from hidden panes
    local hidden_panes=$(defaults read "/Library/Preferences/com.apple.systempreferences" HiddenPreferencePanes 2>/dev/null)
    if [[ -n "$hidden_panes" ]]; then
        echo "Removing from hidden panes..."
        defaults delete "/Library/Preferences/com.apple.systempreferences" HiddenPreferencePanes 2>/dev/null
    fi
    
    # Remove from disabled panes
    local disabled_panes=$(defaults read "/Library/Preferences/com.apple.systempreferences" DisabledPreferencePanes 2>/dev/null)
    if [[ -n "$disabled_panes" ]]; then
        echo "Removing from disabled panes..."
        defaults delete "/Library/Preferences/com.apple.systempreferences" DisabledPreferencePanes 2>/dev/null
    fi
    
    echo "✓ Profiles pane access restored"
    echo "Users can now access the Profiles pane in System Preferences"
}

# Usage
restore_profiles_pane

Multiple Preference Panes Management

#!/bin/bash

# Manage multiple preference panes simultaneously
manage_multiple_panes() {
    local action="${1:-hide}"  # hide, disable, or restore
    local panes=("${@:2}")    # Array of pane identifiers
    
    if [[ ${#panes[@]} -eq 0 ]]; then
        echo "Usage: manage_multiple_panes [hide|disable|restore] <pane1> [pane2] ..."
        echo "Example: manage_multiple_panes hide profiles bluetooth network"
        return 1
    fi
    
    echo "=== Managing Multiple Preference Panes ==="
    echo "Action: $action"
    echo "Panes: ${panes[*]}"
    echo ""
    
    # Convert friendly names to bundle identifiers
    local bundle_ids=()
    for pane in "${panes[@]}"; do
        local bundle_id=$(get_bundle_identifier "$pane")
        if [[ -n "$bundle_id" ]]; then
            bundle_ids+=("$bundle_id")
            echo "✓ $pane -> $bundle_id"
        else
            echo "✗ Unknown pane: $pane"
        fi
    done
    
    if [[ ${#bundle_ids[@]} -eq 0 ]]; then
        echo "No valid panes specified"
        return 1
    fi
    
    # Apply the action
    case "$action" in
        "hide")
            defaults write "/Library/Preferences/com.apple.systempreferences" \
                HiddenPreferencePanes -array "${bundle_ids[@]}"
            echo "✓ Panes hidden successfully"
            ;;
        "disable")
            defaults write "/Library/Preferences/com.apple.systempreferences" \
                DisabledPreferencePanes -array "${bundle_ids[@]}"
            echo "✓ Panes disabled successfully"
            ;;
        "restore")
            defaults delete "/Library/Preferences/com.apple.systempreferences" HiddenPreferencePanes 2>/dev/null
            defaults delete "/Library/Preferences/com.apple.systempreferences" DisabledPreferencePanes 2>/dev/null
            echo "✓ All panes restored"
            ;;
        *)
            echo "Invalid action: $action"
            return 1
            ;;
    esac
}

# Convert friendly names to bundle identifiers
get_bundle_identifier() {
    local pane_name="$1"
    
    case "$pane_name" in
        "profiles") echo "com.apple.preferences.configurationprofiles" ;;
        "bluetooth") echo "com.apple.preferences.Bluetooth" ;;
        "network") echo "com.apple.preference.network" ;;
        "security") echo "com.apple.preference.security" ;;
        "users") echo "com.apple.preferences.users" ;;
        "sharing") echo "com.apple.preferences.sharing" ;;
        "timemachine") echo "com.apple.prefs.backup" ;;
        "energy") echo "com.apple.preference.energysaver" ;;
        "displays") echo "com.apple.preference.displays" ;;
        "sound") echo "com.apple.preference.sound" ;;
        "keyboard") echo "com.apple.preference.keyboard" ;;
        "mouse") echo "com.apple.preference.mouse" ;;
        "trackpad") echo "com.apple.preference.trackpad" ;;
        "printers") echo "com.apple.preference.printfax" ;;
        "software_update") echo "com.apple.preferences.softwareupdate" ;;
        "date_time") echo "com.apple.preference.datetime" ;;
        "startup_disk") echo "com.apple.preference.startupdisk" ;;
        "accessibility") echo "com.apple.preference.universalaccess" ;;
        "screen_time") echo "com.apple.preference.screentime" ;;
        "extensions") echo "com.apple.preferences.extensions" ;;
        *) echo "" ;;
    esac
}

# Usage examples
# manage_multiple_panes hide profiles bluetooth network
# manage_multiple_panes disable security users sharing
# manage_multiple_panes restore

Advanced System Preferences Management

Policy-Based Preference Management

#!/bin/bash

# Policy-based system preferences management
apply_preference_policy() {
    local policy_name="${1:-standard_office}"
    local user_role="${2:-standard_user}"
    
    echo "=== Applying Preference Policy ==="
    echo "Policy: $policy_name"
    echo "User Role: $user_role"
    echo ""
    
    # Define policies
    case "$policy_name" in
        "kiosk_mode")
            apply_kiosk_policy "$user_role"
            ;;
        "locked_down")
            apply_locked_down_policy "$user_role"
            ;;
        "standard_office")
            apply_standard_office_policy "$user_role"
            ;;
        "developer_workstation")
            apply_developer_policy "$user_role"
            ;;
        "educational")
            apply_educational_policy "$user_role"
            ;;
        "healthcare")
            apply_healthcare_policy "$user_role"
            ;;
        "financial")
            apply_financial_policy "$user_role"
            ;;
        "public_terminal")
            apply_public_terminal_policy "$user_role"
            ;;
        "executive")
            apply_executive_policy "$user_role"
            ;;
        "contractor")
            apply_contractor_policy "$user_role"
            ;;
        *)
            echo "Unknown policy: $policy_name"
            return 1
            ;;
    esac
}

# Kiosk mode policy (maximum restrictions)
apply_kiosk_policy() {
    echo "Applying kiosk mode policy..."
    local restricted_panes=(
        "com.apple.preferences.configurationprofiles"
        "com.apple.preference.security"
        "com.apple.preferences.users"
        "com.apple.preferences.sharing"
        "com.apple.preference.network"
        "com.apple.prefs.backup"
        "com.apple.preferences.softwareupdate"
        "com.apple.preference.datetime"
        "com.apple.preference.startupdisk"
        "com.apple.preferences.extensions"
    )
    
    defaults write "/Library/Preferences/com.apple.systempreferences" \
        HiddenPreferencePanes -array "${restricted_panes[@]}"
    
    echo "✓ Kiosk policy applied - most preferences hidden"
}

# Locked down policy (high security)
apply_locked_down_policy() {
    echo "Applying locked down policy..."
    local restricted_panes=(
        "com.apple.preferences.configurationprofiles"
        "com.apple.preference.security"
        "com.apple.preferences.users"
        "com.apple.preferences.sharing"
        "com.apple.prefs.backup"
        "com.apple.preferences.softwareupdate"
        "com.apple.preference.startupdisk"
    )
    
    defaults write "/Library/Preferences/com.apple.systempreferences" \
        DisabledPreferencePanes -array "${restricted_panes[@]}"
    
    echo "✓ Locked down policy applied - security-sensitive panes disabled"
}

# Standard office policy (moderate restrictions)
apply_standard_office_policy() {
    echo "Applying standard office policy..."
    local restricted_panes=(
        "com.apple.preferences.configurationprofiles"
        "com.apple.preferences.sharing"
        "com.apple.preference.startupdisk"
    )
    
    defaults write "/Library/Preferences/com.apple.systempreferences" \
        DisabledPreferencePanes -array "${restricted_panes[@]}"
    
    echo "✓ Standard office policy applied - minimal restrictions"
}

# Developer workstation policy (minimal restrictions)
apply_developer_policy() {
    echo "Applying developer workstation policy..."
    local restricted_panes=(
        "com.apple.preferences.configurationprofiles"
    )
    
    defaults write "/Library/Preferences/com.apple.systempreferences" \
        DisabledPreferencePanes -array "${restricted_panes[@]}"
    
    echo "✓ Developer policy applied - profile management restricted only"
}

# Educational policy (student-appropriate restrictions)
apply_educational_policy() {
    echo "Applying educational policy..."
    local restricted_panes=(
        "com.apple.preferences.configurationprofiles"
        "com.apple.preference.security"
        "com.apple.preferences.users"
        "com.apple.preferences.sharing"
        "com.apple.preferences.softwareupdate"
        "com.apple.preference.startupdisk"
    )
    
    defaults write "/Library/Preferences/com.apple.systempreferences" \
        HiddenPreferencePanes -array "${restricted_panes[@]}"
    
    echo "✓ Educational policy applied - student-safe configuration"
}

# Healthcare policy (HIPAA compliance focused)
apply_healthcare_policy() {
    echo "Applying healthcare policy..."
    local restricted_panes=(
        "com.apple.preferences.configurationprofiles"
        "com.apple.preference.security"
        "com.apple.preferences.sharing"
        "com.apple.preference.network"
        "com.apple.prefs.backup"
    )
    
    defaults write "/Library/Preferences/com.apple.systempreferences" \
        DisabledPreferencePanes -array "${restricted_panes[@]}"
    
    echo "✓ Healthcare policy applied - HIPAA compliance focused"
}

# Financial policy (enhanced security)
apply_financial_policy() {
    echo "Applying financial policy..."
    local restricted_panes=(
        "com.apple.preferences.configurationprofiles"
        "com.apple.preference.security"
        "com.apple.preferences.users"
        "com.apple.preferences.sharing"
        "com.apple.preference.network"
        "com.apple.prefs.backup"
        "com.apple.preferences.extensions"
    )
    
    defaults write "/Library/Preferences/com.apple.systempreferences" \
        DisabledPreferencePanes -array "${restricted_panes[@]}"
    
    echo "✓ Financial policy applied - enhanced security restrictions"
}

# Public terminal policy (maximum protection)
apply_public_terminal_policy() {
    echo "Applying public terminal policy..."
    local restricted_panes=(
        "com.apple.preferences.configurationprofiles"
        "com.apple.preference.security"
        "com.apple.preferences.users"
        "com.apple.preferences.sharing"
        "com.apple.preference.network"
        "com.apple.prefs.backup"
        "com.apple.preferences.softwareupdate"
        "com.apple.preference.datetime"
        "com.apple.preference.startupdisk"
        "com.apple.preferences.extensions"
        "com.apple.preference.energysaver"
    )
    
    defaults write "/Library/Preferences/com.apple.systempreferences" \
        HiddenPreferencePanes -array "${restricted_panes[@]}"
    
    echo "✓ Public terminal policy applied - maximum protection"
}

# Executive policy (minimal restrictions, full access)
apply_executive_policy() {
    echo "Applying executive policy..."
    # Remove all restrictions for executives
    defaults delete "/Library/Preferences/com.apple.systempreferences" HiddenPreferencePanes 2>/dev/null
    defaults delete "/Library/Preferences/com.apple.systempreferences" DisabledPreferencePanes 2>/dev/null
    
    echo "✓ Executive policy applied - full access granted"
}

# Contractor policy (temporary access restrictions)
apply_contractor_policy() {
    echo "Applying contractor policy..."
    local restricted_panes=(
        "com.apple.preferences.configurationprofiles"
        "com.apple.preference.security"
        "com.apple.preferences.users"
        "com.apple.preferences.sharing"
        "com.apple.prefs.backup"
        "com.apple.preferences.softwareupdate"
        "com.apple.preference.startupdisk"
        "com.apple.preferences.extensions"
    )
    
    defaults write "/Library/Preferences/com.apple.systempreferences" \
        DisabledPreferencePanes -array "${restricted_panes[@]}"
    
    echo "✓ Contractor policy applied - temporary access restrictions"
}

Enterprise System Preferences Management Tool

#!/bin/bash

# MacFleet System Preferences Management Tool
# Comprehensive preference pane control and enterprise policy management

# Configuration
SCRIPT_VERSION="1.0.0"
LOG_FILE="/var/log/macfleet_preferences.log"
REPORT_DIR="/etc/macfleet/reports/preferences"
CONFIG_DIR="/etc/macfleet/preferences"
POLICY_DIR="/etc/macfleet/policies/preferences"
BACKUP_DIR="/etc/macfleet/backups/preferences"

# Create directories if they don't exist
mkdir -p "$REPORT_DIR" "$CONFIG_DIR" "$POLICY_DIR" "$BACKUP_DIR"

# Comprehensive preference pane mapping
declare -A PREFERENCE_PANES=(
    ["profiles"]="com.apple.preferences.configurationprofiles"
    ["bluetooth"]="com.apple.preferences.Bluetooth"
    ["network"]="com.apple.preference.network"
    ["security"]="com.apple.preference.security"
    ["users"]="com.apple.preferences.users"
    ["sharing"]="com.apple.preferences.sharing"
    ["timemachine"]="com.apple.prefs.backup"
    ["energy"]="com.apple.preference.energysaver"
    ["displays"]="com.apple.preference.displays"
    ["sound"]="com.apple.preference.sound"
    ["keyboard"]="com.apple.preference.keyboard"
    ["mouse"]="com.apple.preference.mouse"
    ["trackpad"]="com.apple.preference.trackpad"
    ["printers"]="com.apple.preference.printfax"
    ["software_update"]="com.apple.preferences.softwareupdate"
    ["date_time"]="com.apple.preference.datetime"
    ["startup_disk"]="com.apple.preference.startupdisk"
    ["accessibility"]="com.apple.preference.universalaccess"
    ["screen_time"]="com.apple.preference.screentime"
    ["extensions"]="com.apple.preferences.extensions"
    ["spotlight"]="com.apple.preference.spotlight"
    ["language_region"]="com.apple.Localization"
    ["desktop_screensaver"]="com.apple.preference.desktopscreeneffect"
    ["dock"]="com.apple.preference.dock"
    ["mission_control"]="com.apple.preference.expose"
    ["notifications"]="com.apple.preference.notifications"
    ["internet_accounts"]="com.apple.preferences.internetaccounts"
    ["wallet_apple_pay"]="com.apple.preferences.wallet"
    ["siri"]="com.apple.preference.speech"
    ["touch_id"]="com.apple.preferences.password"
)

# Enterprise policy templates
declare -A POLICY_TEMPLATES=(
    ["kiosk_mode"]="Maximum restrictions for public kiosks and displays"
    ["locked_down"]="High security restrictions for sensitive environments"
    ["standard_office"]="Moderate restrictions for typical office environments"
    ["developer_workstation"]="Minimal restrictions for development environments"
    ["educational"]="Student-appropriate restrictions for educational institutions"
    ["healthcare"]="HIPAA-compliant restrictions for healthcare environments"
    ["financial"]="Enhanced security for financial services environments"
    ["public_terminal"]="Maximum protection for public access terminals"
    ["executive"]="Minimal to no restrictions for executive users"
    ["contractor"]="Temporary access restrictions for contract workers"
)

# Compliance frameworks
declare -A COMPLIANCE_FRAMEWORKS=(
    ["hipaa"]="Health Insurance Portability and Accountability Act"
    ["sox"]="Sarbanes-Oxley Act compliance"
    ["pci_dss"]="Payment Card Industry Data Security Standard"
    ["ferpa"]="Family Educational Rights and Privacy Act"
    ["gdpr"]="General Data Protection Regulation"
    ["nist"]="National Institute of Standards and Technology"
    ["iso27001"]="International Organization for Standardization 27001"
    ["cis"]="Center for Internet Security controls"
    ["fisma"]="Federal Information Security Management Act"
    ["common_criteria"]="Common Criteria security evaluation standard"
)

# Logging function
log_action() {
    local message="$1"
    local severity="${2:-INFO}"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    echo "[$timestamp] [$severity] $message" | tee -a "$LOG_FILE"
}

# Enterprise system preferences management
enterprise_preferences_management() {
    local operation="${1:-status}"
    local policy_name="${2:-standard_office}"
    local target_panes="${3:-}"
    local compliance_framework="${4:-}"
    
    log_action "Starting enterprise preferences management" "INFO"
    log_action "Operation: $operation, Policy: $policy_name" "INFO"
    
    echo "=== Enterprise System Preferences Management ==="
    echo "Operation: $operation"
    echo "Policy: $policy_name"
    echo "Target Panes: ${target_panes:-all_policy_defined}"
    echo "Compliance Framework: ${compliance_framework:-none}"
    echo "Management ID: $(uuidgen)"
    echo ""
    
    # Backup current configuration
    backup_current_configuration
    
    case "$operation" in
        "apply_policy")
            apply_enterprise_policy "$policy_name" "$compliance_framework"
            ;;
        "hide_panes")
            if [[ -n "$target_panes" ]]; then
                hide_specific_panes "$target_panes"
            else
                echo "Error: No target panes specified for hide operation"
                return 1
            fi
            ;;
        "disable_panes")
            if [[ -n "$target_panes" ]]; then
                disable_specific_panes "$target_panes"
            else
                echo "Error: No target panes specified for disable operation"
                return 1
            fi
            ;;
        "restore_all")
            restore_all_preferences
            ;;
        "status")
            show_preferences_status
            ;;
        "audit")
            perform_preferences_audit "$compliance_framework"
            ;;
        "list_policies")
            list_available_policies
            ;;
        "list_panes")
            list_available_panes
            ;;
        *)
            echo "Unknown operation: $operation"
            return 1
            ;;
    esac
    
    # Generate management report
    generate_preferences_report "$operation" "$policy_name" "$target_panes" "$compliance_framework"
    
    log_action "preferences management completed" "INFO"
}

# Backup current configuration
backup_current_configuration() {
    local backup_file="$BACKUP_DIR/preferences_backup_$(date +%Y%m%d_%H%M%S).plist"
    
    echo "--- Creating Configuration Backup ---"
    
    # Copy current system preferences configuration
    if [[ -f "/Library/Preferences/com.apple.systempreferences.plist" ]]; then
        cp "/Library/Preferences/com.apple.systempreferences.plist" "$backup_file"
        echo "✓ Configuration backed up to: $backup_file"
        log_action "Configuration backed up: $backup_file" "INFO"
    else
        echo "⚠️ No existing configuration file found"
        log_action "No existing configuration file to backup" "WARNING"
    fi
}

# Apply enterprise policy with compliance considerations
apply_enterprise_policy() {
    local policy_name="$1"
    local compliance_framework="$2"
    
    echo "--- Applying Enterprise Policy ---"
    echo "Policy: $policy_name"
    echo "Compliance: ${compliance_framework:-none}"
    
    # Apply base policy
    case "$policy_name" in
        "kiosk_mode")
            apply_kiosk_mode_policy
            ;;
        "locked_down")
            apply_locked_down_policy
            ;;
        "standard_office")
            apply_standard_office_policy
            ;;
        "developer_workstation")
            apply_developer_workstation_policy
            ;;
        "educational")
            apply_educational_policy
            ;;
        "healthcare")
            apply_healthcare_policy
            ;;
        "financial")
            apply_financial_policy
            ;;
        "public_terminal")
            apply_public_terminal_policy
            ;;
        "executive")
            apply_executive_policy
            ;;
        "contractor")
            apply_contractor_policy
            ;;
        *)
            echo "Unknown policy: $policy_name"
            return 1
            ;;
    esac
    
    # Apply compliance-specific modifications
    if [[ -n "$compliance_framework" ]]; then
        apply_compliance_modifications "$compliance_framework"
    fi
    
    echo "✓ Enterprise policy applied successfully"
}

# Apply compliance-specific modifications
apply_compliance_modifications() {
    local framework="$1"
    
    echo "--- Applying Compliance Modifications ---"
    echo "Framework: $framework"
    
    case "$framework" in
        "hipaa")
            apply_hipaa_compliance
            ;;
        "sox")
            apply_sox_compliance
            ;;
        "pci_dss")
            apply_pci_dss_compliance
            ;;
        "ferpa")
            apply_ferpa_compliance
            ;;
        "gdpr")
            apply_gdpr_compliance
            ;;
        *)
            echo "Unknown compliance framework: $framework"
            ;;
    esac
}

# HIPAA compliance modifications
apply_hipaa_compliance() {
    echo "Applying HIPAA compliance modifications..."
    
    # Additional restrictions for healthcare data protection
    local hipaa_restricted=(
        "com.apple.preferences.sharing"
        "com.apple.preference.network"
        "com.apple.prefs.backup"
        "com.apple.preferences.internetaccounts"
    )
    
    # Get current disabled panes
    local current_disabled=$(defaults read "/Library/Preferences/com.apple.systempreferences" DisabledPreferencePanes 2>/dev/null | tr -d '(),"' | tr '\n' ' ')
    
    # Combine with HIPAA requirements
    local combined_disabled=($current_disabled "${hipaa_restricted[@]}")
    
    defaults write "/Library/Preferences/com.apple.systempreferences" \
        DisabledPreferencePanes -array "${combined_disabled[@]}"
    
    echo "✓ HIPAA compliance modifications applied"
}

# SOX compliance modifications
apply_sox_compliance() {
    echo "Applying SOX compliance modifications..."
    
    # Financial audit and control requirements
    local sox_restricted=(
        "com.apple.preferences.configurationprofiles"
        "com.apple.preference.security"
        "com.apple.preferences.users"
        "com.apple.preference.datetime"
    )
    
    # Similar pattern for SOX
    local current_disabled=$(defaults read "/Library/Preferences/com.apple.systempreferences" DisabledPreferencePanes 2>/dev/null | tr -d '(),"' | tr '\n' ' ')
    local combined_disabled=($current_disabled "${sox_restricted[@]}")
    
    defaults write "/Library/Preferences/com.apple.systempreferences" \
        DisabledPreferencePanes -array "${combined_disabled[@]}"
    
    echo "✓ SOX compliance modifications applied"
}

# PCI DSS compliance modifications
apply_pci_dss_compliance() {
    echo "Applying PCI DSS compliance modifications..."
    
    # Payment card industry requirements
    local pci_restricted=(
        "com.apple.preferences.sharing"
        "com.apple.preference.network"
        "com.apple.preference.security"
        "com.apple.preferences.extensions"
    )
    
    local current_disabled=$(defaults read "/Library/Preferences/com.apple.systempreferences" DisabledPreferencePanes 2>/dev/null | tr -d '(),"' | tr '\n' ' ')
    local combined_disabled=($current_disabled "${pci_restricted[@]}")
    
    defaults write "/Library/Preferences/com.apple.systempreferences" \
        DisabledPreferencePanes -array "${combined_disabled[@]}"
    
    echo "✓ PCI DSS compliance modifications applied"
}

# FERPA compliance modifications
apply_ferpa_compliance() {
    echo "Applying FERPA compliance modifications..."
    
    # Educational privacy requirements
    local ferpa_restricted=(
        "com.apple.preferences.sharing"
        "com.apple.preferences.internetaccounts"
        "com.apple.prefs.backup"
    )
    
    local current_disabled=$(defaults read "/Library/Preferences/com.apple.systempreferences" DisabledPreferencePanes 2>/dev/null | tr -d '(),"' | tr '\n' ' ')
    local combined_disabled=($current_disabled "${ferpa_restricted[@]}")
    
    defaults write "/Library/Preferences/com.apple.systempreferences" \
        DisabledPreferencePanes -array "${combined_disabled[@]}"
    
    echo "✓ FERPA compliance modifications applied"
}

# GDPR compliance modifications
apply_gdpr_compliance() {
    echo "Applying GDPR compliance modifications..."
    
    # European data protection requirements
    local gdpr_restricted=(
        "com.apple.preferences.sharing"
        "com.apple.prefs.backup"
        "com.apple.preferences.internetaccounts"
        "com.apple.preference.notifications"
    )
    
    local current_disabled=$(defaults read "/Library/Preferences/com.apple.systempreferences" DisabledPreferencePanes 2>/dev/null | tr -d '(),"' | tr '\n' ' ')
    local combined_disabled=($current_disabled "${gdpr_restricted[@]}")
    
    defaults write "/Library/Preferences/com.apple.systempreferences" \
        DisabledPreferencePanes -array "${combined_disabled[@]}"
    
    echo "✓ GDPR compliance modifications applied"
}

# Show current preferences status
show_preferences_status() {
    echo "--- System Preferences Status ---"
    
    # Check hidden panes
    local hidden_panes=$(defaults read "/Library/Preferences/com.apple.systempreferences" HiddenPreferencePanes 2>/dev/null)
    if [[ -n "$hidden_panes" ]]; then
        echo "Hidden Panes:"
        echo "$hidden_panes" | tr -d '(),"' | tr '\n' ' ' | xargs -n1 | while read pane; do
            if [[ -n "$pane" ]]; then
                local friendly_name=$(get_friendly_name "$pane")
                echo "  - $friendly_name ($pane)"
            fi
        done
    else
        echo "Hidden Panes: None"
    fi
    
    echo ""
    
    # Check disabled panes
    local disabled_panes=$(defaults read "/Library/Preferences/com.apple.systempreferences" DisabledPreferencePanes 2>/dev/null)
    if [[ -n "$disabled_panes" ]]; then
        echo "Disabled Panes:"
        echo "$disabled_panes" | tr -d '(),"' | tr '\n' ' ' | xargs -n1 | while read pane; do
            if [[ -n "$pane" ]]; then
                local friendly_name=$(get_friendly_name "$pane")
                echo "  - $friendly_name ($pane)"
            fi
        done
    else
        echo "Disabled Panes: None"
    fi
}

# Get friendly name from bundle identifier
get_friendly_name() {
    local bundle_id="$1"
    
    for friendly_name in "${!PREFERENCE_PANES[@]}"; do
        if [[ "${PREFERENCE_PANES[$friendly_name]}" == "$bundle_id" ]]; then
            echo "$friendly_name"
            return
        fi
    done
    
    echo "unknown"
}

# Generate comprehensive preferences report
generate_preferences_report() {
    local operation="$1"
    local policy_name="$2"
    local target_panes="$3"
    local compliance_framework="$4"
    
    local report_file="$REPORT_DIR/preferences_report_$(date +%Y%m%d_%H%M%S).json"
    
    # Get current configuration
    local hidden_panes=$(defaults read "/Library/Preferences/com.apple.systempreferences" HiddenPreferencePanes 2>/dev/null | tr -d '(),"' | tr '\n' ' ')
    local disabled_panes=$(defaults read "/Library/Preferences/com.apple.systempreferences" DisabledPreferencePanes 2>/dev/null | tr -d '(),"' | tr '\n' ' ')
    
    cat > "$report_file" << EOF
{
    "preferences_report": {
        "report_metadata": {
            "report_id": "$(uuidgen)",
            "generated_date": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
            "hostname": "$(hostname)",
            "script_version": "$SCRIPT_VERSION",
            "macos_version": "$(sw_vers -productVersion)"
        },
        "operation_details": {
            "operation": "$operation",
            "policy_name": "$policy_name",
            "target_panes": "$target_panes",
            "compliance_framework": "$compliance_framework"
        },
        "current_configuration": {
            "hidden_panes": "$hidden_panes",
            "disabled_panes": "$disabled_panes",
            "total_restrictions": $(echo "$hidden_panes $disabled_panes" | wc -w)
        },
        "system_information": {
            "total_preference_panes": ${#PREFERENCE_PANES[@]},
            "available_policies": ${#POLICY_TEMPLATES[@]},
            "compliance_frameworks": ${#COMPLIANCE_FRAMEWORKS[@]}
        }
    }
}
EOF
    
    echo "Preferences report generated: $report_file"
    log_action "Preferences report generated: $report_file" "INFO"
}

# List available policies
list_available_policies() {
    echo "--- Available Enterprise Policies ---"
    for policy in "${!POLICY_TEMPLATES[@]}"; do
        echo "  $policy: ${POLICY_TEMPLATES[$policy]}"
    done
}

# List available preference panes
list_available_panes() {
    echo "--- Available Preference Panes ---"
    for pane in "${!PREFERENCE_PANES[@]}"; do
        echo "  $pane: ${PREFERENCE_PANES[$pane]}"
    done
}

# Main execution function
main() {
    local operation="${1:-help}"
    local policy="${2:-}"
    local panes="${3:-}"
    local compliance="${4:-}"
    
    log_action "=== MacFleet System Preferences Management Started ===" "INFO"
    log_action "Operation: $operation" "INFO"
    
    case "$operation" in
        "apply")
            if [[ -z "$policy" ]]; then
                echo "Usage: $0 apply <policy_name> [compliance_framework]"
                echo "Available policies: ${!POLICY_TEMPLATES[*]}"
                exit 1
            fi
            enterprise_preferences_management "apply_policy" "$policy" "" "$compliance"
            ;;
        "hide")
            if [[ -z "$panes" ]]; then
                echo "Usage: $0 hide <pane1,pane2,...>"
                echo "Available panes: ${!PREFERENCE_PANES[*]}"
                exit 1
            fi
            enterprise_preferences_management "hide_panes" "" "$panes"
            ;;
        "disable")
            if [[ -z "$panes" ]]; then
                echo "Usage: $0 disable <pane1,pane2,...>"
                echo "Available panes: ${!PREFERENCE_PANES[*]}"
                exit 1
            fi
            enterprise_preferences_management "disable_panes" "" "$panes"
            ;;
        "restore")
            enterprise_preferences_management "restore_all"
            ;;
        "status")
            enterprise_preferences_management "status"
            ;;
        "audit")
            enterprise_preferences_management "audit" "" "" "$policy"
            ;;
        "list-policies")
            enterprise_preferences_management "list_policies"
            ;;
        "list-panes")
            enterprise_preferences_management "list_panes"
            ;;
        "help")
            echo "Usage: $0 [operation] [options...]"
            echo "Operations:"
            echo "  apply <policy> [compliance] - Apply enterprise policy"
            echo "  hide <panes> - Hide specific preference panes"
            echo "  disable <panes> - Disable specific preference panes"
            echo "  restore - Restore all preference panes"
            echo "  status - Show current preferences status"
            echo "  audit [compliance] - Perform compliance audit"
            echo "  list-policies - List available policies"
            echo "  list-panes - List available preference panes"
            echo "  help - Show this help"
            echo ""
            echo "Available Policies: ${!POLICY_TEMPLATES[*]}"
            echo "Compliance Frameworks: ${!COMPLIANCE_FRAMEWORKS[*]}"
            ;;
        *)
            log_action "ERROR: Unknown operation: $operation" "ERROR"
            echo "Use '$0 help' for usage information"
            exit 1
            ;;
    esac
    
    log_action "=== System preferences management completed ===" "INFO"
}

# Execute main function
main "$@"

Important Considerations

macOS Version Compatibility

  • Hiding Panes: Requires macOS 13.0 or later (HiddenPreferencePanes)
  • Disabling Panes: Works on macOS 10.2 and later (DisabledPreferencePanes)
  • Bundle Identifiers: May change between macOS versions
  • System Integrity Protection: Some restrictions may not apply with SIP enabled

Enterprise Deployment Notes

  • User Impact: Hidden/disabled panes affect all users on the device
  • Administrative Access: Changes require administrator privileges
  • Policy Testing: Always test policies on non-production devices first
  • Backup and Recovery: Maintain configuration backups for policy rollback

Security and Compliance Considerations

  • Principle of Least Privilege: Only restrict access to necessary preference panes
  • Audit Logging: All preference changes should be logged for compliance
  • Compliance Frameworks: Different industries require specific restrictions
  • User Training: Inform users about restricted functionality and alternatives

System Information Management on macOS

Collect and analyze comprehensive system information across your MacFleet devices using advanced system profiling, automated data collection, and enterprise-grade analytics. This tutorial provides powerful tools for implementing organizational device inventory, monitoring, and compliance reporting.

Understanding macOS System Information

macOS provides several tools for system information gathering:

  • system_profiler - Comprehensive system information collection
  • uname - Basic system and kernel information
  • sw_vers - Software version information
  • hwpref - Hardware preference data
  • ioreg - I/O Registry hardware information
  • System Information.app - GUI system information interface

Basic System Information Operations

Complete System Information

#!/bin/bash

# Get complete system information
echo "=== Complete System Information ==="
system_profiler

echo "System information collection completed"

List Available Data Types

#!/bin/bash

# List all available system profiler data types
echo "=== Available Data Types ==="
system_profiler --listDataTypes

echo "Data types listing completed"

Specific System Information

#!/bin/bash

# Get specific system information
DATA_TYPE="${1:-SPHardwareDataType}"

echo "=== $DATA_TYPE Information ==="
system_profiler "$DATA_TYPE"

echo "Specific system information retrieved"

Save System Report to File

#!/bin/bash

# Save system information to file
REPORT_FILE="${1:-/tmp/system_report_$(date +%Y%m%d_%H%M%S).txt}"

echo "=== Saving System Report ==="
system_profiler > "$REPORT_FILE"

echo "System report saved to: $REPORT_FILE"

Enterprise System Information Management System

#!/bin/bash

# MacFleet Enterprise System Information Management System
# Comprehensive system data collection, analysis, and monitoring

# Configuration
MACFLEET_DIR="/etc/macfleet"
SYSINFO_DIR="$MACFLEET_DIR/system_information"
REPORTS_DIR="$MACFLEET_DIR/reports"
COMPLIANCE_DIR="$MACFLEET_DIR/compliance"
AUDIT_DIR="$MACFLEET_DIR/audit"
LOG_FILE="/var/log/macfleet_system_information.log"
POLICIES_DIR="$MACFLEET_DIR/system_policies"
INVENTORY_DIR="$MACFLEET_DIR/inventory"

# Create directory structure
create_directories() {
    local dirs=("$MACFLEET_DIR" "$SYSINFO_DIR" "$REPORTS_DIR" "$COMPLIANCE_DIR" "$AUDIT_DIR" "$POLICIES_DIR" "$INVENTORY_DIR")
    for dir in "${dirs[@]}"; do
        [[ ! -d "$dir" ]] && mkdir -p "$dir"
    done
}

# Logging function
log_action() {
    local message="$1"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    echo "[$timestamp] $message" | tee -a "$LOG_FILE"
}

# System Information Categories for Enterprise Management
declare -A SYSTEM_CATEGORIES=(
    ["hardware_overview"]="SPHardwareDataType,SPMemoryDataType,SPStorageDataType"
    ["software_inventory"]="SPSoftwareDataType,SPApplicationsDataType,SPExtensionsDataType"
    ["network_configuration"]="SPNetworkDataType,SPBluetoothDataType,SPWWANDataType"
    ["security_configuration"]="SPFirewallDataType,SPManagedClientDataType,SPConfigurationProfileDataType"
    ["peripherals"]="SPUSBDataType,SPThunderboltDataType,SPAudioDataType,SPDisplaysDataType"
    ["system_diagnostics"]="SPPowerDataType,SPLogsDataType,SPDiagnosticsDataType"
    ["enterprise_management"]="SPManagedClientDataType,SPConfigurationProfileDataType,SPCertificatesDataType"
)

# Data Collection Policies
declare -A COLLECTION_POLICIES=(
    ["comprehensive"]="all_data_types,full_detail,include_sensitive,export_json"
    ["security_focused"]="security_data,certificates,firewall_config,managed_profiles"
    ["hardware_inventory"]="hardware_overview,storage_details,memory_config,peripherals"
    ["software_audit"]="applications,extensions,system_software,preferences"
    ["network_assessment"]="network_interfaces,bluetooth_devices,wireless_config"
    ["compliance_report"]="security_config,certificates,managed_profiles,audit_data"
)

# System Health Monitoring Thresholds
declare -A HEALTH_THRESHOLDS=(
    ["cpu_temperature_warning"]=80
    ["memory_pressure_warning"]=80
    ["storage_usage_warning"]=85
    ["battery_cycle_warning"]=800
    ["uptime_excessive_hours"]=168  # 1 week
)

# Comprehensive system information collection
collect_system_information() {
    local collection_policy="$1"
    local output_format="${2:-json}"
    local include_sensitive="${3:-false}"
    local collection_id="sysinfo_$(date +%Y%m%d_%H%M%S)"
    local output_file="$SYSINFO_DIR/${collection_id}.${output_format}"
    
    log_action "Starting system information collection: $collection_policy"
    
    # Initialize collection metadata
    local hostname=$(hostname)
    local serial_number=$(system_profiler SPHardwareDataType | grep "Serial Number" | awk '{print $4}')
    local model_identifier=$(system_profiler SPHardwareDataType | grep "Model Identifier" | awk '{print $3}')
    local os_version=$(sw_vers -productVersion)
    local build_version=$(sw_vers -buildVersion)
    local uptime=$(uptime | awk '{print $3,$4}' | sed 's/,//')
    
    # Collect data based on policy
    local collected_data=""
    local data_types=""
    
    case "$collection_policy" in
        "comprehensive")
            data_types=$(system_profiler --listDataTypes | tr '\n' ' ')
            ;;
        "security_focused")
            data_types="SPFirewallDataType SPManagedClientDataType SPConfigurationProfileDataType SPCertificatesDataType"
            ;;
        "hardware_inventory")
            data_types="SPHardwareDataType SPMemoryDataType SPStorageDataType SPUSBDataType SPDisplaysDataType SPAudioDataType"
            ;;
        "software_audit")
            data_types="SPSoftwareDataType SPApplicationsDataType SPExtensionsDataType SPPrefPaneDataType"
            ;;
        "network_assessment")
            data_types="SPNetworkDataType SPBluetoothDataType SPWWANDataType SPAirPortDataType"
            ;;
        "compliance_report")
            data_types="SPManagedClientDataType SPConfigurationProfileDataType SPCertificatesDataType SPFirewallDataType"
            ;;
    esac
    
    # Collect data for each specified type
    for data_type in $data_types; do
        [[ -z "$data_type" ]] && continue
        
        log_action "Collecting data type: $data_type"
        
        if [[ "$output_format" == "json" ]]; then
            local type_data=$(system_profiler -json "$data_type" 2>/dev/null)
            if [[ -n "$type_data" && "$type_data" != "null" ]]; then
                collected_data="$collected_data\"$data_type\":$type_data,"
            fi
        else
            local type_data=$(system_profiler "$data_type" 2>/dev/null)
            if [[ -n "$type_data" ]]; then
                collected_data="$collected_data\n=== $data_type ===\n$type_data\n"
            fi
        fi
    done
    
    # Additional system metrics
    local additional_metrics=""
    if [[ "$include_sensitive" == "true" || "$collection_policy" == "comprehensive" ]]; then
        local cpu_info=$(sysctl -n machdep.cpu.brand_string)
        local memory_total=$(system_profiler SPHardwareDataType | grep "Memory:" | awk '{print $2,$3}')
        local storage_info=$(df -h / | awk 'NR==2 {print $2,$3,$4,$5}')
        local network_interfaces=$(ifconfig | grep "^[a-z]" | awk '{print $1}' | sed 's/:$//' | tr '\n' ' ')
        local running_processes=$(ps aux | wc -l)
        local logged_in_users=$(who | wc -l)
        
        additional_metrics="{\"cpu_info\":\"$cpu_info\",\"memory_total\":\"$memory_total\",\"storage_info\":\"$storage_info\",\"network_interfaces\":\"$network_interfaces\",\"running_processes\":$running_processes,\"logged_in_users\":$logged_in_users}"
    fi
    
    # Create structured output
    if [[ "$output_format" == "json" ]]; then
        # Remove trailing comma from collected data
        collected_data="${collected_data%,}"
        
        cat > "$output_file" << EOF
{
  "collection_metadata": {
    "collection_id": "$collection_id",
    "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
    "policy": "$collection_policy",
    "hostname": "$hostname",
    "serial_number": "$serial_number",
    "model_identifier": "$model_identifier",
    "os_version": "$os_version",
    "build_version": "$build_version",
    "uptime": "$uptime"
  },
  "system_data": {$collected_data},
  "additional_metrics": $additional_metrics,
  "collection_summary": {
    "data_types_collected": $(echo "$data_types" | wc -w),
    "include_sensitive": "$include_sensitive",
    "collection_size_bytes": $(wc -c < "$output_file" 2>/dev/null || echo "0")
  }
}
EOF
    else
        cat > "$output_file" << EOF
=== MacFleet System Information Report ===
Collection ID: $collection_id
Timestamp: $(date)
Policy: $collection_policy
Hostname: $hostname
Serial Number: $serial_number
Model: $model_identifier
OS Version: $os_version ($build_version)
Uptime: $uptime

$collected_data
EOF
    fi
    
    log_action "System information collection completed: $output_file"
    echo "$output_file"
}

# System health analysis
analyze_system_health() {
    local analysis_type="$1"
    local health_report="$REPORTS_DIR/system_health_$(date +%Y%m%d_%H%M%S).json"
    
    log_action "Starting system health analysis: $analysis_type"
    
    # Collect basic health metrics
    local cpu_temp=$(sudo powermetrics -n 1 -s cpu_power | grep "CPU die temperature" | awk '{print $4}' 2>/dev/null || echo "0")
    local memory_pressure=$(vm_stat | grep "Pages compressed" | awk '{print $3}' | sed 's/\.//' | head -1)
    local storage_usage=$(df -h / | awk 'NR==2 {print $5}' | sed 's/%//')
    local uptime_seconds=$(sysctl -n kern.boottime | awk '{print $4}' | sed 's/,//')
    local current_time=$(date +%s)
    local uptime_hours=$(( (current_time - uptime_seconds) / 3600 ))
    
    # System load analysis
    local load_average=$(uptime | awk -F'load average:' '{print $2}' | awk '{print $1}' | sed 's/,//')
    local cpu_cores=$(sysctl -n hw.ncpu)
    local load_per_core=$(echo "scale=2; $load_average / $cpu_cores" | bc -l 2>/dev/null || echo "0")
    
    # Battery information (if available)
    local battery_cycle_count=0
    local battery_condition="Unknown"
    if system_profiler SPPowerDataType | grep -q "Cycle Count"; then
        battery_cycle_count=$(system_profiler SPPowerDataType | grep "Cycle Count" | awk '{print $3}')
        battery_condition=$(system_profiler SPPowerDataType | grep "Condition" | awk '{print $2}')
    fi
    
    # Determine health status
    local health_status="healthy"
    local health_alerts=""
    
    if [[ $(echo "$cpu_temp > ${HEALTH_THRESHOLDS[cpu_temperature_warning]}" | bc -l 2>/dev/null) -eq 1 ]]; then
        health_status="warning"
        health_alerts="$health_alerts\"High CPU temperature: ${cpu_temp}°C\","
    fi
    
    if [[ $storage_usage -gt ${HEALTH_THRESHOLDS[storage_usage_warning]} ]]; then
        health_status="warning"
        health_alerts="$health_alerts\"High storage usage: ${storage_usage}%\","
    fi
    
    if [[ $battery_cycle_count -gt ${HEALTH_THRESHOLDS[battery_cycle_warning]} ]]; then
        health_status="warning"
        health_alerts="$health_alerts\"High battery cycle count: $battery_cycle_count\","
    fi
    
    if [[ $uptime_hours -gt ${HEALTH_THRESHOLDS[uptime_excessive_hours]} ]]; then
        health_status="attention"
        health_alerts="$health_alerts\"Excessive uptime: ${uptime_hours} hours\","
    fi
    
    # Remove trailing comma
    health_alerts="${health_alerts%,}"
    
    # Create health report
    cat > "$health_report" << EOF
{
  "system_health_analysis": {
    "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
    "analysis_type": "$analysis_type",
    "health_status": "$health_status",
    "device_info": {
      "hostname": "$(hostname)",
      "serial_number": "$(system_profiler SPHardwareDataType | grep "Serial Number" | awk '{print $4}')",
      "model": "$(system_profiler SPHardwareDataType | grep "Model Identifier" | awk '{print $3}')",
      "os_version": "$(sw_vers -productVersion)"
    }
  },
  "health_metrics": {
    "cpu_temperature_celsius": "$cpu_temp",
    "memory_pressure_pages": "$memory_pressure",
    "storage_usage_percent": $storage_usage,
    "uptime_hours": $uptime_hours,
    "load_average": "$load_average",
    "load_per_core": "$load_per_core",
    "cpu_cores": $cpu_cores,
    "battery_cycle_count": $battery_cycle_count,
    "battery_condition": "$battery_condition"
  },
  "health_alerts": [$health_alerts],
  "recommendations": [
    $([ "$health_status" != "healthy" ] && echo "\"Address health alerts for optimal performance\",")
    $([ $uptime_hours -gt 72 ] && echo "\"Consider system restart for optimal performance\",")
    $([ $storage_usage -gt 80 ] && echo "\"Review storage usage and cleanup if necessary\",")
    "\"Regular health monitoring recommended\""
  ]
}
EOF
    
    if [[ "$health_status" != "healthy" ]]; then
        log_action "HEALTH WARNING: System health issues detected - $health_status"
    fi
    
    log_action "System health analysis completed: $health_report"
    echo "$health_report"
}

# Enterprise device inventory management
manage_device_inventory() {
    local inventory_action="$1"
    local device_group="${2:-default}"
    local inventory_file="$INVENTORY_DIR/device_inventory_${device_group}.json"
    
    log_action "Managing device inventory: $inventory_action for group $device_group"
    
    case "$inventory_action" in
        "register")
            # Register device in inventory
            local device_data=$(collect_system_information "hardware_inventory" "json" "false")
            local hostname=$(hostname)
            local serial_number=$(system_profiler SPHardwareDataType | grep "Serial Number" | awk '{print $4}')
            local model=$(system_profiler SPHardwareDataType | grep "Model Name" | awk -F': ' '{print $2}')
            local mac_address=$(ifconfig en0 | grep ether | awk '{print $2}')
            
            # Update inventory database
            if [[ -f "$inventory_file" ]]; then
                # Update existing inventory
                jq --arg hostname "$hostname" --arg serial "$serial_number" --arg model "$model" --arg mac "$mac_address" --arg timestamp "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
                   '.devices[$hostname] = {serial_number: $serial, model: $model, mac_address: $mac, last_updated: $timestamp, status: "active"}' \
                   "$inventory_file" > "${inventory_file}.tmp" && mv "${inventory_file}.tmp" "$inventory_file"
            else
                # Create new inventory
                jq -n --arg hostname "$hostname" --arg serial "$serial_number" --arg model "$model" --arg mac "$mac_address" --arg timestamp "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
                   '{inventory_metadata: {group: "'$device_group'", created: $timestamp}, devices: {($hostname): {serial_number: $serial, model: $model, mac_address: $mac, last_updated: $timestamp, status: "active"}}}' \
                   > "$inventory_file"
            fi
            
            log_action "Device registered in inventory: $hostname ($serial_number)"
            ;;
            
        "update")
            # Update device information
            local hostname=$(hostname)
            if [[ -f "$inventory_file" ]] && jq -e ".devices[\"$hostname\"]" "$inventory_file" >/dev/null; then
                jq --arg hostname "$hostname" --arg timestamp "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
                   '.devices[$hostname].last_updated = $timestamp | .devices[$hostname].status = "active"' \
                   "$inventory_file" > "${inventory_file}.tmp" && mv "${inventory_file}.tmp" "$inventory_file"
                log_action "Device inventory updated: $hostname"
            else
                log_action "Device not found in inventory, registering: $hostname"
                manage_device_inventory "register" "$device_group"
            fi
            ;;
            
        "list")
            # List devices in inventory
            if [[ -f "$inventory_file" ]]; then
                echo "=== Device Inventory for Group: $device_group ==="
                jq -r '.devices | to_entries[] | "\(.key): \(.value.model) (\(.value.serial_number)) - \(.value.status)"' "$inventory_file"
            else
                echo "No inventory found for group: $device_group"
            fi
            ;;
            
        "remove")
            # Remove device from inventory
            local hostname=$(hostname)
            if [[ -f "$inventory_file" ]]; then
                jq --arg hostname "$hostname" 'del(.devices[$hostname])' "$inventory_file" > "${inventory_file}.tmp" && mv "${inventory_file}.tmp" "$inventory_file"
                log_action "Device removed from inventory: $hostname"
            fi
            ;;
    esac
}

# Compliance and security reporting
generate_compliance_report() {
    local compliance_framework="$1"
    local report_file="$COMPLIANCE_DIR/compliance_${compliance_framework}_$(date +%Y%m%d_%H%M%S).json"
    
    log_action "Generating compliance report: $compliance_framework"
    
    # Collect security-relevant system information
    local security_data=$(collect_system_information "security_focused" "json" "true")
    
    # Check specific compliance requirements
    local filevault_status=$(fdesetup status | grep -q "On" && echo "enabled" || echo "disabled")
    local firewall_status=$(sudo /usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate | grep -q "enabled" && echo "enabled" || echo "disabled")
    local gatekeeper_status=$(spctl --status | grep -q "enabled" && echo "enabled" || echo "disabled")
    local sip_status=$(csrutil status | grep -q "enabled" && echo "enabled" || echo "disabled")
    local secure_boot_status=$(nvram 94b73556-2197-4702-82a8-3e1337dafbfb:AppleSecureBootPolicy 2>/dev/null | grep -q "2" && echo "full" || echo "reduced")
    
    # Software update status
    local auto_update_status=$(defaults read /Library/Preferences/com.apple.SoftwareUpdate AutomaticCheckEnabled 2>/dev/null || echo "0")
    local last_update_check=$(defaults read /Library/Preferences/com.apple.SoftwareUpdate LastSuccessfulDate 2>/dev/null || echo "Unknown")
    
    # Certificate information
    local certificate_count=$(security find-certificate -a | grep "labl" | wc -l)
    local expired_certificates=$(security find-certificate -a -p | openssl x509 -noout -checkend 0 2>/dev/null | grep -c "will expire" || echo "0")
    
    # Create compliance report based on framework
    case "$compliance_framework" in
        "nist")
            cat > "$report_file" << EOF
{
  "compliance_report": {
    "framework": "NIST Cybersecurity Framework",
    "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
    "device_info": {
      "hostname": "$(hostname)",
      "serial_number": "$(system_profiler SPHardwareDataType | grep "Serial Number" | awk '{print $4}')",
      "os_version": "$(sw_vers -productVersion)"
    }
  },
  "security_controls": {
    "identify": {
      "asset_management": "implemented",
      "system_inventory": "automated"
    },
    "protect": {
      "access_control": "$([ "$gatekeeper_status" == "enabled" ] && echo "implemented" || echo "needs_attention")",
      "data_security": "$([ "$filevault_status" == "enabled" ] && echo "implemented" || echo "needs_attention")",
      "protective_technology": "$([ "$firewall_status" == "enabled" ] && echo "implemented" || echo "needs_attention")"
    },
    "detect": {
      "security_monitoring": "basic",
      "malicious_code_protection": "$([ "$gatekeeper_status" == "enabled" ] && echo "implemented" || echo "needs_attention")"
    },
    "respond": {
      "incident_response": "manual",
      "communications": "standard"
    },
    "recover": {
      "recovery_planning": "$([ "$filevault_status" == "enabled" ] && echo "implemented" || echo "needs_attention")",
      "backup_procedures": "time_machine"
    }
  },
  "technical_controls": {
    "filevault_encryption": "$filevault_status",
    "firewall_protection": "$firewall_status",
    "gatekeeper_protection": "$gatekeeper_status",
    "system_integrity_protection": "$sip_status",
    "secure_boot": "$secure_boot_status",
    "automatic_updates": "$([ "$auto_update_status" == "1" ] && echo "enabled" || echo "disabled")",
    "certificate_management": {
      "total_certificates": $certificate_count,
      "expired_certificates": $expired_certificates
    }
  }
}
EOF
            ;;
            
        "hipaa")
            cat > "$report_file" << EOF
{
  "compliance_report": {
    "framework": "HIPAA Security Rule",
    "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
    "device_info": {
      "hostname": "$(hostname)",
      "serial_number": "$(system_profiler SPHardwareDataType | grep "Serial Number" | awk '{print $4}')",
      "os_version": "$(sw_vers -productVersion)"
    }
  },
  "administrative_safeguards": {
    "access_management": "policy_required",
    "workforce_training": "policy_required",
    "contingency_plan": "policy_required"
  },
  "physical_safeguards": {
    "facility_access": "policy_required",
    "workstation_security": "$([ "$filevault_status" == "enabled" ] && echo "implemented" || echo "needs_attention")",
    "device_controls": "$([ "$gatekeeper_status" == "enabled" ] && echo "implemented" || echo "needs_attention")"
  },
  "technical_safeguards": {
    "access_control": "$([ "$gatekeeper_status" == "enabled" ] && echo "implemented" || echo "needs_attention")",
    "audit_controls": "basic_logging",
    "integrity": "$([ "$sip_status" == "enabled" ] && echo "implemented" || echo "needs_attention")",
    "transmission_security": "$([ "$firewall_status" == "enabled" ] && echo "implemented" || echo "needs_attention")",
    "encryption": "$([ "$filevault_status" == "enabled" ] && echo "implemented" || echo "needs_attention")"
  }
}
EOF
            ;;
    esac
    
    log_action "Compliance report generated: $report_file"
    echo "Compliance report saved to: $report_file"
}

# Automated system monitoring and alerting
monitor_system_continuously() {
    local monitoring_interval="${1:-600}"  # 10 minutes default
    local alert_threshold="${2:-warning}"  # warning level default
    
    log_action "Starting continuous system monitoring (interval: ${monitoring_interval}s, threshold: $alert_threshold)"
    
    while true; do
        # Perform health analysis
        local health_report=$(analyze_system_health "continuous")
        local health_status=$(jq -r '.system_health_analysis.health_status' "$health_report" 2>/dev/null || echo "unknown")
        
        if [[ "$health_status" != "healthy" && "$health_status" != "unknown" ]]; then
            local hostname=$(hostname)
            log_action "SYSTEM ALERT: Health status is $health_status for $hostname"
            
            # Send system notification
            osascript -e "display notification \"System health: $health_status\" with title \"MacFleet System Monitor\""
            
            # Generate detailed report if critical
            if [[ "$health_status" == "critical" ]]; then
                collect_system_information "comprehensive" "json" "false"
            fi
        fi
        
        # Update device inventory
        manage_device_inventory "update" "monitored"
        
        # Log current status
        log_action "System monitoring check completed - Status: $health_status"
        
        sleep "$monitoring_interval"
    done
}

# Fleet deployment and management
deploy_to_fleet() {
    local deployment_action="$1"
    local fleet_file="$2"
    local deployment_policy="${3:-standard}"
    
    if [[ ! -f "$fleet_file" ]]; then
        log_action "ERROR: Fleet file not found: $fleet_file"
        return 1
    fi
    
    log_action "Deploying system information management to fleet: $deployment_action"
    
    while IFS= read -r host; do
        [[ -z "$host" || "$host" =~ ^#.*$ ]] && continue
        
        echo "Deploying to: $host"
        
        # Deploy system information management to remote host
        ssh "$host" "bash -s" << EOF
#!/bin/bash
# Remote deployment of system information management: $deployment_policy

# Create MacFleet directories
mkdir -p /etc/macfleet/{system_information,reports,compliance,audit,system_policies,inventory}

# Collect initial system information
echo "Collecting initial system information on \$(hostname)"

case "$deployment_policy" in
    "comprehensive")
        echo "Deploying comprehensive system monitoring"
        ;;
    "security_focused")
        echo "Deploying security-focused system monitoring"
        ;;
    "compliance_audit")
        echo "Deploying compliance audit configuration"
        ;;
esac

echo "System information management deployed on \$(hostname)"
EOF
        
        if [[ $? -eq 0 ]]; then
            log_action "Successfully deployed to: $host"
        else
            log_action "Failed to deploy to: $host"
        fi
        
    done < "$fleet_file"
    
    log_action "Fleet deployment completed"
}

# Health check and system validation
perform_system_health_check() {
    echo "=== MacFleet System Information Management Health Check ==="
    
    # Check system_profiler availability
    if command -v system_profiler >/dev/null 2>&1; then
        echo "✓ system_profiler: Available"
    else
        echo "✗ system_profiler: Not available"
    fi
    
    # Check system information accessibility
    local hardware_info=$(system_profiler SPHardwareDataType 2>/dev/null)
    if [[ -n "$hardware_info" ]]; then
        echo "✓ Hardware information: Accessible"
    else
        echo "⚠️  Hardware information: Limited access"
    fi
    
    # Check security status
    local filevault_status=$(fdesetup status)
    if echo "$filevault_status" | grep -q "On"; then
        echo "✓ FileVault: Enabled"
    else
        echo "○ FileVault: Disabled"
    fi
    
    # Check firewall status
    if sudo /usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate | grep -q "enabled"; then
        echo "✓ Firewall: Enabled"
    else
        echo "○ Firewall: Disabled"
    fi
    
    # Check Gatekeeper status
    if spctl --status | grep -q "enabled"; then
        echo "✓ Gatekeeper: Enabled"
    else
        echo "○ Gatekeeper: Disabled"
    fi
    
    # Check System Integrity Protection
    if csrutil status | grep -q "enabled"; then
        echo "✓ SIP: Enabled"
    else
        echo "⚠️  SIP: Disabled"
    fi
    
    # Check available storage space
    local available_space=$(df -h / | awk 'NR==2 {print $4}')
    echo "✓ Available storage: $available_space"
    
    # Check system uptime
    local uptime_info=$(uptime)
    echo "✓ System uptime: $uptime_info"
}

# Main execution function
main() {
    create_directories
    
    case "${1:-}" in
        "collect")
            collect_system_information "${2:-comprehensive}" "${3:-json}" "${4:-false}"
            ;;
        "analyze_health")
            analyze_system_health "${2:-standard}"
            ;;
        "inventory")
            manage_device_inventory "${2:-list}" "${3:-default}"
            ;;
        "compliance")
            generate_compliance_report "${2:-nist}"
            ;;
        "monitor")
            monitor_system_continuously "${2:-600}" "${3:-warning}"
            ;;
        "deploy_fleet")
            deploy_to_fleet "${2:-install}" "$3" "${4:-standard}"
            ;;
        "health_check")
            perform_system_health_check
            ;;
        "help"|*)
            echo "MacFleet Enterprise System Information Management System"
            echo ""
            echo "Usage: $0 <command> [options]"
            echo ""
            echo "Commands:"
            echo "  collect [policy] [format] [sensitive]    - Collect system information (comprehensive|security_focused|hardware_inventory|software_audit|network_assessment|compliance_report) [json|text] [true|false]"
            echo "  analyze_health [type]                    - Analyze system health (standard|detailed|continuous)"
            echo "  inventory <action> [group]               - Manage device inventory (register|update|list|remove) [group_name]"
            echo "  compliance [framework]                   - Generate compliance report (nist|hipaa|sox|iso27001)"
            echo "  monitor [interval] [threshold]           - Continuous monitoring (interval in seconds) (healthy|warning|critical)"
            echo "  deploy_fleet <action> <fleet_file> [policy] - Deploy to fleet (install|update|remove) [comprehensive|security_focused|compliance_audit]"
            echo "  health_check                             - Perform system health check"
            echo ""
            echo "Examples:"
            echo "  $0 collect comprehensive json false"
            echo "  $0 analyze_health detailed"
            echo "  $0 inventory register production"
            echo "  $0 compliance nist"
            echo "  $0 monitor 300 warning"
            echo "  $0 health_check"
            ;;
    esac
}

# Execute main function
main "$@"

System Information Data Types

The enterprise system supports comprehensive data type collection:

CategoryData TypesUse Case
Hardware OverviewSPHardwareDataType, SPMemoryDataType, SPStorageDataTypeAsset inventory and capacity planning
Software InventorySPSoftwareDataType, SPApplicationsDataType, SPExtensionsDataTypeLicense management and security auditing
Network ConfigurationSPNetworkDataType, SPBluetoothDataType, SPWWANDataTypeNetwork security and connectivity analysis
Security ConfigurationSPFirewallDataType, SPManagedClientDataType, SPConfigurationProfileDataTypeCompliance and security posture assessment
PeripheralsSPUSBDataType, SPThunderboltDataType, SPAudioDataType, SPDisplaysDataTypePeripheral management and security validation

Enterprise Collection Policies

Comprehensive Collection

# Collect all available system information
./sysinfo_manager.sh collect comprehensive json false

# Include sensitive information for detailed analysis
./sysinfo_manager.sh collect comprehensive json true

Security-Focused Collection

# Collect security-relevant information only
./sysinfo_manager.sh collect security_focused json false

# Generate security compliance report
./sysinfo_manager.sh compliance nist

Hardware Inventory

# Collect hardware inventory data
./sysinfo_manager.sh collect hardware_inventory json false

# Register device in enterprise inventory
./sysinfo_manager.sh inventory register production

System Health Monitoring

Health Analysis

# Perform standard health analysis
./sysinfo_manager.sh analyze_health standard

# Detailed health analysis with comprehensive metrics
./sysinfo_manager.sh analyze_health detailed

Continuous Monitoring

# Monitor system health every 10 minutes
./sysinfo_manager.sh monitor 600 warning

# Monitor system health every 5 minutes with critical threshold
./sysinfo_manager.sh monitor 300 critical

Enterprise Device Inventory

Inventory Management

# Register device in production inventory
./sysinfo_manager.sh inventory register production

# Update device information
./sysinfo_manager.sh inventory update production

# List all devices in inventory
./sysinfo_manager.sh inventory list production

# Remove device from inventory
./sysinfo_manager.sh inventory remove production

Compliance and Security Reporting

NIST Cybersecurity Framework

# Generate NIST compliance report
./sysinfo_manager.sh compliance nist

HIPAA Security Rule

# Generate HIPAA compliance report
./sysinfo_manager.sh compliance hipaa

Fleet Deployment Examples

Deploy to Development Fleet

Create a fleet file dev_fleet.txt:

dev-mac-01.company.com
dev-mac-02.company.com
dev-mac-03.company.com
# Deploy comprehensive system monitoring
./sysinfo_manager.sh deploy_fleet install dev_fleet.txt comprehensive

Deploy Security Monitoring

# Deploy security-focused monitoring to production fleet
./sysinfo_manager.sh deploy_fleet install prod_fleet.txt security_focused

Advanced Enterprise Features

Automated Data Collection

The system provides automated data collection capabilities:

  • Scheduled collection with customizable intervals
  • Policy-driven data gathering based on organizational requirements
  • Intelligent filtering to reduce data volume while maintaining completeness
  • Secure transmission of collected data to central repositories

System Health Analytics

Advanced health monitoring includes:

  • Performance metrics analysis and trending
  • Resource utilization monitoring and alerting
  • Security posture assessment and recommendations
  • Predictive maintenance based on system health indicators

Enterprise Integration

Integration capabilities include:

  • LDAP/Active Directory integration for user and device management
  • SIEM integration for security event correlation
  • Asset management system integration
  • Compliance framework alignment and reporting

Important Security Considerations

  • Data sensitivity requires appropriate handling and encryption
  • Access controls must be implemented for sensitive system information
  • Audit logging should track all system information access and collection
  • Network security must protect data transmission between devices
  • Compliance requirements vary by industry and geographic location

Performance and Scalability

The enterprise system is designed for:

  • Large-scale deployment across thousands of devices
  • Efficient data collection with minimal system impact
  • Scalable storage for historical data and trend analysis
  • High availability with redundancy and failover capabilities
  • Performance optimization for various hardware configurations

This comprehensive system transforms basic system information retrieval into an enterprise-grade device management and monitoring platform with advanced analytics, compliance reporting, and fleet-wide management capabilities.

Storage Management on macOS

Monitor and optimize storage across your MacFleet devices using advanced disk usage analysis, automated cleanup policies, and comprehensive storage management. This tutorial provides enterprise-grade tools for implementing organizational storage policies and fleet-wide storage optimization.

Understanding macOS Storage Management

macOS provides several command-line tools for storage management:

  • du - Directory usage analysis and space consumption
  • df - Disk free space and filesystem information
  • diskutil - Disk utility for advanced disk operations
  • tmutil - Time Machine utility for backup storage
  • Storage Management - GUI storage optimization interface

Basic Storage Operations

Check User Storage Usage

#!/bin/bash

# Check disk usage for all users
echo "=== User Storage Usage ==="
sudo du -hxd1 /Users

echo "Storage usage check completed"

Check Filesystem Usage

#!/bin/bash

# Check overall filesystem usage
echo "=== Filesystem Usage ==="
df -h

# Check specific filesystem
# df -h /dev/disk1s1

echo "Filesystem usage check completed"

Check Current Directory Usage

#!/bin/bash

# Check current directory usage
echo "=== Current Directory Usage ==="
du -sh *

echo "Directory usage check completed"

Enterprise Storage Management System

#!/bin/bash

# MacFleet Enterprise Storage Management System
# Comprehensive storage monitoring, optimization, and policy management

# Configuration
MACFLEET_DIR="/etc/macfleet"
STORAGE_DIR="$MACFLEET_DIR/storage_management"
REPORTS_DIR="$MACFLEET_DIR/reports"
COMPLIANCE_DIR="$MACFLEET_DIR/compliance"
AUDIT_DIR="$MACFLEET_DIR/audit"
LOG_FILE="/var/log/macfleet_storage_management.log"
POLICIES_DIR="$MACFLEET_DIR/storage_policies"
CLEANUP_DIR="$MACFLEET_DIR/cleanup_logs"

# Create directory structure
create_directories() {
    local dirs=("$MACFLEET_DIR" "$STORAGE_DIR" "$REPORTS_DIR" "$COMPLIANCE_DIR" "$AUDIT_DIR" "$POLICIES_DIR" "$CLEANUP_DIR")
    for dir in "${dirs[@]}"; do
        [[ ! -d "$dir" ]] && mkdir -p "$dir"
    done
}

# Logging function
log_action() {
    local message="$1"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    echo "[$timestamp] $message" | tee -a "$LOG_FILE"
}

# Storage Categories for Enterprise Management
declare -A STORAGE_CATEGORIES=(
    ["system_critical"]="macOS,system_apps,kernel_extensions,system_logs"
    ["user_data"]="documents,downloads,desktop,pictures,movies"
    ["application_data"]="app_support,caches,preferences,saved_states"
    ["development"]="xcode,simulators,build_artifacts,source_code"
    ["media_content"]="photos,videos,music,podcasts"
    ["temporary_files"]="caches,logs,trash,temp_downloads"
    ["backup_data"]="time_machine,local_snapshots,manual_backups"
)

# Storage Policies for Different Environments
declare -A STORAGE_POLICIES=(
    ["aggressive_cleanup"]="clear_caches,remove_logs_7days,empty_trash,remove_downloads_30days"
    ["conservative_cleanup"]="clear_caches,remove_logs_30days,archive_old_files"
    ["development_optimized"]="preserve_builds,clear_simulator_data,optimize_xcode_cache"
    ["media_optimized"]="compress_videos,optimize_photos,remove_duplicates"
    ["security_focused"]="secure_delete,encrypt_backups,audit_sensitive_files"
    ["compliance_strict"]="retain_all,encrypt_storage,detailed_logging,no_auto_delete"
)

# Disk Space Thresholds for Different Alert Levels
declare -A ALERT_THRESHOLDS=(
    ["critical"]=5     # Less than 5GB free
    ["warning"]=10     # Less than 10GB free
    ["low"]=20         # Less than 20GB free
    ["optimal"]=50     # Less than 50GB free
)

# Comprehensive storage analysis
analyze_storage_comprehensive() {
    local analysis_level="$1"
    local output_file="$STORAGE_DIR/storage_analysis_$(date +%Y%m%d_%H%M%S).json"
    
    log_action "Starting comprehensive storage analysis: $analysis_level"
    
    # Get basic filesystem information
    local total_space=$(df -h / | awk 'NR==2 {print $2}')
    local used_space=$(df -h / | awk 'NR==2 {print $3}')
    local available_space=$(df -h / | awk 'NR==2 {print $4}')
    local usage_percentage=$(df -h / | awk 'NR==2 {print $5}' | sed 's/%//')
    
    # Convert to bytes for calculations
    local available_gb=$(df -g / | awk 'NR==2 {print $4}')
    
    # Determine alert level
    local alert_level="optimal"
    if [[ $available_gb -lt ${ALERT_THRESHOLDS["critical"]} ]]; then
        alert_level="critical"
    elif [[ $available_gb -lt ${ALERT_THRESHOLDS["warning"]} ]]; then
        alert_level="warning"
    elif [[ $available_gb -lt ${ALERT_THRESHOLDS["low"]} ]]; then
        alert_level="low"
    fi
    
    # Analyze user directories
    local user_data=""
    while IFS= read -r user_dir; do
        if [[ -d "$user_dir" && ! "$user_dir" =~ (Shared|.localized)$ ]]; then
            local user_name=$(basename "$user_dir")
            local user_size=$(du -sg "$user_dir" 2>/dev/null | awk '{print $1}' || echo "0")
            user_data="$user_data{\"user\":\"$user_name\",\"size_gb\":$user_size},"
        fi
    done <<< "$(find /Users -maxdepth 1 -type d)"
    
    # Remove trailing comma
    user_data="${user_data%,}"
    
    # Analyze large directories
    local large_dirs=""
    if [[ "$analysis_level" == "detailed" || "$analysis_level" == "full" ]]; then
        while IFS= read -r dir_info; do
            local size=$(echo "$dir_info" | awk '{print $1}')
            local path=$(echo "$dir_info" | awk '{$1=""; print substr($0,2)}')
            [[ $size -gt 1 ]] && large_dirs="$large_dirs{\"path\":\"$path\",\"size_gb\":$size},"
        done <<< "$(sudo du -sg /Applications /Library /System /Users 2>/dev/null | sort -nr)"
        large_dirs="${large_dirs%,}"
    fi
    
    # Analyze system caches and temporary files
    local temp_data=""
    local cache_size=$(du -sg ~/Library/Caches 2>/dev/null | awk '{print $1}' || echo "0")
    local log_size=$(du -sg /var/log 2>/dev/null | awk '{print $1}' || echo "0")
    local trash_size=$(du -sg ~/.Trash 2>/dev/null | awk '{print $1}' || echo "0")
    
    temp_data="{\"caches_gb\":$cache_size,\"logs_gb\":$log_size,\"trash_gb\":$trash_size}"
    
    # Create comprehensive report
    cat > "$output_file" << EOF
{
  "storage_analysis": {
    "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
    "analysis_level": "$analysis_level",
    "alert_level": "$alert_level",
    "filesystem_info": {
      "total_space": "$total_space",
      "used_space": "$used_space",
      "available_space": "$available_space",
      "usage_percentage": $usage_percentage,
      "available_gb": $available_gb
    },
    "user_breakdown": [$user_data],
    "large_directories": [$large_dirs],
    "temporary_files": $temp_data
  },
  "recommendations": [
    $([ $alert_level == "critical" ] && echo "\"Immediate cleanup required - critical storage level\",")
    $([ $alert_level == "warning" ] && echo "\"Storage cleanup recommended\",")
    $([ $cache_size -gt 5 ] && echo "\"Clear application caches ($cache_size GB)\",")
    $([ $trash_size -gt 1 ] && echo "\"Empty trash ($trash_size GB)\",")
    $([ $log_size -gt 2 ] && echo "\"Archive old log files ($log_size GB)\",")
    "\"Regular storage monitoring recommended\""
  ]
}
EOF
    
    log_action "Storage analysis completed. Report: $output_file"
    
    # Alert if critical
    if [[ "$alert_level" == "critical" ]]; then
        log_action "CRITICAL ALERT: Storage space critically low ($available_gb GB remaining)"
        # Send alert notification
        osascript -e "display notification \"Critical storage space: $available_gb GB remaining\" with title \"MacFleet Storage Alert\""
    fi
    
    echo "$output_file"
}

# Advanced storage cleanup with policies
perform_storage_cleanup() {
    local cleanup_policy="$1"
    local dry_run="${2:-false}"
    local cleanup_report="$CLEANUP_DIR/cleanup_$(date +%Y%m%d_%H%M%S).json"
    
    log_action "Starting storage cleanup with policy: $cleanup_policy (dry_run: $dry_run)"
    
    local total_freed=0
    local operations=""
    
    case "$cleanup_policy" in
        "aggressive_cleanup")
            # Clear application caches
            if [[ "$dry_run" == "false" ]]; then
                local cache_size_before=$(du -sg ~/Library/Caches 2>/dev/null | awk '{print $1}' || echo "0")
                find ~/Library/Caches -type f -mtime +1 -delete 2>/dev/null
                local cache_size_after=$(du -sg ~/Library/Caches 2>/dev/null | awk '{print $1}' || echo "0")
                local cache_freed=$((cache_size_before - cache_size_after))
                total_freed=$((total_freed + cache_freed))
                operations="$operations{\"operation\":\"clear_caches\",\"freed_gb\":$cache_freed},"
            fi
            
            # Remove old logs (7 days)
            if [[ "$dry_run" == "false" ]]; then
                local log_size_before=$(du -sg ~/Library/Logs 2>/dev/null | awk '{print $1}' || echo "0")
                find ~/Library/Logs -type f -mtime +7 -delete 2>/dev/null
                local log_size_after=$(du -sg ~/Library/Logs 2>/dev/null | awk '{print $1}' || echo "0")
                local log_freed=$((log_size_before - log_size_after))
                total_freed=$((total_freed + log_freed))
                operations="$operations{\"operation\":\"remove_old_logs\",\"freed_gb\":$log_freed},"
            fi
            
            # Empty trash
            if [[ "$dry_run" == "false" ]]; then
                local trash_size=$(du -sg ~/.Trash 2>/dev/null | awk '{print $1}' || echo "0")
                rm -rf ~/.Trash/*
                total_freed=$((total_freed + trash_size))
                operations="$operations{\"operation\":\"empty_trash\",\"freed_gb\":$trash_size},"
            fi
            
            # Remove old downloads (30 days)
            if [[ "$dry_run" == "false" ]]; then
                local downloads_size_before=$(du -sg ~/Downloads 2>/dev/null | awk '{print $1}' || echo "0")
                find ~/Downloads -type f -mtime +30 -delete 2>/dev/null
                local downloads_size_after=$(du -sg ~/Downloads 2>/dev/null | awk '{print $1}' || echo "0")
                local downloads_freed=$((downloads_size_before - downloads_size_after))
                total_freed=$((total_freed + downloads_freed))
                operations="$operations{\"operation\":\"remove_old_downloads\",\"freed_gb\":$downloads_freed},"
            fi
            ;;
            
        "development_optimized")
            # Clear Xcode derived data
            if [[ -d ~/Library/Developer/Xcode/DerivedData && "$dry_run" == "false" ]]; then
                local derived_size=$(du -sg ~/Library/Developer/Xcode/DerivedData 2>/dev/null | awk '{print $1}' || echo "0")
                rm -rf ~/Library/Developer/Xcode/DerivedData/*
                total_freed=$((total_freed + derived_size))
                operations="$operations{\"operation\":\"clear_xcode_derived_data\",\"freed_gb\":$derived_size},"
            fi
            
            # Clear iOS Simulator data
            if [[ -d ~/Library/Developer/CoreSimulator && "$dry_run" == "false" ]]; then
                local sim_size_before=$(du -sg ~/Library/Developer/CoreSimulator 2>/dev/null | awk '{print $1}' || echo "0")
                xcrun simctl delete unavailable
                local sim_size_after=$(du -sg ~/Library/Developer/CoreSimulator 2>/dev/null | awk '{print $1}' || echo "0")
                local sim_freed=$((sim_size_before - sim_size_after))
                total_freed=$((total_freed + sim_freed))
                operations="$operations{\"operation\":\"cleanup_simulator_data\",\"freed_gb\":$sim_freed},"
            fi
            ;;
            
        "media_optimized")
            # Find and report duplicate files
            if [[ "$dry_run" == "false" ]]; then
                log_action "Scanning for duplicate media files..."
                # This is a placeholder for duplicate detection logic
                operations="$operations{\"operation\":\"duplicate_scan\",\"freed_gb\":0},"
            fi
            
            # Optimize photo library (placeholder)
            log_action "Photo library optimization available through Photos app"
            operations="$operations{\"operation\":\"photo_optimization_recommended\",\"freed_gb\":0},"
            ;;
    esac
    
    # Remove trailing comma
    operations="${operations%,}"
    
    # Create cleanup report
    cat > "$cleanup_report" << EOF
{
  "cleanup_report": {
    "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
    "policy": "$cleanup_policy",
    "dry_run": "$dry_run",
    "total_freed_gb": $total_freed,
    "operations": [$operations]
  },
  "storage_after_cleanup": {
    "available_space": "$(df -h / | awk 'NR==2 {print $4}')",
    "usage_percentage": "$(df -h / | awk 'NR==2 {print $5}')"
  }
}
EOF
    
    if [[ "$dry_run" == "false" ]]; then
        log_action "Cleanup completed. Total space freed: ${total_freed}GB"
    else
        log_action "Dry run completed. Would free approximately: ${total_freed}GB"
    fi
    
    echo "$cleanup_report"
}

# Storage monitoring and alerting
monitor_storage_continuously() {
    local monitoring_interval="${1:-300}"  # 5 minutes default
    local alert_threshold="${2:-10}"       # 10GB default
    
    log_action "Starting continuous storage monitoring (interval: ${monitoring_interval}s, threshold: ${alert_threshold}GB)"
    
    while true; do
        local available_gb=$(df -g / | awk 'NR==2 {print $4}')
        local usage_percent=$(df -h / | awk 'NR==2 {print $5}' | sed 's/%//')
        
        if [[ $available_gb -lt $alert_threshold ]]; then
            log_action "STORAGE ALERT: Only ${available_gb}GB remaining (${usage_percent}% used)"
            
            # Send system notification
            osascript -e "display notification \"Low storage: ${available_gb}GB remaining\" with title \"MacFleet Storage Monitor\""
            
            # Optionally trigger automatic cleanup
            if [[ $available_gb -lt 5 ]]; then
                log_action "Triggering emergency cleanup..."
                perform_storage_cleanup "aggressive_cleanup" "false"
            fi
        fi
        
        # Log current status
        log_action "Storage status: ${available_gb}GB available (${usage_percent}% used)"
        
        sleep "$monitoring_interval"
    done
}

# Enterprise storage reporting
generate_storage_report() {
    local report_type="$1"
    local report_file="$REPORTS_DIR/storage_enterprise_$(date +%Y%m%d_%H%M%S).json"
    
    log_action "Generating enterprise storage report: $report_type"
    
    # Collect comprehensive storage data
    local filesystem_data=$(df -h | grep -v "tmpfs\|devfs" | awk 'NR>1 {print "{\"filesystem\":\""$1"\",\"size\":\""$2"\",\"used\":\""$3"\",\"available\":\""$4"\",\"usage_percent\":\""$5"\"}"}' | tr '\n' ',' | sed 's/,$//')
    
    # Analyze user storage patterns
    local user_analysis=""
    local total_users=0
    local total_user_storage=0
    
    while IFS= read -r user_dir; do
        if [[ -d "$user_dir" && ! "$user_dir" =~ (Shared|.localized)$ ]]; then
            local user_name=$(basename "$user_dir")
            local user_size_gb=$(du -sg "$user_dir" 2>/dev/null | awk '{print $1}' || echo "0")
            ((total_users++))
            total_user_storage=$((total_user_storage + user_size_gb))
            user_analysis="$user_analysis{\"user\":\"$user_name\",\"storage_gb\":$user_size_gb},"
        fi
    done <<< "$(find /Users -maxdepth 1 -type d)"
    
    user_analysis="${user_analysis%,}"
    local avg_user_storage=$((total_user_storage / total_users))
    
    # Application storage analysis
    local app_storage=""
    if [[ -d /Applications ]]; then
        while IFS= read -r app_info; do
            local size=$(echo "$app_info" | awk '{print $1}')
            local app_path=$(echo "$app_info" | awk '{$1=""; print substr($0,2)}')
            local app_name=$(basename "$app_path")
            [[ $size -gt 0 ]] && app_storage="$app_storage{\"application\":\"$app_name\",\"size_gb\":$size},"
        done <<< "$(du -sg /Applications/*.app 2>/dev/null | sort -nr | head -20)"
        app_storage="${app_storage%,}"
    fi
    
    # System health indicators
    local health_indicators=""
    local available_gb=$(df -g / | awk 'NR==2 {print $4}')
    local health_status="healthy"
    
    if [[ $available_gb -lt 5 ]]; then
        health_status="critical"
    elif [[ $available_gb -lt 10 ]]; then
        health_status="warning"
    elif [[ $available_gb -lt 20 ]]; then
        health_status="low"
    fi
    
    health_indicators="{\"status\":\"$health_status\",\"available_gb\":$available_gb,\"recommendation\":\"$([ "$health_status" != "healthy" ] && echo "Cleanup required" || echo "Storage optimal")\"}"
    
    # Create comprehensive enterprise report
    cat > "$report_file" << EOF
{
  "enterprise_storage_report": {
    "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
    "report_type": "$report_type",
    "device_info": {
      "hostname": "$(hostname)",
      "mac_address": "$(ifconfig en0 | grep ether | awk '{print $2}')",
      "serial_number": "$(system_profiler SPHardwareDataType | grep 'Serial Number' | awk '{print $4}')"
    }
  },
  "storage_overview": {
    "filesystems": [$filesystem_data],
    "health_status": $health_indicators
  },
  "user_analysis": {
    "total_users": $total_users,
    "total_user_storage_gb": $total_user_storage,
    "average_user_storage_gb": $avg_user_storage,
    "user_breakdown": [$user_analysis]
  },
  "application_analysis": {
    "top_applications": [$app_storage]
  },
  "compliance_info": {
    "data_retention_policy": "enterprise_standard",
    "encryption_status": "$(fdesetup status | grep -q "On" && echo "enabled" || echo "disabled")",
    "backup_status": "$(tmutil status | grep -q "Running" && echo "active" || echo "inactive")"
  },
  "recommendations": [
    $([ "$health_status" == "critical" ] && echo "\"Immediate storage cleanup required\",")
    $([ $total_user_storage -gt 100 ] && echo "\"Consider user storage policies\",")
    $([ $available_gb -lt 20 ] && echo "\"Implement automated cleanup policies\",")
    "\"Regular storage monitoring recommended\""
  ]
}
EOF
    
    log_action "storage report generated: $report_file"
    echo "$report_file"
}

# Storage policy enforcement
enforce_storage_policies() {
    local policy_level="$1"
    
    log_action "Enforcing storage policies: $policy_level"
    
    case "$policy_level" in
        "enterprise_standard")
            # Standard enterprise storage policies
            log_action "Applying enterprise standard storage policies"
            
            # Set up automatic cleanup schedules
            cat > /tmp/macfleet_storage_cleanup.plist << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.macfleet.storage.cleanup</string>
    <key>ProgramArguments</key>
    <array>
        <string>/bin/bash</string>
        <string>-c</string>
        <string>$(realpath "$0") perform_storage_cleanup conservative_cleanup false</string>
    </array>
    <key>StartCalendarInterval</key>
    <dict>
        <key>Hour</key>
        <integer>2</integer>
        <key>Minute</key>
        <integer>0</integer>
    </dict>
    <key>StandardOutPath</key>
    <string>/var/log/macfleet_storage_cleanup.log</string>
    <key>StandardErrorPath</key>
    <string>/var/log/macfleet_storage_cleanup.log</string>
</dict>
</plist>
EOF
            sudo mv /tmp/macfleet_storage_cleanup.plist /Library/LaunchDaemons/
            sudo launchctl load /Library/LaunchDaemons/com.macfleet.storage.cleanup.plist
            ;;
            
        "development_team")
            # Policies optimized for development teams
            log_action "Applying development team storage policies"
            perform_storage_cleanup "development_optimized" "false"
            ;;
            
        "media_production")
            # Policies for media production environments
            log_action "Applying media production storage policies"
            perform_storage_cleanup "media_optimized" "false"
            ;;
    esac
    
    log_action "Storage policies enforcement completed: $policy_level"
}

# Storage optimization recommendations
generate_optimization_recommendations() {
    local analysis_file="$1"
    local recommendations_file="$REPORTS_DIR/storage_recommendations_$(date +%Y%m%d_%H%M%S).json"
    
    log_action "Generating storage optimization recommendations"
    
    # Analyze current storage state
    local available_gb=$(df -g / | awk 'NR==2 {print $4}')
    local usage_percent=$(df -h / | awk 'NR==2 {print $5}' | sed 's/%//')
    
    # Check for common storage issues
    local cache_size=$(du -sg ~/Library/Caches 2>/dev/null | awk '{print $1}' || echo "0")
    local downloads_size=$(du -sg ~/Downloads 2>/dev/null | awk '{print $1}' || echo "0")
    local trash_size=$(du -sg ~/.Trash 2>/dev/null | awk '{print $1}' || echo "0")
    local log_size=$(sudo du -sg /var/log 2>/dev/null | awk '{print $1}' || echo "0")
    
    # Generate recommendations based on analysis
    local recommendations=""
    local priority="medium"
    
    if [[ $available_gb -lt 10 ]]; then
        priority="high"
        recommendations="$recommendations\"Immediate cleanup required - storage critically low\","
    fi
    
    if [[ $cache_size -gt 5 ]]; then
        recommendations="$recommendations\"Clear application caches (${cache_size}GB potential savings)\","
    fi
    
    if [[ $downloads_size -gt 10 ]]; then
        recommendations="$recommendations\"Review Downloads folder (${downloads_size}GB)\","
    fi
    
    if [[ $trash_size -gt 1 ]]; then
        recommendations="$recommendations\"Empty Trash (${trash_size}GB immediate savings)\","
    fi
    
    if [[ $log_size -gt 5 ]]; then
        recommendations="$recommendations\"Archive old log files (${log_size}GB)\","
    fi
    
    if [[ $usage_percent -gt 80 ]]; then
        recommendations="$recommendations\"Consider external storage or cloud archiving\","
    fi
    
    # Remove trailing comma
    recommendations="${recommendations%,}"
    
    cat > "$recommendations_file" << EOF
{
  "optimization_recommendations": {
    "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
    "priority_level": "$priority",
    "current_status": {
      "available_gb": $available_gb,
      "usage_percent": $usage_percent,
      "storage_health": "$([ $available_gb -gt 20 ] && echo "healthy" || echo "attention_required")"
    },
    "immediate_actions": [$recommendations],
    "long_term_strategies": [
      "Implement automated cleanup policies",
      "Set up storage monitoring alerts",
      "Consider cloud storage integration",
      "Regular storage health assessments"
    ],
    "potential_savings": {
      "caches_gb": $cache_size,
      "downloads_gb": $downloads_size,
      "trash_gb": $trash_size,
      "logs_gb": $log_size,
      "total_potential_gb": $((cache_size + downloads_size + trash_size + log_size))
    }
  }
}
EOF
    
    log_action "Storage optimization recommendations generated: $recommendations_file"
    echo "$recommendations_file"
}

# Fleet storage management
deploy_storage_management_to_fleet() {
    local fleet_file="$1"
    local management_policy="$2"
    
    if [[ ! -f "$fleet_file" ]]; then
        log_action "ERROR: Fleet file not found: $fleet_file"
        return 1
    fi
    
    log_action "Deploying storage management to fleet with policy: $management_policy"
    
    while IFS= read -r host; do
        [[ -z "$host" || "$host" =~ ^#.*$ ]] && continue
        
        echo "Deploying storage management to: $host"
        
        # Deploy storage management script to remote host
        ssh "$host" "bash -s" << EOF
#!/bin/bash
# Remote deployment of storage management: $management_policy

# Create MacFleet directories
mkdir -p /etc/macfleet/{storage_management,reports,compliance,audit,storage_policies,cleanup_logs}

# Set up basic storage monitoring
echo "Setting up storage monitoring for policy: $management_policy"

case "$management_policy" in
    "enterprise_standard")
        # Set up enterprise-grade monitoring
        echo "Configuring enterprise storage monitoring"
        ;;
    "development_optimized")
        # Set up development-focused monitoring
        echo "Configuring development storage optimization"
        ;;
    "media_production")
        # Set up media production monitoring
        echo "Configuring media production storage management"
        ;;
esac

echo "Storage management deployment completed on \$(hostname)"
EOF
        
        if [[ $? -eq 0 ]]; then
            log_action "Successfully deployed storage management to: $host"
        else
            log_action "Failed to deploy storage management to: $host"
        fi
        
    done < "$fleet_file"
    
    log_action "Fleet storage management deployment completed"
}

# Health check and system validation
perform_storage_health_check() {
    echo "=== MacFleet Storage Management Health Check ==="
    
    # Check disk space
    local available_gb=$(df -g / | awk 'NR==2 {print $4}')
    local usage_percent=$(df -h / | awk 'NR==2 {print $5}' | sed 's/%//')
    
    if [[ $available_gb -gt 20 ]]; then
        echo "✓ Disk space: Healthy (${available_gb}GB available)"
    elif [[ $available_gb -gt 10 ]]; then
        echo "⚠️  Disk space: Low (${available_gb}GB available)"
    else
        echo "🔴 Disk space: Critical (${available_gb}GB available)"
    fi
    
    # Check for large cache files
    local cache_size=$(du -sg ~/Library/Caches 2>/dev/null | awk '{print $1}' || echo "0")
    if [[ $cache_size -gt 5 ]]; then
        echo "⚠️  Large caches detected: ${cache_size}GB"
    else
        echo "✓ Cache size: Normal (${cache_size}GB)"
    fi
    
    # Check trash
    local trash_size=$(du -sg ~/.Trash 2>/dev/null | awk '{print $1}' || echo "0")
    if [[ $trash_size -gt 1 ]]; then
        echo "○ Trash contains: ${trash_size}GB (can be emptied)"
    else
        echo "✓ Trash: Empty"
    fi
    
    # Check FileVault encryption
    if fdesetup status | grep -q "On"; then
        echo "✓ FileVault: Enabled"
    else
        echo "○ FileVault: Disabled"
    fi
    
    # Check Time Machine
    if tmutil status | grep -q "Running"; then
        echo "✓ Time Machine: Active"
    else
        echo "○ Time Machine: Inactive"
    fi
    
    # Check APFS snapshots
    local snapshots=$(tmutil listlocalsnapshots / | wc -l)
    if [[ $snapshots -gt 10 ]]; then
        echo "⚠️  Many local snapshots: $snapshots (consider cleanup)"
    else
        echo "✓ Local snapshots: $snapshots"
    fi
}

# Main execution function
main() {
    create_directories
    
    case "${1:-}" in
        "analyze")
            analyze_storage_comprehensive "${2:-standard}"
            ;;
        "cleanup")
            perform_storage_cleanup "${2:-conservative_cleanup}" "${3:-false}"
            ;;
        "monitor")
            monitor_storage_continuously "${2:-300}" "${3:-10}"
            ;;
        "report")
            generate_storage_report "${2:-comprehensive}"
            ;;
        "enforce_policies")
            enforce_storage_policies "${2:-enterprise_standard}"
            ;;
        "recommendations")
            generate_optimization_recommendations "$2"
            ;;
        "deploy_fleet")
            deploy_storage_management_to_fleet "$2" "${3:-enterprise_standard}"
            ;;
        "health_check")
            perform_storage_health_check
            ;;
        "help"|*)
            echo "MacFleet Enterprise Storage Management System"
            echo ""
            echo "Usage: $0 <command> [options]"
            echo ""
            echo "Commands:"
            echo "  analyze [level]                     - Analyze storage (basic|standard|detailed|full)"
            echo "  cleanup <policy> [dry_run]          - Perform cleanup (aggressive_cleanup|conservative_cleanup|development_optimized|media_optimized) [true|false]"
            echo "  monitor [interval] [threshold]      - Continuous monitoring (interval in seconds, threshold in GB)"
            echo "  report [type]                       - Generate enterprise report (comprehensive|summary|compliance)"
            echo "  enforce_policies [policy]           - Enforce storage policies (enterprise_standard|development_team|media_production)"
            echo "  recommendations [analysis_file]     - Generate optimization recommendations"
            echo "  deploy_fleet <fleet_file> [policy]  - Deploy to fleet"
            echo "  health_check                        - Perform system health check"
            echo ""
            echo "Examples:"
            echo "  $0 analyze detailed"
            echo "  $0 cleanup aggressive_cleanup false"
            echo "  $0 monitor 600 15"
            echo "  $0 report comprehensive"
            echo "  $0 health_check"
            ;;
    esac
}

# Execute main function
main "$@"

Storage Analysis and Monitoring

The enterprise system provides comprehensive storage analysis:

Analysis LevelScopeDetailsUse Case
BasicOverall disk usageQuick space checkDaily monitoring
StandardUser and system breakdownDetailed usage patternsWeekly reviews
DetailedLarge directories analysisComprehensive inventoryMonthly audits
FullComplete system analysisEnterprise reportingQuarterly assessments

Storage Cleanup Policies

Aggressive Cleanup Policy

# Perform aggressive cleanup to reclaim maximum space
./storage_manager.sh cleanup aggressive_cleanup false

# Dry run to see what would be cleaned
./storage_manager.sh cleanup aggressive_cleanup true

Development-Optimized Cleanup

# Clean development-specific cache and build data
./storage_manager.sh cleanup development_optimized false

Media Production Cleanup

# Optimize storage for media production workflows
./storage_manager.sh cleanup media_optimized false

Enterprise Storage Monitoring

Continuous Monitoring

# Monitor storage every 5 minutes with 10GB threshold
./storage_manager.sh monitor 300 10

# Monitor storage every hour with 20GB threshold
./storage_manager.sh monitor 3600 20

Automated Alerts

The system provides intelligent alerting:

  • Critical Alert - Less than 5GB remaining
  • Warning Alert - Less than 10GB remaining
  • Low Storage - Less than 20GB remaining
  • Optimal - More than 50GB remaining

Storage Policy Management

Enterprise Standard Policy

# Apply enterprise standard storage policies
./storage_manager.sh enforce_policies enterprise_standard

Development Team Policy

# Apply development-focused storage policies
./storage_manager.sh enforce_policies development_team

Media Production Policy

# Apply media production storage policies
./storage_manager.sh enforce_policies media_production

Fleet Deployment Examples

Deploy to Development Fleet

Create a fleet file dev_fleet.txt:

dev-mac-01.company.com
dev-mac-02.company.com
dev-mac-03.company.com
# Deploy development-optimized storage management
./storage_manager.sh deploy_fleet dev_fleet.txt development_team

Deploy to Production Fleet

# Deploy enterprise standard storage management
./storage_manager.sh deploy_fleet prod_fleet.txt enterprise_standard

Advanced Storage Features

Storage Analytics and Reporting

The system provides comprehensive enterprise reporting:

  • Usage patterns across users and applications
  • Cost analysis for storage optimization
  • Compliance reporting for regulatory requirements
  • Trend analysis for capacity planning

Automated Optimization

Advanced optimization features include:

  • Duplicate file detection and removal
  • Cache management with intelligent cleanup
  • Log rotation and archival
  • Backup optimization and verification

Security and Compliance

Enterprise security features:

  • Encrypted storage verification and monitoring
  • Audit trails for all storage operations
  • Data retention policy enforcement
  • Secure deletion for sensitive data

Important Storage Considerations

  • FileVault encryption should be enabled for enterprise security
  • Time Machine backups require adequate external storage
  • APFS snapshots consume storage and should be monitored
  • Application caches can grow large and require regular cleanup
  • User education helps maintain optimal storage usage

Compliance and Governance

The enterprise system supports various compliance frameworks:

  • GDPR Compliance - Data retention and secure deletion
  • HIPAA Requirements - Healthcare data storage security
  • SOX Compliance - Financial data storage controls
  • ISO 27001 - Information security storage management

Performance Optimization

Storage performance optimization includes:

  • SSD health monitoring and optimization
  • APFS optimization for modern file systems
  • Cache management for improved performance
  • Defragmentation recommendations when needed

Testing and Validation

Before enterprise deployment:

  1. Test cleanup policies on non-production systems
  2. Verify monitoring thresholds are appropriate for your environment
  3. Confirm alert mechanisms work correctly
  4. Test recovery procedures for critical storage situations
  5. Validate compliance reporting meets organizational requirements

This comprehensive system transforms basic disk usage commands into an enterprise-grade storage management platform with advanced monitoring, automated optimization, and fleet-wide management capabilities.

Configure Stage Manager on macOS Devices

Stage Manager is a powerful window management feature introduced in macOS Ventura that helps users organize and focus on their work by grouping windows and hiding inactive applications. This tutorial shows you how to manage Stage Manager settings across your Mac fleet using shell scripts.

What is Stage Manager?

Stage Manager is a window management system that:

  • Organizes windows into focused groups on the desktop
  • Reduces visual clutter by hiding inactive applications
  • Improves productivity by allowing users to switch between different work contexts
  • Supports external displays with independent Stage Manager controls
  • Integrates with Mission Control for enhanced window management

Prerequisites and Compatibility

System Requirements

  • macOS 13.0 (Ventura) or later - Stage Manager is not available on earlier versions
  • Supported devices: Mac computers with Apple Silicon (M1, M2, M3, M4) or Intel processors
  • Administrative privileges for script execution

Hardware Compatibility

Stage Manager works best on:

  • MacBook Pro and MacBook Air (2018 or later)
  • iMac (2019 or later)
  • Mac Studio (all models)
  • Mac Pro (2019 or later)
  • Mac mini (2018 or later)

Basic Stage Manager Management

Enable Stage Manager

#!/bin/bash

# Script to enable Stage Manager on macOS
CurrentUser=$(ls -l /dev/console | awk '/ / { print $3 }')
CurrentUserUID=$(id -u "$CurrentUser")

echo "MacFleet Stage Manager Enablement"
echo "Current user: $CurrentUser"
echo "Current user UID: $CurrentUserUID"

# Enable Stage Manager globally
launchctl asuser $CurrentUserUID sudo -iu "$CurrentUser" defaults write com.apple.WindowManager GloballyEnabled -bool true

echo "✅ Stage Manager has been enabled for user $CurrentUser"
echo "Changes will take effect after the next login or window manager restart"

Disable Stage Manager

#!/bin/bash

# Script to disable Stage Manager on macOS
CurrentUser=$(ls -l /dev/console | awk '/ / { print $3 }')
CurrentUserUID=$(id -u "$CurrentUser")

echo "MacFleet Stage Manager Disablement"
echo "Current user: $CurrentUser"
echo "Current user UID: $CurrentUserUID"

# Disable Stage Manager globally
launchctl asuser $CurrentUserUID sudo -iu "$CurrentUser" defaults write com.apple.WindowManager GloballyEnabled -bool false

echo "❌ Stage Manager has been disabled for user $CurrentUser"
echo "Changes will take effect after the next login or window manager restart"

Advanced Stage Manager Configuration

Comprehensive Stage Manager Management Script

#!/bin/bash

# Advanced Stage Manager management for Mac fleet
DEVICE_NAME=$(scutil --get ComputerName)
CURRENT_USER=$(ls -l /dev/console | awk '/ / { print $3 }')
CURRENT_USER_UID=$(id -u "$CURRENT_USER")
MACOS_VERSION=$(sw_vers -productVersion)
LOG_FILE="/var/log/macfleet_stage_manager.log"

# Function to log messages
log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}

# Function to check macOS version compatibility
check_compatibility() {
    local major_version=$(echo "$MACOS_VERSION" | cut -d. -f1)
    local minor_version=$(echo "$MACOS_VERSION" | cut -d. -f2)
    
    if [ "$major_version" -ge 13 ]; then
        echo "✅ macOS $MACOS_VERSION is compatible with Stage Manager"
        return 0
    else
        echo "❌ macOS $MACOS_VERSION is not compatible with Stage Manager (requires 13.0+)"
        return 1
    fi
}

# Function to get current Stage Manager status
get_stage_manager_status() {
    local status=$(launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults read com.apple.WindowManager GloballyEnabled 2>/dev/null)
    case "$status" in
        1) echo "enabled" ;;
        0) echo "disabled" ;;
        *) echo "undefined" ;;
    esac
}

# Function to enable Stage Manager
enable_stage_manager() {
    launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults write com.apple.WindowManager GloballyEnabled -bool true
    log_message "Stage Manager enabled on $DEVICE_NAME for user $CURRENT_USER"
}

# Function to disable Stage Manager
disable_stage_manager() {
    launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults write com.apple.WindowManager GloballyEnabled -bool false
    log_message "Stage Manager disabled on $DEVICE_NAME for user $CURRENT_USER"
}

# Function to configure recent apps visibility
configure_recent_apps() {
    local show_recent="$1"
    
    if [ "$show_recent" = "true" ]; then
        launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults write com.apple.WindowManager AutoHide -bool false
        log_message "Recent apps visibility enabled"
        echo "✅ Recent applications will be visible on the left side"
    else
        launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults write com.apple.WindowManager AutoHide -bool true
        log_message "Recent apps visibility disabled"
        echo "❌ Recent applications will be hidden"
    fi
}

# Function to configure window grouping behavior
configure_window_grouping() {
    local grouping_mode="$1"
    
    case "$grouping_mode" in
        "all_at_once")
            launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults write com.apple.WindowManager AppWindowGroupingBehavior -bool false
            log_message "Window grouping set to 'All at Once'"
            echo "✅ Window grouping: All at Once"
            ;;
        "one_at_time")
            launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults write com.apple.WindowManager AppWindowGroupingBehavior -bool true
            log_message "Window grouping set to 'One at a Time'"
            echo "✅ Window grouping: One at a Time"
            ;;
        *)
            echo "❌ Invalid grouping mode. Use 'all_at_once' or 'one_at_time'"
            return 1
            ;;
    esac
}

# Function to restart Window Manager
restart_window_manager() {
    launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" killall WindowManager 2>/dev/null
    sleep 2
    log_message "Window Manager restarted for user $CURRENT_USER"
}

# Function to validate Stage Manager configuration
validate_configuration() {
    local expected_state="$1"
    local current_state=$(get_stage_manager_status)
    
    if [ "$current_state" = "$expected_state" ]; then
        echo "✅ Configuration validation successful: Stage Manager is $expected_state"
        return 0
    else
        echo "❌ Configuration validation failed: Expected $expected_state, got $current_state"
        return 1
    fi
}

# Main execution
echo "MacFleet Stage Manager Configuration"
echo "==================================="
echo "Device: $DEVICE_NAME"
echo "User: $CURRENT_USER"
echo "macOS Version: $MACOS_VERSION"
echo ""

log_message "Starting Stage Manager configuration on $DEVICE_NAME"

# Check compatibility
if ! check_compatibility; then
    log_message "Stage Manager configuration aborted due to compatibility issues"
    exit 1
fi

# Display current status
echo "Current Stage Manager status: $(get_stage_manager_status)"
echo ""

# Configuration options (uncomment as needed)
# enable_stage_manager
# disable_stage_manager
# configure_recent_apps "true"
# configure_window_grouping "all_at_once"
# restart_window_manager

log_message "Stage Manager configuration completed"

Interactive Stage Manager Configuration

#!/bin/bash

# Interactive Stage Manager configuration tool
CURRENT_USER=$(ls -l /dev/console | awk '/ / { print $3 }')
CURRENT_USER_UID=$(id -u "$CURRENT_USER")
MACOS_VERSION=$(sw_vers -productVersion)

# Function to get current Stage Manager status
get_stage_manager_status() {
    local status=$(launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults read com.apple.WindowManager GloballyEnabled 2>/dev/null)
    case "$status" in
        1) echo "enabled" ;;
        0) echo "disabled" ;;
        *) echo "not configured" ;;
    esac
}

# Function to get recent apps setting
get_recent_apps_status() {
    local status=$(launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults read com.apple.WindowManager AutoHide 2>/dev/null)
    case "$status" in
        1) echo "hidden" ;;
        0) echo "visible" ;;
        *) echo "not configured" ;;
    esac
}

# Function to get window grouping setting
get_window_grouping_status() {
    local status=$(launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults read com.apple.WindowManager AppWindowGroupingBehavior 2>/dev/null)
    case "$status" in
        1) echo "one at a time" ;;
        0) echo "all at once" ;;
        *) echo "not configured" ;;
    esac
}

# Function to display current configuration
display_current_config() {
    echo "Current Stage Manager Configuration:"
    echo "==================================="
    echo "Stage Manager: $(get_stage_manager_status)"
    echo "Recent Apps: $(get_recent_apps_status)"
    echo "Window Grouping: $(get_window_grouping_status)"
    echo ""
}

# Main interactive menu
echo "MacFleet Stage Manager Interactive Configuration"
echo "==============================================="
echo "Device: $(scutil --get ComputerName)"
echo "User: $CURRENT_USER"
echo "macOS Version: $MACOS_VERSION"
echo ""

# Check compatibility
major_version=$(echo "$MACOS_VERSION" | cut -d. -f1)
if [ "$major_version" -lt 13 ]; then
    echo "❌ Stage Manager requires macOS 13.0 or later"
    echo "Current version: $MACOS_VERSION"
    exit 1
fi

display_current_config

echo "Configuration Options:"
echo "1. Enable Stage Manager"
echo "2. Disable Stage Manager"
echo "3. Show recent applications"
echo "4. Hide recent applications"
echo "5. Set window grouping to 'All at Once'"
echo "6. Set window grouping to 'One at a Time'"
echo "7. Apply recommended settings"
echo "8. Reset to defaults"
echo "9. Display current configuration"
echo "0. Exit"
echo ""

read -p "Enter your choice (0-9): " choice

case $choice in
    1)
        launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults write com.apple.WindowManager GloballyEnabled -bool true
        echo "✅ Stage Manager enabled"
        ;;
    2)
        launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults write com.apple.WindowManager GloballyEnabled -bool false
        echo "❌ Stage Manager disabled"
        ;;
    3)
        launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults write com.apple.WindowManager AutoHide -bool false
        echo "✅ Recent applications will be visible"
        ;;
    4)
        launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults write com.apple.WindowManager AutoHide -bool true
        echo "❌ Recent applications will be hidden"
        ;;
    5)
        launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults write com.apple.WindowManager AppWindowGroupingBehavior -bool false
        echo "✅ Window grouping set to 'All at Once'"
        ;;
    6)
        launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults write com.apple.WindowManager AppWindowGroupingBehavior -bool true
        echo "✅ Window grouping set to 'One at a Time'"
        ;;
    7)
        # Apply recommended enterprise settings
        launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults write com.apple.WindowManager GloballyEnabled -bool true
        launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults write com.apple.WindowManager AutoHide -bool false
        launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults write com.apple.WindowManager AppWindowGroupingBehavior -bool false
        echo "✅ Applied recommended enterprise settings"
        ;;
    8)
        # Reset to system defaults
        launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults delete com.apple.WindowManager GloballyEnabled 2>/dev/null
        launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults delete com.apple.WindowManager AutoHide 2>/dev/null
        launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults delete com.apple.WindowManager AppWindowGroupingBehavior 2>/dev/null
        echo "✅ Reset to system defaults"
        ;;
    9)
        display_current_config
        ;;
    0)
        echo "Exiting..."
        exit 0
        ;;
    *)
        echo "Invalid choice. Please try again."
        ;;
esac

echo ""
echo "Configuration updated. Changes may require logout/login to take full effect."
echo "You can verify the changes in System Settings > Desktop & Dock > Stage Manager."

Enterprise Deployment Scripts

Bulk Stage Manager Configuration

#!/bin/bash

# Enterprise Stage Manager deployment script
COMPANY_NAME="MacFleet"
DEPLOYMENT_DATE=$(date +"%Y-%m-%d")
LOG_FILE="/var/log/macfleet_stage_manager_deployment.log"
REPORT_FILE="/tmp/stage_manager_deployment_report_$(date +%Y%m%d_%H%M%S).txt"

# Configuration settings
STAGE_MANAGER_ENABLED=true
RECENT_APPS_VISIBLE=true
WINDOW_GROUPING_MODE="all_at_once"  # Options: "all_at_once" or "one_at_time"
RESTART_WINDOW_MANAGER=true

# Function to log messages
log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}

# Function to check macOS compatibility
check_macos_compatibility() {
    local macos_version=$(sw_vers -productVersion)
    local major_version=$(echo "$macos_version" | cut -d. -f1)
    
    if [ "$major_version" -ge 13 ]; then
        log_message "macOS $macos_version is compatible with Stage Manager"
        return 0
    else
        log_message "macOS $macos_version is not compatible with Stage Manager"
        return 1
    fi
}

# Function to get device information
get_device_info() {
    local device_name=$(scutil --get ComputerName)
    local device_serial=$(system_profiler SPHardwareDataType | grep "Serial Number" | awk '{print $4}')
    local macos_version=$(sw_vers -productVersion)
    local current_user=$(ls -l /dev/console | awk '/ / { print $3 }')
    local hardware_model=$(system_profiler SPHardwareDataType | grep "Model Name" | cut -d: -f2 | xargs)
    
    echo "Device: $device_name"
    echo "Serial: $device_serial"
    echo "Hardware: $hardware_model"
    echo "macOS: $macos_version"
    echo "User: $current_user"
}

# Function to deploy Stage Manager configuration
deploy_stage_manager_config() {
    local current_user=$(ls -l /dev/console | awk '/ / { print $3 }')
    local current_user_uid=$(id -u "$current_user")
    
    # Enable/disable Stage Manager
    if [ "$STAGE_MANAGER_ENABLED" = true ]; then
        launchctl asuser $current_user_uid sudo -iu "$current_user" defaults write com.apple.WindowManager GloballyEnabled -bool true
        log_message "Stage Manager enabled for user $current_user"
        echo "✅ Stage Manager enabled"
    else
        launchctl asuser $current_user_uid sudo -iu "$current_user" defaults write com.apple.WindowManager GloballyEnabled -bool false
        log_message "Stage Manager disabled for user $current_user"
        echo "❌ Stage Manager disabled"
    fi
    
    # Configure recent apps visibility
    if [ "$RECENT_APPS_VISIBLE" = true ]; then
        launchctl asuser $current_user_uid sudo -iu "$current_user" defaults write com.apple.WindowManager AutoHide -bool false
        log_message "Recent apps visibility enabled"
        echo "✅ Recent apps will be visible"
    else
        launchctl asuser $current_user_uid sudo -iu "$current_user" defaults write com.apple.WindowManager AutoHide -bool true
        log_message "Recent apps visibility disabled"
        echo "❌ Recent apps will be hidden"
    fi
    
    # Configure window grouping behavior
    case "$WINDOW_GROUPING_MODE" in
        "all_at_once")
            launchctl asuser $current_user_uid sudo -iu "$current_user" defaults write com.apple.WindowManager AppWindowGroupingBehavior -bool false
            log_message "Window grouping set to 'All at Once'"
            echo "✅ Window grouping: All at Once"
            ;;
        "one_at_time")
            launchctl asuser $current_user_uid sudo -iu "$current_user" defaults write com.apple.WindowManager AppWindowGroupingBehavior -bool true
            log_message "Window grouping set to 'One at a Time'"
            echo "✅ Window grouping: One at a Time"
            ;;
    esac
    
    # Restart Window Manager if requested
    if [ "$RESTART_WINDOW_MANAGER" = true ]; then
        launchctl asuser $current_user_uid sudo -iu "$current_user" killall WindowManager 2>/dev/null
        sleep 2
        log_message "Window Manager restarted"
        echo "🔄 Window Manager restarted"
    fi
}

# Function to validate deployment
validate_deployment() {
    local current_user=$(ls -l /dev/console | awk '/ / { print $3 }')
    local current_user_uid=$(id -u "$current_user")
    
    local stage_manager_status=$(launchctl asuser $current_user_uid sudo -iu "$current_user" defaults read com.apple.WindowManager GloballyEnabled 2>/dev/null)
    local recent_apps_status=$(launchctl asuser $current_user_uid sudo -iu "$current_user" defaults read com.apple.WindowManager AutoHide 2>/dev/null)
    local window_grouping_status=$(launchctl asuser $current_user_uid sudo -iu "$current_user" defaults read com.apple.WindowManager AppWindowGroupingBehavior 2>/dev/null)
    
    local validation_success=true
    
    # Validate Stage Manager status
    if [ "$STAGE_MANAGER_ENABLED" = true ] && [ "$stage_manager_status" = "1" ]; then
        echo "✅ Stage Manager validation: PASSED"
    elif [ "$STAGE_MANAGER_ENABLED" = false ] && [ "$stage_manager_status" = "0" ]; then
        echo "✅ Stage Manager validation: PASSED"
    else
        echo "❌ Stage Manager validation: FAILED"
        validation_success=false
    fi
    
    # Validate recent apps setting
    if [ "$RECENT_APPS_VISIBLE" = true ] && [ "$recent_apps_status" = "0" ]; then
        echo "✅ Recent apps validation: PASSED"
    elif [ "$RECENT_APPS_VISIBLE" = false ] && [ "$recent_apps_status" = "1" ]; then
        echo "✅ Recent apps validation: PASSED"
    else
        echo "❌ Recent apps validation: FAILED"
        validation_success=false
    fi
    
    if [ "$validation_success" = true ]; then
        log_message "Deployment validation successful"
        return 0
    else
        log_message "Deployment validation failed"
        return 1
    fi
}

# Main deployment process
echo "$COMPANY_NAME Stage Manager Deployment" > "$REPORT_FILE"
echo "========================================" >> "$REPORT_FILE"
echo "Date: $DEPLOYMENT_DATE" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"

get_device_info >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"

log_message "Starting Stage Manager deployment"
echo "Starting deployment..." >> "$REPORT_FILE"

# Check macOS compatibility
if ! check_macos_compatibility; then
    echo "Status: FAILED - Incompatible macOS version" >> "$REPORT_FILE"
    log_message "Deployment aborted due to macOS compatibility"
    exit 1
fi

# Deploy configuration
deploy_stage_manager_config

# Validate deployment
if validate_deployment; then
    echo "Status: SUCCESS" >> "$REPORT_FILE"
else
    echo "Status: FAILED" >> "$REPORT_FILE"
fi

log_message "Deployment completed"
echo "Deployment completed. Report saved to: $REPORT_FILE"
cat "$REPORT_FILE"

Stage Manager Monitoring and Reporting

#!/bin/bash

# Stage Manager monitoring and reporting script
CENTRAL_SERVER="your-macfleet-server.com"
DEVICE_ID=$(system_profiler SPHardwareDataType | grep "Serial Number" | awk '{print $4}')
REPORT_FILE="/tmp/stage_manager_report_${DEVICE_ID}.json"

# Function to create JSON report
create_json_report() {
    local device_name=$(scutil --get ComputerName)
    local device_user=$(ls -l /dev/console | awk '/ / { print $3 }')
    local device_user_uid=$(id -u "$device_user")
    local os_version=$(sw_vers -productVersion)
    local timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
    local hardware_model=$(system_profiler SPHardwareDataType | grep "Model Name" | cut -d: -f2 | xargs)
    
    # Get Stage Manager settings
    local stage_manager_enabled=$(launchctl asuser $device_user_uid sudo -iu "$device_user" defaults read com.apple.WindowManager GloballyEnabled 2>/dev/null)
    local recent_apps_hidden=$(launchctl asuser $device_user_uid sudo -iu "$device_user" defaults read com.apple.WindowManager AutoHide 2>/dev/null)
    local window_grouping=$(launchctl asuser $device_user_uid sudo -iu "$device_user" defaults read com.apple.WindowManager AppWindowGroupingBehavior 2>/dev/null)
    
    # Check if Stage Manager is supported
    local major_version=$(echo "$os_version" | cut -d. -f1)
    local stage_manager_supported=$([ "$major_version" -ge 13 ] && echo "true" || echo "false")
    
    cat > "$REPORT_FILE" << EOF
{
  "device_info": {
    "device_id": "$DEVICE_ID",
    "device_name": "$device_name",
    "hardware_model": "$hardware_model",
    "user": "$device_user",
    "os_version": "$os_version",
    "timestamp": "$timestamp"
  },
  "stage_manager": {
    "supported": $stage_manager_supported,
    "enabled": $([ "$stage_manager_enabled" = "1" ] && echo "true" || echo "false"),
    "configured": $([ -n "$stage_manager_enabled" ] && echo "true" || echo "false"),
    "recent_apps_hidden": $([ "$recent_apps_hidden" = "1" ] && echo "true" || echo "false"),
    "window_grouping_mode": "$([ "$window_grouping" = "1" ] && echo "one_at_time" || echo "all_at_once")"
  },
  "window_manager": {
    "process_running": $(pgrep -x "WindowManager" > /dev/null && echo "true" || echo "false"),
    "last_restart": "$(ps -p $(pgrep -x "WindowManager") -o lstart= 2>/dev/null | xargs)"
  }
}
EOF
}

# Function to collect usage statistics
collect_usage_stats() {
    local device_user=$(ls -l /dev/console | awk '/ / { print $3 }')
    local device_user_uid=$(id -u "$device_user")
    
    # Check if Stage Manager is currently active
    local stage_manager_active=$(launchctl asuser $device_user_uid sudo -iu "$device_user" defaults read com.apple.WindowManager GloballyEnabled 2>/dev/null)
    
    if [ "$stage_manager_active" = "1" ]; then
        echo "Stage Manager is currently active"
        
        # Get window count (approximation)
        local window_count=$(launchctl asuser $device_user_uid sudo -iu "$device_user" osascript -e 'tell application "System Events" to count windows of every application process' 2>/dev/null)
        echo "Current window count: $window_count"
        
        # Check if external displays are connected
        local display_count=$(system_profiler SPDisplaysDataType | grep -c "Display Type:")
        echo "Connected displays: $display_count"
    else
        echo "Stage Manager is not active"
    fi
}

# Main execution
echo "MacFleet Stage Manager Monitoring"
echo "================================="
echo "Device ID: $DEVICE_ID"

# Create monitoring report
create_json_report

# Collect usage statistics
collect_usage_stats

echo "Report generated: $REPORT_FILE"
echo "Stage Manager monitoring completed"

# Display report summary
echo ""
echo "Report Summary:"
echo "==============="
cat "$REPORT_FILE" | grep -E '"supported|enabled|configured"' | sed 's/[",]//g' | sed 's/^[ ]*//'

# Optional: Send to central server
# curl -X POST -H "Content-Type: application/json" -d @"$REPORT_FILE" "https://$CENTRAL_SERVER/api/stage-manager-reports"

Best Practices for Stage Manager Management

1. User Training and Adoption

  • Provide comprehensive training on Stage Manager features
  • Create user guides and documentation
  • Demonstrate productivity benefits
  • Offer personalized configurations based on user roles

2. Configuration Standards

  • Define organizational standards for Stage Manager settings
  • Create different profiles for different user types
  • Document approved configurations
  • Implement change management processes

3. Performance Considerations

  • Monitor system performance impact
  • Consider hardware capabilities when enabling Stage Manager
  • Test configurations on different device types
  • Provide rollback options

4. Integration with Other Tools

  • Coordinate with existing window management tools
  • Consider impact on screen sharing and remote access
  • Test with business applications
  • Ensure compatibility with accessibility features

Troubleshooting Common Issues

Issue: Stage Manager Not Available

# Check macOS version
macos_version=$(sw_vers -productVersion)
echo "macOS version: $macos_version"

# Check if running on compatible hardware
hardware_model=$(system_profiler SPHardwareDataType | grep "Model Name" | cut -d: -f2 | xargs)
echo "Hardware model: $hardware_model"

# Verify system requirements
if [[ "$macos_version" < "13.0" ]]; then
    echo "❌ Stage Manager requires macOS 13.0 or later"
fi

Issue: Changes Not Taking Effect

# Restart Window Manager
current_user=$(ls -l /dev/console | awk '/ / { print $3 }')
current_user_uid=$(id -u "$current_user")

launchctl asuser $current_user_uid sudo -iu "$current_user" killall WindowManager
sleep 3

# Verify process restart
if pgrep -x "WindowManager" > /dev/null; then
    echo "✅ Window Manager restarted successfully"
else
    echo "❌ Window Manager failed to restart"
fi

Issue: Permission Denied

# Check user permissions
current_user=$(ls -l /dev/console | awk '/ / { print $3 }')
echo "Current user: $current_user"

# Verify user context
id "$current_user"

# Check if user has necessary permissions
if groups "$current_user" | grep -q "admin"; then
    echo "✅ User has admin privileges"
else
    echo "❌ User does not have admin privileges"
fi

Issue: Settings Not Persisting

# Check preferences file
current_user=$(ls -l /dev/console | awk '/ / { print $3 }')
plist_file="/Users/$current_user/Library/Preferences/com.apple.WindowManager.plist"

if [ -f "$plist_file" ]; then
    echo "✅ Preferences file exists"
    ls -la "$plist_file"
else
    echo "❌ Preferences file not found"
fi

# Force preferences sync
defaults synchronize

Stage Manager Feature Deep Dive

Understanding Stage Manager Components

Stage Manager consists of several key components:

  1. Window Groups: Collections of related windows that appear together
  2. Stage: The main working area where active window groups are displayed
  3. Recent Applications: Sidebar showing recently used applications
  4. External Display Support: Independent Stage Manager operation on external displays

Advanced Configuration Options

#!/bin/bash

# Advanced Stage Manager configuration options
CURRENT_USER=$(ls -l /dev/console | awk '/ / { print $3 }')
CURRENT_USER_UID=$(id -u "$CURRENT_USER")

# Configure Stage Manager for external displays
configure_external_display_stage_manager() {
    local enable_external="$1"
    
    if [ "$enable_external" = "true" ]; then
        launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults write com.apple.WindowManager StandardStageStripShowsFullDesktop -bool true
        echo "✅ External display Stage Manager enabled"
    else
        launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults write com.apple.WindowManager StandardStageStripShowsFullDesktop -bool false
        echo "❌ External display Stage Manager disabled"
    fi
}

# Configure Stage Manager animation speed
configure_animation_speed() {
    local speed="$1"  # Values: 0.1 to 1.0
    
    if [[ "$speed" =~ ^[0-9]+\.?[0-9]*$ ]] && (( $(echo "$speed >= 0.1" | bc -l) )) && (( $(echo "$speed <= 1.0" | bc -l) )); then
        launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults write com.apple.WindowManager StageManagerAnimationSpeed -float "$speed"
        echo "✅ Animation speed set to $speed"
    else
        echo "❌ Invalid animation speed. Use values between 0.1 and 1.0"
    fi
}

# Configure Stage Manager hotkeys
configure_hotkeys() {
    local enable_hotkeys="$1"
    
    if [ "$enable_hotkeys" = "true" ]; then
        launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults write com.apple.WindowManager EnableHotKeys -bool true
        echo "✅ Stage Manager hotkeys enabled"
    else
        launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults write com.apple.WindowManager EnableHotKeys -bool false
        echo "❌ Stage Manager hotkeys disabled"
    fi
}

# Example usage
# configure_external_display_stage_manager "true"
# configure_animation_speed "0.5"
# configure_hotkeys "true"

Conclusion

Stage Manager is a powerful productivity feature that can significantly improve window management workflows when properly configured. This comprehensive guide provides:

  • Basic enable/disable functionality for quick deployment
  • Advanced configuration options for customized user experiences
  • Enterprise deployment scripts for large-scale management
  • Monitoring and reporting tools for ongoing management
  • Troubleshooting guides for common issues

Regular implementation of Stage Manager management practices will help ensure your Mac fleet provides an optimal user experience while maintaining organizational standards and productivity goals.

For maximum effectiveness, consider integrating Stage Manager configuration with your existing Mac fleet management tools and user training programs.

Managing Spotlight Indexing on macOS Devices

Spotlight is macOS's powerful system-wide search feature that helps users quickly locate files, documents, applications, emails, and more across their system. While Spotlight provides excellent search capabilities, its continuous background indexing can sometimes impact system performance, particularly on older hardware or resource-constrained environments. This comprehensive guide provides methods to manage Spotlight indexing effectively.

Understanding Spotlight and Its Impact

Spotlight uses a sophisticated indexing system that continuously scans and catalogs content on your Mac to provide instant search results. This indexing process involves:

  • File content analysis: Reading and indexing text within documents
  • Metadata extraction: Cataloging file properties, creation dates, and tags
  • Application indexing: Tracking installed applications and their data
  • Email and message indexing: Indexing Mail, Messages, and other communication apps
  • Real-time updates: Monitoring file system changes to keep the index current

Why Manage Spotlight Indexing?

There are several scenarios where managing Spotlight indexing becomes necessary:

  • Performance optimization: Reducing CPU and disk usage on resource-limited systems
  • Privacy concerns: Preventing indexing of sensitive files and directories
  • Storage management: Saving disk space used by index files
  • Troubleshooting: Resolving search issues or corrupted indexes
  • Enterprise deployment: Standardizing search behavior across managed devices
  • Development environments: Preventing indexing of build directories and temporary files

Prerequisites

Before managing Spotlight indexing, ensure you have:

  • Administrative privileges on the Mac
  • Terminal or SSH access
  • Understanding of the impact on search functionality
  • Backup of important data (recommended)

Basic Spotlight Management Commands

Understanding mdutil

The mdutil command is the primary tool for managing Spotlight indexing:

# Check indexing status
mdutil -s /

# Enable indexing for a volume
mdutil -i on /

# Disable indexing for a volume
mdutil -i off /

# Erase and rebuild index
mdutil -E /

# Get help
mdutil -h

Checking Current Indexing Status

Before making changes, check the current indexing status:

#!/bin/bash

# Check Spotlight indexing status for all volumes
echo "Spotlight Indexing Status Report"
echo "==============================="
echo "Date: $(date)"
echo ""

# Get all mounted volumes
volumes=$(df -h | grep "^/dev" | awk '{print $9}')

echo "Volume Indexing Status:"
echo "----------------------"

for volume in $volumes; do
    if [ -d "$volume" ]; then
        status=$(mdutil -s "$volume" 2>/dev/null | grep "Indexing enabled")
        echo "$volume: $status"
    fi
done

echo ""
echo "Active indexing processes:"
ps aux | grep -i mds | grep -v grep

Disabling Spotlight Indexing

Basic Disable Script

Simple script to disable Spotlight indexing on the main volume:

#!/bin/bash

# Disable Spotlight indexing on the root volume
echo "Disabling Spotlight indexing..."

if sudo mdutil -i off /; then
    echo "✓ Spotlight indexing disabled successfully"
    
    # Verify the change
    status=$(mdutil -s / | grep "Indexing enabled")
    echo "Current status: $status"
else
    echo "✗ Failed to disable Spotlight indexing"
    exit 1
fi

echo "Note: Search functionality will be limited until indexing is re-enabled"

Advanced Disable Script with Logging

More comprehensive script with logging and verification:

#!/bin/bash

# Advanced Spotlight disable script with logging
LOG_FILE="/var/log/spotlight_management.log"
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')

# Function to log messages
log_message() {
    echo "[$TIMESTAMP] $1" | tee -a "$LOG_FILE"
}

# Function to disable indexing for a volume
disable_indexing() {
    local volume=$1
    
    log_message "Attempting to disable indexing for volume: $volume"
    
    # Check if volume exists
    if [ ! -d "$volume" ]; then
        log_message "ERROR: Volume $volume does not exist"
        return 1
    fi
    
    # Check current status
    current_status=$(mdutil -s "$volume" 2>/dev/null)
    log_message "Current status for $volume: $current_status"
    
    # Disable indexing
    if sudo mdutil -i off "$volume"; then
        log_message "SUCCESS: Indexing disabled for $volume"
        
        # Verify the change
        new_status=$(mdutil -s "$volume" 2>/dev/null)
        log_message "New status for $volume: $new_status"
        
        return 0
    else
        log_message "ERROR: Failed to disable indexing for $volume"
        return 1
    fi
}

# Main execution
log_message "Starting Spotlight indexing disable process"

# Disable for root volume
if disable_indexing "/"; then
    log_message "Root volume indexing disabled successfully"
else
    log_message "Failed to disable root volume indexing"
    exit 1
fi

# Optional: Disable for other volumes
# Uncomment the following lines to disable for additional volumes
# disable_indexing "/Volumes/ExternalDrive"
# disable_indexing "/Users"

log_message "Spotlight indexing disable process completed"
echo "Process completed. Check log at: $LOG_FILE"

Batch Disable for Multiple Volumes

Script to disable indexing on multiple volumes:

#!/bin/bash

# Batch disable Spotlight indexing for multiple volumes
VOLUMES=(
    "/"
    "/Users"
    "/Applications"
    # Add more volumes as needed
)

echo "Batch Spotlight Indexing Disable"
echo "================================"
echo "Date: $(date)"
echo ""

successful=0
failed=0

for volume in "${VOLUMES[@]}"; do
    echo "Processing volume: $volume"
    
    if [ -d "$volume" ]; then
        if sudo mdutil -i off "$volume" 2>/dev/null; then
            echo "  ✓ Successfully disabled indexing for $volume"
            ((successful++))
        else
            echo "  ✗ Failed to disable indexing for $volume"
            ((failed++))
        fi
    else
        echo "  ⚠ Volume $volume does not exist, skipping"
    fi
done

echo ""
echo "Summary:"
echo "--------"
echo "Successfully disabled: $successful volumes"
echo "Failed: $failed volumes"

if [ $failed -gt 0 ]; then
    echo "Some operations failed. Check individual volume status manually."
    exit 1
fi

Removing Spotlight Index Files

Basic Cleanup Script

After disabling indexing, remove existing index files to free up space:

#!/bin/bash

# Remove Spotlight index files
echo "Removing Spotlight index files..."

# Remove .Spotlight-V100 directories (modern macOS)
if sudo rm -rf /.Spotlight-V100; then
    echo "✓ Removed .Spotlight-V100 directory"
else
    echo "⚠ No .Spotlight-V100 directory found or removal failed"
fi

# Remove legacy .Spotlight directories
if sudo rm -rf /.Spotlight*; then
    echo "✓ Removed legacy Spotlight directories"
else
    echo "⚠ No legacy Spotlight directories found"
fi

# Calculate space freed
echo "Spotlight index cleanup completed"

Advanced Cleanup with Size Calculation

More detailed cleanup script that shows space savings:

#!/bin/bash

# Advanced Spotlight index cleanup with size reporting
echo "Spotlight Index Cleanup Utility"
echo "==============================="
echo "Date: $(date)"
echo ""

# Function to get directory size
get_size() {
    local dir=$1
    if [ -d "$dir" ]; then
        du -sh "$dir" 2>/dev/null | cut -f1
    else
        echo "0B"
    fi
}

# Function to remove spotlight directories
cleanup_spotlight_dirs() {
    local base_path=$1
    local total_size=0
    
    echo "Cleaning up Spotlight directories in: $base_path"
    
    # Find all Spotlight directories
    spotlight_dirs=$(find "$base_path" -name ".Spotlight*" -type d 2>/dev/null)
    
    if [ -z "$spotlight_dirs" ]; then
        echo "  No Spotlight directories found"
        return 0
    fi
    
    for dir in $spotlight_dirs; do
        size=$(get_size "$dir")
        echo "  Found: $dir ($size)"
        
        if sudo rm -rf "$dir"; then
            echo "    ✓ Removed successfully"
        else
            echo "    ✗ Failed to remove"
        fi
    done
}

# Clean up common locations
cleanup_spotlight_dirs "/"
cleanup_spotlight_dirs "/Users"

# Clean up on external volumes if any
for volume in /Volumes/*; do
    if [ -d "$volume" ]; then
        echo ""
        cleanup_spotlight_dirs "$volume"
    fi
done

echo ""
echo "Spotlight index cleanup completed"
echo "Run 'df -h' to see updated disk usage"

Enabling Spotlight Indexing

Basic Enable Script

Simple script to re-enable Spotlight indexing:

#!/bin/bash

# Enable Spotlight indexing on the root volume
echo "Enabling Spotlight indexing..."

if sudo mdutil -i on /; then
    echo "✓ Spotlight indexing enabled successfully"
    
    # Verify the change
    status=$(mdutil -s / | grep "Indexing enabled")
    echo "Current status: $status"
    
    echo ""
    echo "Note: Indexing will begin automatically and may take some time to complete"
    echo "You can monitor progress using Spotlight search"
else
    echo "✗ Failed to enable Spotlight indexing"
    exit 1
fi

Advanced Enable with Progress Monitoring

Script that enables indexing and provides progress monitoring:

#!/bin/bash

# Advanced Spotlight enable script with progress monitoring
LOG_FILE="/var/log/spotlight_management.log"
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')

# Function to log messages
log_message() {
    echo "[$TIMESTAMP] $1" | tee -a "$LOG_FILE"
}

# Function to monitor indexing progress
monitor_indexing() {
    local volume=$1
    local timeout=60  # Monitor for 60 seconds
    local elapsed=0
    
    echo "Monitoring indexing progress for $volume..."
    
    while [ $elapsed -lt $timeout ]; do
        # Check if indexing is in progress
        if ps aux | grep -v grep | grep -q "mds_stores\|mdworker"; then
            echo "  Indexing in progress... (${elapsed}s elapsed)"
        else
            echo "  Indexing may have completed or paused"
            break
        fi
        
        sleep 5
        elapsed=$((elapsed + 5))
    done
    
    if [ $elapsed -ge $timeout ]; then
        echo "  Monitoring timeout reached. Indexing may still be in progress."
    fi
}

# Function to enable indexing for a volume
enable_indexing() {
    local volume=$1
    
    log_message "Attempting to enable indexing for volume: $volume"
    
    # Check if volume exists
    if [ ! -d "$volume" ]; then
        log_message "ERROR: Volume $volume does not exist"
        return 1
    fi
    
    # Check current status
    current_status=$(mdutil -s "$volume" 2>/dev/null)
    log_message "Current status for $volume: $current_status"
    
    # Enable indexing
    if sudo mdutil -i on "$volume"; then
        log_message "SUCCESS: Indexing enabled for $volume"
        
        # Verify the change
        new_status=$(mdutil -s "$volume" 2>/dev/null)
        log_message "New status for $volume: $new_status"
        
        # Monitor initial progress
        monitor_indexing "$volume"
        
        return 0
    else
        log_message "ERROR: Failed to enable indexing for $volume"
        return 1
    fi
}

# Main execution
log_message "Starting Spotlight indexing enable process"

# Enable for root volume
if enable_indexing "/"; then
    log_message "Root volume indexing enabled successfully"
else
    log_message "Failed to enable root volume indexing"
    exit 1
fi

log_message "Spotlight indexing enable process completed"
echo "Process completed. Check log at: $LOG_FILE"

Rebuilding Spotlight Index

Basic Rebuild Script

Script to completely rebuild the Spotlight index:

#!/bin/bash

# Rebuild Spotlight index
echo "Rebuilding Spotlight index..."
echo "Warning: This will erase the current index and rebuild from scratch"
echo ""

read -p "Continue? (y/N): " confirm
if [[ ! $confirm =~ ^[Yy]$ ]]; then
    echo "Operation cancelled"
    exit 0
fi

echo "Starting index rebuild..."

if sudo mdutil -E /; then
    echo "✓ Index rebuild initiated successfully"
    
    # Show status
    status=$(mdutil -s /)
    echo "Current status: $status"
    
    echo ""
    echo "The index rebuild process has started and will continue in the background"
    echo "This may take several hours depending on the amount of data"
    echo "You can monitor progress using Activity Monitor (look for mds_stores and mdworker processes)"
else
    echo "✗ Failed to initiate index rebuild"
    exit 1
fi

Advanced Rebuild with Selective Volumes

Script to rebuild indexes for specific volumes:

#!/bin/bash

# Advanced Spotlight index rebuild script
VOLUMES=(
    "/"
    "/Users"
    # Add specific volumes or use discovery
)

AUTO_DISCOVER=${1:-false}

echo "Spotlight Index Rebuild Utility"
echo "==============================="
echo "Date: $(date)"
echo ""

# Function to discover mounted volumes
discover_volumes() {
    echo "Discovering mounted volumes..."
    
    # Get all mounted HFS+/APFS volumes
    local discovered_volumes=()
    while IFS= read -r line; do
        volume=$(echo "$line" | awk '{print $9}')
        if [ -d "$volume" ] && [ "$volume" != "/dev" ]; then
            discovered_volumes+=("$volume")
        fi
    done < <(df -h | grep "^/dev")
    
    echo "Discovered volumes:"
    for vol in "${discovered_volumes[@]}"; do
        echo "  - $vol"
    done
    
    VOLUMES=("${discovered_volumes[@]}")
}

# Function to rebuild index for a volume
rebuild_index() {
    local volume=$1
    
    echo "Rebuilding index for: $volume"
    
    # Check if volume exists and is mounted
    if [ ! -d "$volume" ]; then
        echo "  ✗ Volume $volume does not exist or is not mounted"
        return 1
    fi
    
    # Show current status
    current_status=$(mdutil -s "$volume" 2>/dev/null)
    echo "  Current status: $current_status"
    
    # Rebuild index
    if sudo mdutil -E "$volume"; then
        echo "  ✓ Index rebuild initiated for $volume"
        
        # Show new status
        new_status=$(mdutil -s "$volume" 2>/dev/null)
        echo "  New status: $new_status"
        
        return 0
    else
        echo "  ✗ Failed to rebuild index for $volume"
        return 1
    fi
}

# Auto-discover volumes if requested
if [ "$AUTO_DISCOVER" = "true" ]; then
    discover_volumes
fi

echo "Volumes to rebuild:"
for volume in "${VOLUMES[@]}"; do
    echo "  - $volume"
done

echo ""
read -p "Proceed with rebuilding indexes? (y/N): " confirm
if [[ ! $confirm =~ ^[Yy]$ ]]; then
    echo "Operation cancelled"
    exit 0
fi

echo ""
echo "Starting index rebuild process..."
echo ""

successful=0
failed=0

for volume in "${VOLUMES[@]}"; do
    if rebuild_index "$volume"; then
        ((successful++))
    else
        ((failed++))
    fi
    echo ""
done

echo "Rebuild Summary:"
echo "---------------"
echo "Successfully initiated: $successful volumes"
echo "Failed: $failed volumes"
echo ""
echo "Note: Index rebuilding will continue in the background"
echo "Monitor progress with: ps aux | grep mds"

Advanced Spotlight Management

Selective Directory Exclusion

Script to exclude specific directories from indexing:

#!/bin/bash

# Exclude specific directories from Spotlight indexing
EXCLUDE_DIRS=(
    "/tmp"
    "/var/tmp"
    "/private/tmp"
    "/Users/Shared/Build"
    # Add more directories as needed
)

echo "Spotlight Directory Exclusion Manager"
echo "===================================="
echo ""

# Function to add directory to exclusion list
exclude_directory() {
    local dir_path=$1
    
    echo "Excluding directory: $dir_path"
    
    # Check if directory exists
    if [ ! -d "$dir_path" ]; then
        echo "  ⚠ Directory does not exist: $dir_path"
        return 1
    fi
    
    # Add to Spotlight privacy list using defaults
    if sudo defaults write /System/Library/CoreServices/Search.bundle/Contents/Resources/SpotlightExclusions.plist Exclusions -array-add "$dir_path"; then
        echo "  ✓ Added to exclusion list"
        return 0
    else
        echo "  ✗ Failed to add to exclusion list"
        return 1
    fi
}

# Function to show current exclusions
show_exclusions() {
    echo "Current Spotlight exclusions:"
    echo "----------------------------"
    
    # Read from system preferences
    if defaults read /System/Library/CoreServices/Search.bundle/Contents/Resources/SpotlightExclusions.plist Exclusions 2>/dev/null; then
        echo ""
    else
        echo "No exclusions found or unable to read exclusions list"
    fi
}

# Show current exclusions
show_exclusions

echo ""
echo "Adding new exclusions..."

for dir in "${EXCLUDE_DIRS[@]}"; do
    exclude_directory "$dir"
done

echo ""
echo "Exclusion process completed"
echo "Restart Spotlight for changes to take effect:"
echo "sudo killall mds && sudo mdutil -E /"

Performance Monitoring Script

Script to monitor Spotlight's impact on system performance:

#!/bin/bash

# Spotlight Performance Monitor
DURATION=${1:-60}  # Monitor for 60 seconds by default
INTERVAL=5

echo "Spotlight Performance Monitor"
echo "============================"
echo "Monitoring duration: ${DURATION} seconds"
echo "Sample interval: ${INTERVAL} seconds"
echo ""

# Function to get Spotlight process stats
get_spotlight_stats() {
    local timestamp=$(date '+%H:%M:%S')
    
    # Get mds processes
    mds_stats=$(ps aux | grep -E "mds|mdworker" | grep -v grep | awk '{
        cpu += $3; 
        mem += $4; 
        count++
    } END {
        printf "Processes: %d, CPU: %.1f%%, Memory: %.1f%%", count, cpu, mem
    }')
    
    # Get disk activity (if available)
    disk_activity=$(iostat -c 1 2>/dev/null | tail -1 | awk '{print "Disk: " $4 "% utilization"}' || echo "Disk: N/A")
    
    echo "[$timestamp] $mds_stats, $disk_activity"
}

# Header
echo "Time     | Spotlight Stats"
echo "---------|------------------------------------------------"

# Monitor loop
elapsed=0
while [ $elapsed -lt $DURATION ]; do
    get_spotlight_stats
    sleep $INTERVAL
    elapsed=$((elapsed + INTERVAL))
done

echo ""
echo "Monitoring completed"

# Show summary
echo ""
echo "Final Process Summary:"
echo "---------------------"
ps aux | grep -E "mds|mdworker" | grep -v grep | head -10

Automation and Scheduling

Automated Maintenance Script

Script for scheduled Spotlight maintenance:

#!/bin/bash

# Automated Spotlight maintenance script
# Can be run via cron or launchd

CONFIG_FILE="/etc/spotlight_maintenance.conf"
LOG_FILE="/var/log/spotlight_maintenance.log"

# Default configuration
REBUILD_INTERVAL=30  # days
CLEANUP_TEMP=true
MONITOR_PERFORMANCE=true

# Function to log with timestamp
log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}

# Load configuration if exists
if [ -f "$CONFIG_FILE" ]; then
    source "$CONFIG_FILE"
    log_message "Configuration loaded from $CONFIG_FILE"
fi

# Function to check if rebuild is needed
needs_rebuild() {
    local index_age_file="/var/db/.spotlight_last_rebuild"
    
    if [ ! -f "$index_age_file" ]; then
        return 0  # No record, assume rebuild needed
    fi
    
    local last_rebuild=$(cat "$index_age_file")
    local current_time=$(date +%s)
    local age_days=$(( (current_time - last_rebuild) / 86400 ))
    
    if [ $age_days -gt $REBUILD_INTERVAL ]; then
        log_message "Index age: $age_days days, rebuild needed"
        return 0
    else
        log_message "Index age: $age_days days, rebuild not needed"
        return 1
    fi
}

# Function to perform rebuild
perform_rebuild() {
    log_message "Starting scheduled index rebuild"
    
    if sudo mdutil -E /; then
        log_message "Index rebuild initiated successfully"
        echo "$(date +%s)" | sudo tee /var/db/.spotlight_last_rebuild > /dev/null
        return 0
    else
        log_message "Index rebuild failed"
        return 1
    fi
}

# Function to cleanup temporary files
cleanup_temp_files() {
    if [ "$CLEANUP_TEMP" = true ]; then
        log_message "Cleaning up temporary Spotlight files"
        
        # Remove temporary index files
        sudo find /tmp -name ".Spotlight*" -exec rm -rf {} \; 2>/dev/null
        sudo find /var/tmp -name ".Spotlight*" -exec rm -rf {} \; 2>/dev/null
        
        log_message "Temporary file cleanup completed"
    fi
}

# Function to check performance
check_performance() {
    if [ "$MONITOR_PERFORMANCE" = true ]; then
        local mds_cpu=$(ps aux | grep mds | grep -v grep | awk '{sum += $3} END {print sum}')
        
        if [ -n "$mds_cpu" ] && [ "$mds_cpu" -gt 50 ]; then
            log_message "WARNING: High Spotlight CPU usage detected: ${mds_cpu}%"
        else
            log_message "Spotlight performance normal: ${mds_cpu:-0}% CPU"
        fi
    fi
}

# Main maintenance routine
log_message "Starting automated Spotlight maintenance"

check_performance
cleanup_temp_files

if needs_rebuild; then
    perform_rebuild
fi

log_message "Automated Spotlight maintenance completed"

Best Practices and Recommendations

1. Performance Considerations

  • Monitor system resources before disabling indexing
  • Consider partial exclusions instead of complete disable
  • Schedule maintenance during off-hours
  • Test changes on non-production systems first

2. Security and Privacy

  • Exclude sensitive directories from indexing
  • Regularly review and update exclusion lists
  • Consider the security implications of search functionality
  • Document all changes for compliance purposes

3. Enterprise Management

  • Standardize Spotlight policies across devices
  • Use configuration management tools for deployment
  • Implement monitoring and alerting for index issues
  • Maintain documentation of all customizations

4. Troubleshooting Guidelines

  • Always check system logs when issues occur
  • Test individual commands before running complex scripts
  • Keep backups of important data before major changes
  • Document the steps taken for future reference

Troubleshooting Common Issues

Index Corruption

#!/bin/bash

# Fix corrupted Spotlight index
echo "Fixing corrupted Spotlight index..."

# Stop indexing
sudo mdutil -i off /

# Remove corrupted index
sudo rm -rf /.Spotlight-V100

# Re-enable and rebuild
sudo mdutil -i on /
sudo mdutil -E /

echo "Index repair initiated"

High CPU Usage

#!/bin/bash

# Address high Spotlight CPU usage
echo "Addressing high Spotlight CPU usage..."

# Check current processes
echo "Current Spotlight processes:"
ps aux | grep -E "mds|mdworker" | grep -v grep

# Temporarily throttle indexing
sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.metadata.mds.plist
sleep 5
sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.metadata.mds.plist

echo "Spotlight services restarted"

Conclusion

Effective Spotlight management is crucial for maintaining optimal macOS performance while preserving search functionality where needed. The scripts and techniques provided in this guide offer comprehensive solutions for various Spotlight management scenarios.

Key takeaways:

  • Understand the impact of indexing on system performance
  • Use appropriate scripts for your specific use case
  • Implement proper monitoring and maintenance procedures
  • Always test changes in a controlled environment
  • Document all modifications for future reference

Remember that disabling Spotlight indexing will significantly impact search functionality, so carefully consider the trade-offs before implementing these changes across your Mac fleet.