Tutorial

New updates and improvements to Macfleet.

Empty Trash on macOS

Learn how to remotely empty trash folders on Mac devices using scripts. This helps free up disk space and manage storage efficiently across your Mac fleet.

Empty Trash for Specific User

Remove all items from a specific user's trash:

#!/bin/bash

# Specify the username
USERNAME="john"

# Empty trash for specific user
sudo rm -rf /Users/"${USERNAME}"/.Trash/*

echo "Trash emptied for user: ${USERNAME}"

Empty Trash for Current User

Automatically detect and empty trash for the currently logged-in user:

#!/bin/bash

# Get current user
CURRENT_USER=$(stat -f "%Su" /dev/console)

# Empty trash for current user
su "$CURRENT_USER" -c "rm -rf ~/.Trash/*"

echo "Trash emptied for current user: ${CURRENT_USER}"

Enhanced Script with Validation

Script with error handling and logging:

#!/bin/bash

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

# Get current user
CURRENT_USER=$(stat -f "%Su" /dev/console)

if [[ -z "$CURRENT_USER" ]]; then
    log_message "Error: Could not determine current user"
    exit 1
fi

log_message "Emptying trash for user: ${CURRENT_USER}"

# Check if trash directory exists
TRASH_DIR="/Users/${CURRENT_USER}/.Trash"
if [[ ! -d "$TRASH_DIR" ]]; then
    log_message "Trash directory not found: ${TRASH_DIR}"
    exit 1
fi

# Count items before deletion
ITEM_COUNT=$(find "$TRASH_DIR" -mindepth 1 -maxdepth 1 | wc -l)
log_message "Found ${ITEM_COUNT} items in trash"

if [[ $ITEM_COUNT -eq 0 ]]; then
    log_message "Trash is already empty"
    exit 0
fi

# Empty trash
if su "$CURRENT_USER" -c "rm -rf ~/.Trash/*"; then
    log_message "Successfully emptied trash for ${CURRENT_USER}"
else
    log_message "Failed to empty trash"
    exit 1
fi

Multi-User Trash Management

Empty trash for all users on the system:

#!/bin/bash

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

log_message "Starting multi-user trash cleanup"

# Find all user directories
for USER_DIR in /Users/*; do
    if [[ -d "$USER_DIR" && ! "$USER_DIR" =~ /Users/(Shared|Guest) ]]; then
        USERNAME=$(basename "$USER_DIR")
        TRASH_DIR="$USER_DIR/.Trash"
        
        if [[ -d "$TRASH_DIR" ]]; then
            ITEM_COUNT=$(find "$TRASH_DIR" -mindepth 1 -maxdepth 1 2>/dev/null | wc -l)
            
            if [[ $ITEM_COUNT -gt 0 ]]; then
                log_message "Emptying trash for user: ${USERNAME} (${ITEM_COUNT} items)"
                sudo rm -rf "$TRASH_DIR"/*
                log_message "Completed trash cleanup for: ${USERNAME}"
            else
                log_message "Trash already empty for user: ${USERNAME}"
            fi
        fi
    fi
done

log_message "Multi-user trash cleanup completed"

Usage with MacFleet

  1. Choose the appropriate script based on your needs
  2. For specific users, modify the USERNAME variable
  3. Deploy through MacFleet's remote script execution
  4. Monitor results in the action history

Prerequisites

  • Full Disk Access: Grant full disk access to MacFleet agent in System Settings > Privacy & Security > Full Disk Access
  • Administrative privileges: Scripts require sudo access for system-wide operations

Security Considerations

  • Verify user permissions before running scripts
  • Consider backing up important files before mass trash deletion
  • Test on limited devices before fleet-wide deployment

Troubleshooting

Permission denied: Ensure MacFleet agent has Full Disk Access User not found: Verify username exists on the target device Script fails: Check if user is currently logged in for user-specific operations


Note: Deleted items cannot be recovered after running these scripts. Always validate on test systems first.

Dock Management and Interface Customization on macOS

Optimize user productivity and maintain consistent interface standards across your MacFleet devices with comprehensive dock management and interface customization. This tutorial covers enterprise dock configuration, fleet-wide deployment, user experience optimization, and automated interface management for enhanced organizational productivity.

Understanding macOS Dock Management

The macOS Dock serves as the primary application launcher and workspace organizer:

  • Application Launcher - Quick access to frequently used applications
  • Active App Indicator - Visual representation of running applications
  • File & Folder Access - Direct access to documents and directories
  • Trash Management - File deletion and recovery interface
  • Productivity Hub - Centralized workspace navigation

Basic Dock Configuration

Set Custom Application Arrangement

#!/bin/bash

# Configure custom dock applications
configure_basic_dock() {
    echo "=== Basic Dock Configuration ==="
    
    local logged_user=$(stat -f%Su /dev/console)
    
    if [[ -z "$logged_user" || "$logged_user" == "root" ]]; then
        echo "❌ No user logged in or invalid user"
        return 1
    fi
    
    echo "Configuring dock for user: $logged_user"
    
    # Define standard application set
    local standard_apps=(
        "/Applications/Safari.app"
        "/Applications/Mail.app"
        "/System/Applications/Messages.app"
        "/Applications/Calendar.app"
        "/Applications/Notes.app"
        "/System/Applications/System Preferences.app"
        "/Applications/Google Chrome.app"
        "/Applications/Microsoft Outlook.app"
        "/Applications/Slack.app"
        "/Applications/Zoom.app"
    )
    
    # Build dock configuration
    local dock_config="<dict><key>tile-data</key><dict><key>file-data</key><dict><key>_CFURLString</key><string>PLACEHOLDER</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>"
    local dock_array=""
    
    for app in "${standard_apps[@]}"; do
        if [[ -d "$app" ]]; then
            local app_entry="${dock_config/PLACEHOLDER/$app}"
            if [[ -n "$dock_array" ]]; then
                dock_array="$dock_array "
            fi
            dock_array="$dock_array'$app_entry'"
            echo "✅ Added to dock: $(basename "$app" .app)"
        else
            echo "⚠️  Application not found: $app"
        fi
    done
    
    # Apply dock configuration
    if [[ -n "$dock_array" ]]; then
        sudo su "$logged_user" -c "defaults write com.apple.dock persistent-apps -array $dock_array"
        sudo su "$logged_user" -c "killall Dock"
        echo "✅ Basic dock configuration applied"
    else
        echo "❌ No applications found to configure"
        return 1
    fi
    
    return 0
}

# Execute function
configure_basic_dock

Reset Dock to Default State

#!/bin/bash

# Reset dock to macOS default configuration
reset_dock_default() {
    echo "=== Resetting Dock to Default State ==="
    
    local logged_user=$(stat -f%Su /dev/console)
    
    if [[ -z "$logged_user" || "$logged_user" == "root" ]]; then
        echo "❌ No user logged in or invalid user"
        return 1
    fi
    
    echo "Resetting dock for user: $logged_user"
    
    # Create backup of current dock configuration
    local backup_file="/tmp/dock_backup_$(date '+%Y%m%d_%H%M%S').plist"
    sudo su "$logged_user" -c "defaults export com.apple.dock '$backup_file'"
    
    if [[ -f "$backup_file" ]]; then
        echo "✅ Dock configuration backed up to: $backup_file"
    fi
    
    # Reset dock preferences
    sudo su "$logged_user" -c "defaults delete com.apple.dock"
    
    # Restart dock
    killall Dock
    
    echo "✅ Dock reset to default state"
    return 0
}

# Execute function
reset_dock_default

Configure Visual Appearance

#!/bin/bash

# Configure dock visual appearance and behavior
configure_dock_appearance() {
    local logged_user=$(stat -f%Su /dev/console)
    local dock_size="${1:-48}"
    local magnification="${2:-true}"
    local autohide="${3:-false}"
    local position="${4:-bottom}"
    
    echo "=== Configuring Dock Appearance ==="
    echo "User: $logged_user"
    echo "Size: $dock_size"
    echo "Magnification: $magnification"
    echo "Auto-hide: $autohide"
    echo "Position: $position"
    
    if [[ -z "$logged_user" || "$logged_user" == "root" ]]; then
        echo "❌ No user logged in"
        return 1
    fi
    
    # Configure dock size
    sudo su "$logged_user" -c "defaults write com.apple.dock tilesize -int $dock_size"
    
    # Configure magnification
    if [[ "$magnification" == "true" ]]; then
        sudo su "$logged_user" -c "defaults write com.apple.dock magnification -bool true"
        sudo su "$logged_user" -c "defaults write com.apple.dock largesize -int 128"
    else
        sudo su "$logged_user" -c "defaults write com.apple.dock magnification -bool false"
    fi
    
    # Configure auto-hide
    sudo su "$logged_user" -c "defaults write com.apple.dock autohide -bool $autohide"
    
    # Configure dock position
    sudo su "$logged_user" -c "defaults write com.apple.dock orientation -string $position"
    
    # Configure minimize effect
    sudo su "$logged_user" -c "defaults write com.apple.dock mineffect -string genie"
    
    # Show hidden app indicators
    sudo su "$logged_user" -c "defaults write com.apple.dock showhidden -bool true"
    
    # Restart dock to apply changes
    killall Dock
    
    echo "✅ Dock appearance configured successfully"
    return 0
}

# Usage example
# configure_dock_appearance 64 true false bottom

Enterprise Dock Management System

#!/bin/bash

# MacFleet Enterprise Dock Management System
# Comprehensive interface customization, productivity optimization, and fleet-wide deployment

# Configuration
LOG_FILE="/var/log/macfleet_dock_management.log"
CONFIG_DIR="/etc/macfleet/dock_management"
POLICIES_DIR="$CONFIG_DIR/policies"
TEMPLATES_DIR="$CONFIG_DIR/templates"
PROFILES_DIR="$CONFIG_DIR/profiles"
REPORTS_DIR="$CONFIG_DIR/reports"
BACKUP_DIR="$CONFIG_DIR/backups"
COMPLIANCE_DIR="$CONFIG_DIR/compliance"
DEPLOYMENT_DIR="$CONFIG_DIR/deployment"

# Dock configuration templates
declare -A DOCK_TEMPLATES=(
    ["developer"]="Xcode,Terminal,Visual Studio Code,GitHub Desktop,Docker,Postman,Simulator,Activity Monitor"
    ["designer"]="Adobe Creative Suite,Figma,Sketch,Affinity Designer,ColorSync Utility,Digital Color Meter,Preview"
    ["business"]="Microsoft Office Suite,Slack,Zoom,Teams,Outlook,OneNote,Salesforce,Tableau"
    ["executive"]="Mail,Calendar,Contacts,Safari,Numbers,Keynote,Pages,Messages,FaceTime"
    ["support"]="Remote Desktop,TeamViewer,Console,Activity Monitor,Network Utility,Disk Utility,Terminal"
    ["education"]="Safari,Mail,Classroom,Pages,Numbers,Keynote,GarageBand,iMovie,Books"
    ["finance"]="Excel,QuickBooks,Sage,TaxAct,Calculator,Numbers,Banking Apps,PDF Expert"
    ["healthcare"]="Epic,Cerner,MEDITECH,DICOM Viewer,Medical Calculator,Secure Messaging,Telemedicine Apps"
)

# User role configurations
declare -A USER_ROLES=(
    ["admin"]="developer,support"
    ["power_user"]="business,developer"
    ["standard_user"]="business"
    ["guest"]="executive"
    ["kiosk"]="education"
)

# Dock size presets
declare -A DOCK_SIZES=(
    ["small"]="32"
    ["medium"]="48"
    ["large"]="64"
    ["extra_large"]="80"
    ["jumbo"]="128"
)

# Enterprise policies
declare -A ENTERPRISE_POLICIES=(
    ["corporate_standard"]="consistent_layout,security_apps,productivity_focused,compliance_enabled"
    ["byod_friendly"]="user_customizable,personal_apps_allowed,flexible_layout"
    ["kiosk_mode"]="locked_layout,essential_apps_only,no_customization"
    ["developer_optimized"]="development_tools,large_dock,custom_shortcuts"
    ["executive_minimal"]="essential_apps,clean_interface,quick_access"
)

# Productivity optimizations
declare -A PRODUCTIVITY_FEATURES=(
    ["hot_corners"]="mission_control,desktop,dashboard,screen_saver"
    ["gestures"]="swipe_navigation,expose,spaces"
    ["shortcuts"]="application_switching,dock_navigation,quick_launch"
    ["organization"]="folder_stacks,recent_items,favorites"
)

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

# Setup directories
setup_directories() {
    for dir in "$CONFIG_DIR" "$POLICIES_DIR" "$TEMPLATES_DIR" "$PROFILES_DIR" "$REPORTS_DIR" "$BACKUP_DIR" "$COMPLIANCE_DIR" "$DEPLOYMENT_DIR"; do
        if [[ ! -d "$dir" ]]; then
            mkdir -p "$dir"
            log_action "Created directory: $dir"
        fi
    done
}

# Install dock management dependencies
install_dock_dependencies() {
    echo "🔧 Installing Dock Management Dependencies"
    
    local dockutil_version="3.0.2"
    local dockutil_pkg="/tmp/dockutil-${dockutil_version}.pkg"
    
    # Check if dockutil is already installed
    if command -v dockutil &>/dev/null; then
        echo "✅ dockutil already installed"
        return 0
    fi
    
    # Download and install dockutil
    echo "📥 Downloading dockutil ${dockutil_version}..."
    if curl -sL "https://github.com/kcrawford/dockutil/releases/download/${dockutil_version}/dockutil-${dockutil_version}.pkg" -o "$dockutil_pkg"; then
        echo "📦 Installing dockutil..."
        if sudo installer -pkg "$dockutil_pkg" -target /; then
            echo "✅ dockutil installed successfully"
            rm -f "$dockutil_pkg"
        else
            echo "❌ Failed to install dockutil"
            return 1
        fi
    else
        echo "❌ Failed to download dockutil"
        return 1
    fi
    
    # Install additional productivity tools
    install_productivity_tools
    
    return 0
}

# Install productivity enhancement tools
install_productivity_tools() {
    echo "🚀 Installing Productivity Enhancement Tools"
    
    # Check for Homebrew
    if ! command -v brew &>/dev/null; then
        echo "📥 Installing Homebrew..."
        /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    fi
    
    # Install additional tools for dock management
    local tools=("jq" "plist" "defaults")
    
    for tool in "${tools[@]}"; do
        if ! command -v "$tool" &>/dev/null; then
            echo "📦 Installing $tool..."
            brew install "$tool" 2>/dev/null || echo "⚠️  Could not install $tool via Homebrew"
        fi
    done
    
    echo "✅ Productivity tools installation completed"
}

# Create dock configuration from template
create_dock_from_template() {
    local template_name="$1"
    local username="$2"
    local customize_options="$3"
    
    log_action "Creating dock configuration from template: $template_name for user: $username"
    
    local template_apps="${DOCK_TEMPLATES[$template_name]}"
    if [[ -z "$template_apps" ]]; then
        log_action "❌ Unknown dock template: $template_name"
        return 1
    fi
    
    local logged_user=$(stat -f%Su /dev/console)
    local target_user="${username:-$logged_user}"
    
    if [[ -z "$target_user" || "$target_user" == "root" ]]; then
        log_action "❌ Invalid target user: $target_user"
        return 1
    fi
    
    echo "🎨 Creating dock configuration from template: $template_name"
    echo "Target user: $target_user"
    
    # Backup current dock configuration
    backup_dock_configuration "$target_user"
    
    # Parse template applications
    IFS=',' read -ra TEMPLATE_APPS <<< "$template_apps"
    
    # Clear current dock
    sudo su "$target_user" -c "defaults write com.apple.dock persistent-apps -array"
    
    # Add applications from template
    for app_name in "${TEMPLATE_APPS[@]}"; do
        add_application_to_dock "$app_name" "$target_user"
    done
    
    # Apply customization options
    if [[ -n "$customize_options" ]]; then
        apply_dock_customizations "$customize_options" "$target_user"
    fi
    
    # Save template configuration
    save_dock_template_config "$template_name" "$target_user"
    
    # Restart dock
    killall Dock
    
    log_action "✅ Dock configuration created from template: $template_name"
    return 0
}

# Add application to dock intelligently
add_application_to_dock() {
    local app_name="$1"
    local username="$2"
    
    # Application path mapping
    local app_paths=(
        "/Applications/${app_name}.app"
        "/System/Applications/${app_name}.app"
        "/Applications/Utilities/${app_name}.app"
        "/Applications/Microsoft Office 2011/${app_name}.app"
        "/Applications/Adobe Creative Suite/${app_name}.app"
        "/Applications/Google Chrome.app"
        "/Applications/Microsoft Outlook.app"
        "/Applications/Microsoft Word.app"
        "/Applications/Microsoft Excel.app"
        "/Applications/Microsoft PowerPoint.app"
        "/Applications/Slack.app"
        "/Applications/Zoom.app"
        "/Applications/Figma.app"
        "/Applications/Visual Studio Code.app"
        "/Applications/Xcode.app"
    )
    
    # Find application path
    local app_path=""
    for path in "${app_paths[@]}"; do
        if [[ -d "$path" ]]; then
            app_path="$path"
            break
        fi
    done
    
    # Handle special application names
    case "$app_name" in
        "Microsoft Office Suite")
            add_application_to_dock "Microsoft Word" "$username"
            add_application_to_dock "Microsoft Excel" "$username"
            add_application_to_dock "Microsoft PowerPoint" "$username"
            add_application_to_dock "Microsoft Outlook" "$username"
            return 0
            ;;
        "Adobe Creative Suite")
            add_application_to_dock "Adobe Photoshop" "$username"
            add_application_to_dock "Adobe Illustrator" "$username"
            add_application_to_dock "Adobe InDesign" "$username"
            return 0
            ;;
        "Terminal")
            app_path="/System/Applications/Utilities/Terminal.app"
            ;;
        "Activity Monitor")
            app_path="/System/Applications/Utilities/Activity Monitor.app"
            ;;
        "System Preferences")
            app_path="/System/Applications/System Preferences.app"
            ;;
    esac
    
    if [[ -n "$app_path" && -d "$app_path" ]]; then
        # Use dockutil if available
        if command -v dockutil &>/dev/null; then
            dockutil --add "$app_path" --allhomes 2>/dev/null
            echo "✅ Added to dock: $app_name"
        else
            # Fallback to defaults command
            local dock_entry="<dict><key>tile-data</key><dict><key>file-data</key><dict><key>_CFURLString</key><string>$app_path</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>"
            sudo su "$username" -c "defaults write com.apple.dock persistent-apps -array-add '$dock_entry'"
            echo "✅ Added to dock: $app_name"
        fi
    else
        echo "⚠️  Application not found: $app_name"
    fi
}

# Apply dock customizations
apply_dock_customizations() {
    local customizations="$1"
    local username="$2"
    
    echo "🎛️  Applying dock customizations: $customizations"
    
    IFS=',' read -ra CUSTOM_OPTIONS <<< "$customizations"
    
    for option in "${CUSTOM_OPTIONS[@]}"; do
        case "$option" in
            "large_size")
                sudo su "$username" -c "defaults write com.apple.dock tilesize -int 64"
                ;;
            "magnification")
                sudo su "$username" -c "defaults write com.apple.dock magnification -bool true"
                sudo su "$username" -c "defaults write com.apple.dock largesize -int 128"
                ;;
            "autohide")
                sudo su "$username" -c "defaults write com.apple.dock autohide -bool true"
                sudo su "$username" -c "defaults write com.apple.dock autohide-time-modifier -float 0.5"
                ;;
            "left_position")
                sudo su "$username" -c "defaults write com.apple.dock orientation -string left"
                ;;
            "right_position")
                sudo su "$username" -c "defaults write com.apple.dock orientation -string right"
                ;;
            "minimize_to_app")
                sudo su "$username" -c "defaults write com.apple.dock minimize-to-application -bool true"
                ;;
            "spring_loading")
                sudo su "$username" -c "defaults write com.apple.dock enable-spring-load-actions-on-all-items -bool true"
                ;;
            "recent_apps")
                sudo su "$username" -c "defaults write com.apple.dock show-recents -bool true"
                ;;
            "no_recent_apps")
                sudo su "$username" -c "defaults write com.apple.dock show-recents -bool false"
                ;;
            *)
                echo "⚠️  Unknown customization option: $option"
                ;;
        esac
    done
    
    echo "✅ Dock customizations applied"
}

# Configure enterprise dock policies
configure_enterprise_dock_policies() {
    local policy_name="$1"
    local deployment_scope="$2"
    local user_groups="$3"
    
    log_action "Configuring enterprise dock policies: $policy_name"
    
    local policy_settings="${ENTERPRISE_POLICIES[$policy_name]}"
    if [[ -z "$policy_settings" ]]; then
        log_action "❌ Unknown enterprise policy: $policy_name"
        return 1
    fi
    
    echo "🏢 Configuring Enterprise Dock Policy: $policy_name"
    echo "Deployment scope: $deployment_scope"
    echo "User groups: $user_groups"
    
    # Create policy configuration
    local policy_config="$POLICIES_DIR/enterprise_policy_${policy_name}.json"
    
    cat > "$policy_config" << EOF
{
    "policy_metadata": {
        "name": "$policy_name",
        "created": "$(date -Iseconds)",
        "deployment_scope": "$deployment_scope",
        "target_groups": "$user_groups",
        "settings": "$policy_settings"
    },
    "dock_configuration": {
        "layout_enforcement": $(get_layout_enforcement "$policy_name"),
        "application_restrictions": $(get_app_restrictions "$policy_name"),
        "customization_permissions": $(get_customization_permissions "$policy_name"),
        "security_requirements": $(get_security_requirements "$policy_name")
    },
    "deployment_rules": {
        "auto_apply": $(get_auto_apply_setting "$policy_name"),
        "user_override": $(get_user_override_setting "$policy_name"),
        "monitoring_level": $(get_monitoring_level "$policy_name"),
        "compliance_checking": $(get_compliance_checking "$policy_name")
    }
}
EOF

    # Apply policy based on deployment scope
    case "$deployment_scope" in
        "fleet_wide")
            apply_fleet_wide_policy "$policy_name" "$policy_config"
            ;;
        "group_based")
            apply_group_based_policy "$policy_name" "$user_groups" "$policy_config"
            ;;
        "individual")
            apply_individual_policy "$policy_name" "$user_groups" "$policy_config"
            ;;
        *)
            log_action "⚠️  Unknown deployment scope: $deployment_scope"
            return 1
            ;;
    esac
    
    log_action "✅ Enterprise dock policy configured: $policy_name"
    return 0
}

# Monitor dock compliance
monitor_dock_compliance() {
    log_action "Starting dock compliance monitoring"
    
    local compliance_report="$COMPLIANCE_DIR/dock_compliance_$(date '+%Y%m%d_%H%M%S').json"
    local logged_user=$(stat -f%Su /dev/console)
    
    cat > "$compliance_report" << EOF
{
    "compliance_metadata": {
        "timestamp": "$(date -Iseconds)",
        "hostname": "$(hostname)",
        "logged_user": "$logged_user",
        "monitor_type": "dock_compliance"
    },
    "dock_assessment": {
        "current_configuration": $(get_current_dock_config "$logged_user"),
        "policy_compliance": $(assess_policy_compliance "$logged_user"),
        "security_compliance": $(assess_dock_security "$logged_user"),
        "productivity_metrics": $(calculate_productivity_metrics "$logged_user")
    },
    "compliance_status": {
        "overall_score": $(calculate_compliance_score),
        "violations": $(detect_policy_violations "$logged_user"),
        "recommendations": $(generate_compliance_recommendations),
        "remediation_actions": $(generate_remediation_actions)
    }
}
EOF

    log_action "✅ Dock compliance monitoring completed: $compliance_report"
    echo "$compliance_report"
}

# Get current dock configuration
get_current_dock_config() {
    local username="$1"
    
    if [[ -z "$username" ]]; then
        echo '{"error": "No username provided"}'
        return 1
    fi
    
    # Extract dock configuration
    local dock_apps
    dock_apps=$(sudo su "$username" -c "defaults read com.apple.dock persistent-apps" 2>/dev/null | grep "file-label" | sed 's/.*= "\(.*\)";/\1/' | tr '\n' ',' | sed 's/,$//')
    
    local dock_size
    dock_size=$(sudo su "$username" -c "defaults read com.apple.dock tilesize" 2>/dev/null || echo "48")
    
    local dock_position
    dock_position=$(sudo su "$username" -c "defaults read com.apple.dock orientation" 2>/dev/null || echo "bottom")
    
    local autohide
    autohide=$(sudo su "$username" -c "defaults read com.apple.dock autohide" 2>/dev/null || echo "false")
    
    local magnification
    magnification=$(sudo su "$username" -c "defaults read com.apple.dock magnification" 2>/dev/null || echo "false")
    
    cat << EOF
{
    "applications": "$dock_apps",
    "size": $dock_size,
    "position": "$dock_position",
    "autohide": $autohide,
    "magnification": $magnification,
    "app_count": $(echo "$dock_apps" | tr ',' '\n' | grep -v '^$' | wc -l)
}
EOF
}

# Optimize dock for productivity
optimize_dock_productivity() {
    local optimization_level="$1"
    local username="$2"
    local role="$3"
    
    log_action "Optimizing dock for productivity: level=$optimization_level, user=$username, role=$role"
    
    local logged_user=$(stat -f%Su /dev/console)
    local target_user="${username:-$logged_user}"
    
    echo "🚀 Optimizing Dock for Productivity"
    echo "Optimization level: $optimization_level"
    echo "Target user: $target_user"
    echo "User role: $role"
    
    case "$optimization_level" in
        "basic")
            apply_basic_productivity_optimizations "$target_user" "$role"
            ;;
        "advanced")
            apply_advanced_productivity_optimizations "$target_user" "$role"
            ;;
        "expert")
            apply_expert_productivity_optimizations "$target_user" "$role"
            ;;
        *)
            log_action "⚠️  Unknown optimization level: $optimization_level"
            return 1
            ;;
    esac
    
    # Configure hot corners for productivity
    configure_hot_corners "$target_user"
    
    # Set up dock shortcuts
    configure_dock_shortcuts "$target_user"
    
    # Apply role-specific optimizations
    apply_role_specific_optimizations "$role" "$target_user"
    
    # Restart dock
    killall Dock
    
    log_action "✅ Dock productivity optimization completed"
    return 0
}

# Apply basic productivity optimizations
apply_basic_productivity_optimizations() {
    local username="$1"
    local role="$2"
    
    echo "📋 Applying basic productivity optimizations"
    
    # Optimize dock size for efficiency
    sudo su "$username" -c "defaults write com.apple.dock tilesize -int 48"
    
    # Enable magnification for better visibility
    sudo su "$username" -c "defaults write com.apple.dock magnification -bool true"
    sudo su "$username" -c "defaults write com.apple.dock largesize -int 64"
    
    # Speed up dock animations
    sudo su "$username" -c "defaults write com.apple.dock autohide-time-modifier -float 0.25"
    sudo su "$username" -c "defaults write com.apple.dock autohide-delay -float 0"
    
    # Show hidden apps
    sudo su "$username" -c "defaults write com.apple.dock showhidden -bool true"
    
    # Minimize windows to app icon
    sudo su "$username" -c "defaults write com.apple.dock minimize-to-application -bool true"
    
    # Disable recent apps in dock (for cleaner interface)
    sudo su "$username" -c "defaults write com.apple.dock show-recents -bool false"
    
    echo "✅ Basic productivity optimizations applied"
}

# Generate productivity metrics
generate_productivity_metrics() {
    local username="$1"
    
    local metrics_report="$REPORTS_DIR/productivity_metrics_${username}_$(date '+%Y%m%d_%H%M%S').json"
    
    cat > "$metrics_report" << EOF
{
    "productivity_metrics": {
        "user": "$username",
        "timestamp": "$(date -Iseconds)",
        "dock_efficiency": $(calculate_dock_efficiency "$username"),
        "application_access_score": $(calculate_app_access_score "$username"),
        "workspace_organization": $(assess_workspace_organization "$username"),
        "productivity_features": $(assess_productivity_features "$username")
    },
    "recommendations": {
        "layout_improvements": $(suggest_layout_improvements "$username"),
        "application_recommendations": $(suggest_app_recommendations "$username"),
        "workflow_optimizations": $(suggest_workflow_optimizations "$username")
    }
}
EOF

    echo "$metrics_report"
}

# Backup dock configuration
backup_dock_configuration() {
    local username="$1"
    local backup_name="${2:-auto_backup}"
    
    local backup_file="$BACKUP_DIR/dock_backup_${username}_${backup_name}_$(date '+%Y%m%d_%H%M%S').plist"
    
    if sudo su "$username" -c "defaults export com.apple.dock '$backup_file'"; then
        log_action "✅ Dock configuration backed up: $backup_file"
        echo "$backup_file"
    else
        log_action "❌ Failed to backup dock configuration for user: $username"
        return 1
    fi
}

# Restore dock configuration
restore_dock_configuration() {
    local username="$1"
    local backup_file="$2"
    
    if [[ ! -f "$backup_file" ]]; then
        log_action "❌ Backup file not found: $backup_file"
        return 1
    fi
    
    log_action "Restoring dock configuration from: $backup_file"
    
    if sudo su "$username" -c "defaults import com.apple.dock '$backup_file'"; then
        killall Dock
        log_action "✅ Dock configuration restored successfully"
        return 0
    else
        log_action "❌ Failed to restore dock configuration"
        return 1
    fi
}

# Main execution function
main() {
    local action="${1:-status}"
    local parameter="$2"
    local additional_param="$3"
    local extra_param="$4"
    
    log_action "=== MacFleet Dock Management Started ==="
    log_action "Action: $action"
    log_action "Parameter: ${parameter:-N/A}"
    
    setup_directories
    
    case "$action" in
        "install")
            install_dock_dependencies
            ;;
        "template")
            if [[ -z "$parameter" ]]; then
                echo "Available dock templates:"
                for template in "${!DOCK_TEMPLATES[@]}"; do
                    echo "  - $template: ${DOCK_TEMPLATES[$template]}"
                done
                echo ""
                echo "Usage: $0 template <template_name> [username] [customizations]"
                exit 1
            fi
            create_dock_from_template "$parameter" "$additional_param" "$extra_param"
            ;;
        "policy")
            if [[ -z "$parameter" || -z "$additional_param" ]]; then
                echo "Available enterprise policies:"
                for policy in "${!ENTERPRISE_POLICIES[@]}"; do
                    echo "  - $policy: ${ENTERPRISE_POLICIES[$policy]}"
                done
                echo ""
                echo "Usage: $0 policy <policy_name> <deployment_scope> [user_groups]"
                echo "Deployment scopes: fleet_wide, group_based, individual"
                exit 1
            fi
            configure_enterprise_dock_policies "$parameter" "$additional_param" "$extra_param"
            ;;
        "optimize")
            if [[ -z "$parameter" ]]; then
                echo "Optimization levels: basic, advanced, expert"
                echo "User roles: ${!USER_ROLES[*]}"
                echo ""
                echo "Usage: $0 optimize <level> [username] [role]"
                exit 1
            fi
            optimize_dock_productivity "$parameter" "$additional_param" "$extra_param"
            ;;
        "monitor")
            monitor_dock_compliance
            ;;
        "backup")
            if [[ -z "$parameter" ]]; then
                parameter=$(stat -f%Su /dev/console)
            fi
            backup_dock_configuration "$parameter" "$additional_param"
            ;;
        "restore")
            if [[ -z "$parameter" || -z "$additional_param" ]]; then
                echo "Usage: $0 restore <username> <backup_file>"
                exit 1
            fi
            restore_dock_configuration "$parameter" "$additional_param"
            ;;
        "reset")
            reset_dock_default
            ;;
        "appearance")
            if [[ -z "$parameter" ]]; then
                echo "Available dock sizes: ${!DOCK_SIZES[*]}"
                echo ""
                echo "Usage: $0 appearance <size> [magnification] [autohide] [position]"
                echo "Example: $0 appearance medium true false bottom"
                exit 1
            fi
            local size="${DOCK_SIZES[$parameter]:-$parameter}"
            configure_dock_appearance "$size" "$additional_param" "$extra_param" "${5:-bottom}"
            ;;
        "metrics")
            if [[ -z "$parameter" ]]; then
                parameter=$(stat -f%Su /dev/console)
            fi
            generate_productivity_metrics "$parameter"
            ;;
        *)
            echo "Usage: $0 {install|template|policy|optimize|monitor|backup|restore|reset|appearance|metrics}"
            echo "  install     - Install dock management dependencies"
            echo "  template    - Apply dock configuration from template"
            echo "  policy      - Configure enterprise dock policies"
            echo "  optimize    - Optimize dock for productivity"
            echo "  monitor     - Monitor dock compliance"
            echo "  backup      - Backup dock configuration"
            echo "  restore     - Restore dock configuration"
            echo "  reset       - Reset dock to default state"
            echo "  appearance  - Configure dock visual appearance"
            echo "  metrics     - Generate productivity metrics"
            exit 1
            ;;
    esac
    
    log_action "=== Dock management operation completed ==="
}

# Execute main function
main "$@"

Advanced Dock Management Features

Smart Application Organization

#!/bin/bash

# Intelligent application organization based on usage patterns
smart_dock_organization() {
    local username="$1"
    local analysis_period="${2:-30}"  # days
    
    echo "🧠 Smart Dock Organization"
    echo "Analyzing usage patterns for $analysis_period days"
    
    local usage_data="$REPORTS_DIR/app_usage_${username}.json"
    
    # Analyze application usage
    cat > "$usage_data" << EOF
{
    "analysis_period": $analysis_period,
    "usage_patterns": $(analyze_app_usage "$username" "$analysis_period"),
    "frequency_ranking": $(rank_apps_by_frequency "$username"),
    "time_based_usage": $(analyze_time_based_usage "$username"),
    "productivity_score": $(calculate_app_productivity_score "$username")
}
EOF

    # Reorganize dock based on usage patterns
    reorganize_dock_by_usage "$username" "$usage_data"
    
    echo "✅ Smart dock organization completed"
}

# Dynamic dock adaptation
dynamic_dock_adaptation() {
    echo "🔄 Dynamic Dock Adaptation"
    
    local adaptation_script="$DEPLOYMENT_DIR/dynamic_adaptation.sh"
    
    cat > "$adaptation_script" << 'EOF'
#!/bin/bash

# Dynamic dock adaptation based on context

while true; do
    CURRENT_HOUR=$(date +%H)
    CURRENT_USER=$(stat -f%Su /dev/console)
    
    # Adapt dock based on time of day
    if [[ $CURRENT_HOUR -ge 9 && $CURRENT_HOUR -le 17 ]]; then
        # Business hours - productivity focus
        apply_business_hours_dock "$CURRENT_USER"
    elif [[ $CURRENT_HOUR -ge 18 && $CURRENT_HOUR -le 22 ]]; then
        # Evening - creative/personal work
        apply_evening_dock "$CURRENT_USER"
    else
        # Off-hours - minimal dock
        apply_minimal_dock "$CURRENT_USER"
    fi
    
    # Check every 30 minutes
    sleep 1800
done
EOF

    chmod +x "$adaptation_script"
    echo "🤖 Dynamic adaptation script created"
}

Productivity Analytics Dashboard

#!/bin/bash

# Generate comprehensive productivity analytics
generate_dock_analytics_dashboard() {
    local time_period="$1"
    local user_scope="$2"
    
    echo "📊 Generating Dock Analytics Dashboard"
    
    local dashboard_report="$REPORTS_DIR/dock_analytics_dashboard_$(date '+%Y%m%d_%H%M%S').html"
    
    cat > "$dashboard_report" << EOF
<!DOCTYPE html>
<html>
<head>
    <title>MacFleet Dock Analytics Dashboard</title>
    <style>
        body { font-family: -apple-system, BlinkMacSystemFont, sans-serif; margin: 20px; }
        .metric-card { border: 1px solid #ddd; border-radius: 8px; padding: 20px; margin: 10px 0; }
        .metric-value { font-size: 2em; font-weight: bold; color: #007AFF; }
        .chart-container { width: 100%; height: 300px; background: #f5f5f5; border-radius: 4px; }
    </style>
</head>
<body>
    <h1>🖥️ MacFleet Dock Analytics Dashboard</h1>
    <div class="metric-card">
        <h3>Overall Productivity Score</h3>
        <div class="metric-value">$(calculate_overall_productivity_score)</div>
    </div>
    <div class="metric-card">
        <h3>Application Usage Efficiency</h3>
        <div class="metric-value">$(calculate_app_usage_efficiency)%</div>
    </div>
    <div class="metric-card">
        <h3>Dock Configuration Compliance</h3>
        <div class="metric-value">$(calculate_dock_compliance)%</div>
    </div>
    <div class="metric-card">
        <h3>User Satisfaction Index</h3>
        <div class="metric-value">$(calculate_user_satisfaction_index)</div>
    </div>
</body>
</html>
EOF

    echo "📈 Analytics dashboard generated: $dashboard_report"
    open "$dashboard_report" 2>/dev/null || echo "Dashboard saved to: $dashboard_report"
}

Enterprise Integration Features

🔗 System Integration

  • Active Directory integration with user role mapping
  • LDAP authentication for dock policy assignment
  • Configuration management integration (Puppet, Ansible, Chef)
  • Mobile device management (MDM) policy synchronization

📱 Fleet Management

  • Centralized deployment across thousands of devices
  • Policy inheritance with organizational unit mapping
  • Bulk configuration updates with rollback capabilities
  • Health monitoring with automated compliance checking

🎯 User Experience Optimization

  • Context-aware adaptation based on time, location, role
  • Machine learning insights for personalized recommendations
  • Productivity analytics with actionable insights
  • A/B testing for dock configuration effectiveness

🛡️ Security and Compliance

  • Policy enforcement with tamper protection
  • Security application integration in dock configurations
  • Compliance reporting for regulatory requirements
  • Audit trails for all dock modifications

Important Notes

  • User permissions required for dock modifications across enterprise
  • Application licensing considerations for enterprise dock templates
  • Performance impact minimal with optimized deployment strategies
  • Backup strategies essential before major dock reconfigurations
  • User training important for productivity optimization adoption
  • Regular monitoring needed to maintain dock compliance and effectiveness

Configuring DNS Settings for Wi-Fi on Mac

The Domain Name System (DNS) is the backbone of the internet, converting human-readable domain names into IP addresses that enable seamless communication between devices. Proper DNS configuration can significantly impact your internet experience, affecting speed, security, and privacy. This comprehensive guide provides methods to configure DNS settings for Wi-Fi on macOS devices.

Understanding DNS and Its Importance

DNS servers act as translators between domain names (like google.com) and IP addresses (like 142.250.80.14). When you type a web address, your device queries a DNS server to find the corresponding IP address, then connects to that server.

Why Change DNS Settings?

There are several compelling reasons to modify your DNS configuration:

  • Improved Performance: Faster DNS servers can reduce website loading times
  • Enhanced Security: DNS filtering can block malicious websites and phishing attempts
  • Privacy Protection: Some DNS providers don't log your browsing activities
  • Content Access: Bypass geographical restrictions and censorship
  • Parental Controls: Filter inappropriate content for family networks
  • Ad Blocking: Some DNS services block advertisements at the DNS level

Popular DNS Providers

Before configuring DNS settings, consider these popular DNS providers:

Google Public DNS

  • Primary: 8.8.8.8
  • Secondary: 8.8.4.4
  • Features: Fast, reliable, minimal logging

Cloudflare DNS

  • Primary: 1.1.1.1
  • Secondary: 1.0.0.1
  • Features: Privacy-focused, very fast, security features

OpenDNS

  • Primary: 208.67.222.222
  • Secondary: 208.67.220.220
  • Features: Content filtering, malware protection

Quad9

  • Primary: 9.9.9.9
  • Secondary: 149.112.112.112
  • Features: Security-focused, blocks malicious domains

Prerequisites

Before configuring DNS settings, ensure you have:

  • Administrative privileges on the Mac
  • Terminal access or System Preferences access
  • Knowledge of your current network configuration
  • Backup of current DNS settings (optional but recommended)

Method 1: Using Shell Scripts

Basic DNS Configuration Script

This script configures DNS server settings for Wi-Fi on macOS:

#!/bin/bash

# Configure DNS servers for Wi-Fi
sudo networksetup -setdnsservers "Wi-Fi" 8.8.8.8 8.8.4.4

# Verify the configuration
output=$(networksetup -getdnsservers "Wi-Fi")
echo "Current DNS Servers: $output"

# Flush DNS cache
sudo dscacheutil -flushcache
echo "DNS cache flushed"

Advanced DNS Configuration Script

A more comprehensive script with multiple DNS options:

#!/bin/bash

# Advanced DNS configuration script for macOS Wi-Fi
# Usage: ./dns_config.sh [provider]
# Providers: google, cloudflare, opendns, quad9, reset

PROVIDER=${1:-google}
INTERFACE="Wi-Fi"

# Function to set DNS servers
set_dns_servers() {
    local primary=$1
    local secondary=$2
    local provider_name=$3
    
    echo "Setting DNS servers to $provider_name..."
    sudo networksetup -setdnsservers "$INTERFACE" "$primary" "$secondary"
    
    # Verify configuration
    current_dns=$(networksetup -getdnsservers "$INTERFACE")
    echo "Current DNS servers: $current_dns"
    
    # Flush DNS cache
    sudo dscacheutil -flushcache
    echo "DNS cache flushed"
    
    # Test DNS resolution
    echo "Testing DNS resolution..."
    nslookup google.com "$primary" | head -5
}

# Function to reset to automatic DNS
reset_dns() {
    echo "Resetting DNS to automatic (DHCP)..."
    sudo networksetup -setdnsservers "$INTERFACE" "Empty"
    current_dns=$(networksetup -getdnsservers "$INTERFACE")
    echo "Current DNS servers: $current_dns"
}

# Main configuration logic
case $PROVIDER in
    google)
        set_dns_servers "8.8.8.8" "8.8.4.4" "Google Public DNS"
        ;;
    cloudflare)
        set_dns_servers "1.1.1.1" "1.0.0.1" "Cloudflare DNS"
        ;;
    opendns)
        set_dns_servers "208.67.222.222" "208.67.220.220" "OpenDNS"
        ;;
    quad9)
        set_dns_servers "9.9.9.9" "149.112.112.112" "Quad9"
        ;;
    reset)
        reset_dns
        ;;
    *)
        echo "Usage: $0 [google|cloudflare|opendns|quad9|reset]"
        echo "Default: google"
        exit 1
        ;;
esac

echo "DNS configuration complete!"

Batch DNS Configuration for Multiple Macs

For managing DNS settings across multiple Mac devices:

#!/bin/bash

# Batch DNS configuration for multiple Macs
HOSTS=(
    "mac1.local"
    "mac2.local"
    "mac3.local"
)

DNS_PRIMARY="1.1.1.1"
DNS_SECONDARY="1.0.0.1"
INTERFACE="Wi-Fi"

echo "Configuring DNS on multiple Macs..."
echo "Primary DNS: $DNS_PRIMARY"
echo "Secondary DNS: $DNS_SECONDARY"
echo ""

for host in "${HOSTS[@]}"; do
    echo "Configuring $host..."
    
    if ping -c 1 -W 1000 "$host" >/dev/null 2>&1; then
        # Create script to run on remote host
        remote_script="sudo networksetup -setdnsservers '$INTERFACE' '$DNS_PRIMARY' '$DNS_SECONDARY' && sudo dscacheutil -flushcache"
        
        if ssh -o ConnectTimeout=5 -o BatchMode=yes "$host" "$remote_script" 2>/dev/null; then
            echo "  ✓ $host - DNS configured successfully"
        else
            echo "  ✗ $host - Failed to configure DNS"
        fi
    else
        echo "  ✗ $host - Host unreachable"
    fi
done

echo ""
echo "Batch DNS configuration complete!"

Method 2: Manual Configuration via System Preferences

Step-by-Step GUI Configuration

  1. Open System Preferences

    • Click the Apple menu > System Preferences
    • Or use Spotlight: Press Cmd+Space, type "System Preferences"
  2. Access Network Settings

    • Click on "Network"
    • Select "Wi-Fi" from the left sidebar
    • Click "Advanced..." button
  3. Configure DNS

    • Click the "DNS" tab
    • Click the "+" button to add DNS servers
    • Enter your preferred DNS servers (e.g., 1.1.1.1, 1.0.0.1)
    • Drag servers to reorder them by priority
  4. Apply Settings

    • Click "OK" to close the Advanced window
    • Click "Apply" to save changes

Command Line Verification

After manual configuration, verify settings using Terminal:

# Check current DNS servers
networksetup -getdnsservers "Wi-Fi"

# Test DNS resolution
nslookup google.com
dig google.com

# Check DNS response time
time nslookup google.com

DNS Management Scripts

Current DNS Information Script

Script to gather comprehensive DNS information:

#!/bin/bash

# DNS Information Gathering Script
echo "DNS Configuration Report"
echo "======================="
echo "Date: $(date)"
echo "Hostname: $(hostname)"
echo ""

# Get all network interfaces
interfaces=$(networksetup -listallnetworkservices | grep -v "denotes")

echo "Network Interfaces and DNS Settings:"
echo "-----------------------------------"

while IFS= read -r interface; do
    if [[ "$interface" != "" ]]; then
        echo "Interface: $interface"
        dns_servers=$(networksetup -getdnsservers "$interface")
        
        if [[ "$dns_servers" == "There aren't any DNS Servers set on"* ]]; then
            echo "  DNS: Automatic (DHCP)"
        else
            echo "  DNS Servers:"
            echo "$dns_servers" | while read -r server; do
                echo "    - $server"
            done
        fi
        echo ""
    fi
done <<< "$interfaces"

# Test DNS resolution performance
echo "DNS Resolution Test:"
echo "-------------------"
test_domains=("google.com" "cloudflare.com" "github.com")

for domain in "${test_domains[@]}"; do
    echo "Testing $domain..."
    time_result=$(time (nslookup "$domain" >/dev/null 2>&1) 2>&1 | grep real | awk '{print $2}')
    echo "  Resolution time: $time_result"
done

DNS Backup and Restore Script

#!/bin/bash

# DNS Backup and Restore Script
BACKUP_DIR="$HOME/dns_backups"
BACKUP_FILE="$BACKUP_DIR/dns_backup_$(date +%Y%m%d_%H%M%S).txt"

# Create backup directory
mkdir -p "$BACKUP_DIR"

# Function to backup DNS settings
backup_dns() {
    echo "Backing up DNS settings..."
    
    {
        echo "DNS Backup - $(date)"
        echo "======================"
        echo ""
        
        # Get all network interfaces
        interfaces=$(networksetup -listallnetworkservices | grep -v "denotes")
        
        while IFS= read -r interface; do
            if [[ "$interface" != "" ]]; then
                echo "Interface: $interface"
                networksetup -getdnsservers "$interface"
                echo ""
            fi
        done <<< "$interfaces"
        
    } > "$BACKUP_FILE"
    
    echo "DNS settings backed up to: $BACKUP_FILE"
}

# Function to restore DNS settings
restore_dns() {
    local backup_file=$1
    
    if [[ ! -f "$backup_file" ]]; then
        echo "Backup file not found: $backup_file"
        return 1
    fi
    
    echo "Restoring DNS settings from: $backup_file"
    echo "Note: Manual restoration required - backup file contains configuration for reference"
    cat "$backup_file"
}

# Main script logic
case "${1:-backup}" in
    backup)
        backup_dns
        ;;
    restore)
        restore_dns "$2"
        ;;
    list)
        echo "Available backups:"
        ls -la "$BACKUP_DIR"
        ;;
    *)
        echo "Usage: $0 [backup|restore <file>|list]"
        exit 1
        ;;
esac

Troubleshooting DNS Issues

Common DNS Problems and Solutions

  1. Slow Internet Browsing

    # Test DNS response times
    time nslookup google.com 8.8.8.8
    time nslookup google.com 1.1.1.1
    
    # Switch to faster DNS server
    sudo networksetup -setdnsservers "Wi-Fi" 1.1.1.1 1.0.0.1
  2. Unable to Access Certain Websites

    # Check if DNS is resolving the domain
    nslookup problematic-site.com
    
    # Try different DNS server
    nslookup problematic-site.com 8.8.8.8
  3. DNS Cache Issues

    # Flush DNS cache
    sudo dscacheutil -flushcache
    sudo killall -HUP mDNSResponder

DNS Diagnostic Script

#!/bin/bash

# DNS Diagnostic Script
echo "DNS Diagnostic Report"
echo "===================="
echo "Date: $(date)"
echo ""

# Check current DNS configuration
echo "1. Current DNS Configuration:"
echo "----------------------------"
networksetup -getdnsservers "Wi-Fi"
echo ""

# Test connectivity to common DNS servers
echo "2. DNS Server Connectivity Test:"
echo "--------------------------------"
dns_servers=("8.8.8.8" "1.1.1.1" "208.67.222.222" "9.9.9.9")

for server in "${dns_servers[@]}"; do
    if ping -c 1 -W 1000 "$server" >/dev/null 2>&1; then
        echo "✓ $server - Reachable"
    else
        echo "✗ $server - Unreachable"
    fi
done
echo ""

# Test DNS resolution
echo "3. DNS Resolution Test:"
echo "----------------------"
test_domains=("google.com" "cloudflare.com" "github.com")

for domain in "${test_domains[@]}"; do
    if nslookup "$domain" >/dev/null 2>&1; then
        echo "✓ $domain - Resolves correctly"
    else
        echo "✗ $domain - Resolution failed"
    fi
done
echo ""

# Check for DNS leaks
echo "4. DNS Leak Check:"
echo "-----------------"
echo "Current DNS resolver:"
nslookup myip.opendns.com resolver1.opendns.com | grep "Address" | tail -1
echo ""

echo "Diagnostic complete!"

Best Practices for DNS Configuration

1. Security Considerations

  • Use reputable DNS providers with security features
  • Regularly update DNS settings based on threat intelligence
  • Consider DNS-over-HTTPS (DoH) for enhanced privacy
  • Monitor DNS queries for suspicious activity

2. Performance Optimization

  • Test multiple DNS providers to find the fastest for your location
  • Use primary and secondary DNS servers for redundancy
  • Consider geographic proximity when selecting DNS servers
  • Monitor DNS resolution times regularly

3. Enterprise Management

  • Standardize DNS settings across all organizational devices
  • Document DNS configurations for disaster recovery
  • Implement DNS filtering for security and compliance
  • Use automated scripts for bulk configuration changes

4. Backup and Recovery

  • Always backup current DNS settings before making changes
  • Test new DNS configurations in a controlled environment
  • Have a rollback plan for DNS changes
  • Document all DNS configuration changes

Advanced DNS Configuration

DNS-over-HTTPS (DoH) Configuration

For enhanced privacy, configure DNS-over-HTTPS:

#!/bin/bash

# Configure DNS-over-HTTPS (DoH) on macOS
# Note: This requires macOS 11.0 or later

# Enable DoH with Cloudflare
sudo networksetup -setdnsservers "Wi-Fi" 1.1.1.1 1.0.0.1
sudo defaults write /Library/Preferences/com.apple.networkd.plist DoHServers -dict-add "1.1.1.1" "https://cloudflare-dns.com/dns-query"
sudo defaults write /Library/Preferences/com.apple.networkd.plist DoHServers -dict-add "1.0.0.1" "https://cloudflare-dns.com/dns-query"

# Restart network services
sudo launchctl unload /System/Library/LaunchDaemons/com.apple.networkd.plist
sudo launchctl load /System/Library/LaunchDaemons/com.apple.networkd.plist

echo "DNS-over-HTTPS configured with Cloudflare"

Custom DNS Configuration for Specific Domains

#!/bin/bash

# Configure custom DNS for specific domains
# Uses /etc/resolver for domain-specific DNS

# Create resolver directory
sudo mkdir -p /etc/resolver

# Configure specific domain to use custom DNS
echo "nameserver 8.8.8.8" | sudo tee /etc/resolver/company.local
echo "nameserver 8.8.4.4" | sudo tee -a /etc/resolver/company.local

# Flush DNS cache
sudo dscacheutil -flushcache
sudo killall -HUP mDNSResponder

echo "Custom DNS configured for company.local domain"

Monitoring and Maintenance

DNS Monitoring Script

#!/bin/bash

# DNS Monitoring Script
LOG_FILE="/var/log/dns_monitor.log"

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

# Monitor DNS performance
monitor_dns() {
    local dns_server=$1
    local test_domain=$2
    
    start_time=$(date +%s%N)
    if nslookup "$test_domain" "$dns_server" >/dev/null 2>&1; then
        end_time=$(date +%s%N)
        duration=$((($end_time - $start_time) / 1000000))
        log_message "DNS $dns_server: $test_domain resolved in ${duration}ms"
    else
        log_message "DNS $dns_server: Failed to resolve $test_domain"
    fi
}

# Monitor multiple DNS servers
dns_servers=("8.8.8.8" "1.1.1.1" "208.67.222.222")
test_domain="google.com"

log_message "Starting DNS monitoring"

for server in "${dns_servers[@]}"; do
    monitor_dns "$server" "$test_domain"
done

log_message "DNS monitoring complete"

Conclusion

Proper DNS configuration is crucial for optimal internet performance, security, and privacy. The scripts and methods provided in this guide offer comprehensive solutions for managing DNS settings on macOS devices, from simple configurations to advanced enterprise deployments.

Key takeaways:

  • Choose DNS providers that align with your performance and privacy requirements
  • Regularly test and monitor DNS performance
  • Implement proper backup and recovery procedures
  • Consider security implications of DNS configuration
  • Use automation for large-scale deployments

Remember to test any DNS changes in a controlled environment before deploying them across your Mac fleet. Proper DNS management can significantly improve your network experience while enhancing security and privacy.

Display Brightness Management and Energy Optimization on macOS

Manage display brightness and energy consumption across your MacFleet devices with comprehensive brightness control, adaptive lighting policies, and enterprise energy optimization tools. This tutorial covers brightness adjustment, automated scheduling, and fleet-wide display management.

Understanding Display Brightness Management

Display brightness control on macOS affects both user experience and energy consumption. Enterprise management includes:

  • Brightness Control - Direct adjustment of display luminosity levels
  • Adaptive Lighting - Automatic adjustment based on environment and time
  • Energy Optimization - Battery conservation through intelligent display management
  • User Experience - Consistent display settings across enterprise devices

Enterprise Benefits

Proper display brightness management provides enterprise advantages:

  • Energy Conservation - Reduced power consumption and extended battery life
  • User Comfort - Optimal viewing conditions for different work environments
  • Security Enhancement - Dimmed displays in public spaces for privacy
  • Health Benefits - Reduced eye strain through proper lighting
  • Standardization - Consistent display experience across device fleet

Basic Brightness Control

Prerequisites and Setup

#!/bin/bash

# Install Homebrew and brightness control tool
install_brightness_tools() {
    echo "=== Installing Brightness Control Tools ==="
    
    # Check if Homebrew is installed
    if ! command -v brew >/dev/null 2>&1; then
        echo "Installing Homebrew..."
        /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
        
        # Add Homebrew to PATH for current session
        eval "$(/opt/homebrew/bin/brew shellenv)" 2>/dev/null || eval "$(/usr/local/bin/brew shellenv)" 2>/dev/null
    else
        echo "✓ Homebrew already installed"
    fi
    
    # Install brightness control tool
    if ! command -v brightness >/dev/null 2>&1; then
        echo "Installing brightness control tool..."
        brew install brightness
    else
        echo "✓ Brightness tool already installed"
    fi
    
    echo "✓ Brightness control tools installation complete"
}

# Usage
install_brightness_tools

Basic Brightness Commands

#!/bin/bash

# Set brightness to specific levels
set_brightness() {
    local level="$1"
    
    if [[ -z "$level" ]]; then
        echo "Usage: set_brightness <level>"
        echo "Level should be between 0.0 (dark) and 1.0 (brightest)"
        return 1
    fi
    
    # Validate brightness level
    if ! [[ "$level" =~ ^[0-9]*\.?[0-9]+$ ]] || (( $(echo "$level > 1.0" | bc -l) )) || (( $(echo "$level < 0.0" | bc -l) )); then
        echo "Error: Brightness level must be between 0.0 and 1.0"
        return 1
    fi
    
    echo "Setting brightness to ${level} ($(echo "$level * 100" | bc)%)"
    
    # Try different brightness command locations
    if command -v brightness >/dev/null 2>&1; then
        brightness "$level"
    elif [[ -x "/usr/local/bin/brightness" ]]; then
        /usr/local/bin/brightness "$level"
    elif [[ -x "/opt/homebrew/bin/brightness" ]]; then
        /opt/homebrew/bin/brightness "$level"
    elif [[ -x "/usr/local/Cellar/brightness/1.2/bin/brightness" ]]; then
        /usr/local/Cellar/brightness/1.2/bin/brightness "$level"
    else
        echo "Error: Brightness control tool not found"
        return 1
    fi
    
    echo "✓ Brightness set to ${level}"
}

# Predefined brightness levels
set_brightness_full() {
    echo "Setting brightness to 100%"
    set_brightness "1.0"
}

set_brightness_high() {
    echo "Setting brightness to 75%"
    set_brightness "0.75"
}

set_brightness_medium() {
    echo "Setting brightness to 50%"
    set_brightness "0.5"
}

set_brightness_low() {
    echo "Setting brightness to 25%"
    set_brightness "0.25"
}

set_brightness_dim() {
    echo "Setting brightness to 10%"
    set_brightness "0.1"
}

# Usage examples
set_brightness_medium

Get Current Brightness Level

#!/bin/bash

# Get current brightness level
get_current_brightness() {
    echo "=== Current Display Brightness ==="
    
    # Try to get brightness using different methods
    local current_brightness=""
    
    # Method 1: Using brightness command
    if command -v brightness >/dev/null 2>&1; then
        current_brightness=$(brightness -l 2>/dev/null | grep -o '[0-9]*\.[0-9]*' | head -1)
    fi
    
    # Method 2: Using system_profiler (fallback)
    if [[ -z "$current_brightness" ]]; then
        current_brightness=$(system_profiler SPDisplaysDataType | grep -i "brightness" | awk '{print $2}' | head -1)
    fi
    
    # Method 3: Using ioreg (alternative fallback)
    if [[ -z "$current_brightness" ]]; then
        local brightness_raw=$(ioreg -c AppleBacklightDisplay | grep brightness | head -1)
        if [[ -n "$brightness_raw" ]]; then
            current_brightness=$(echo "$brightness_raw" | grep -o '[0-9]*\.[0-9]*')
        fi
    fi
    
    if [[ -n "$current_brightness" ]]; then
        local percentage=$(echo "$current_brightness * 100" | bc)
        echo "Current Brightness: $current_brightness (${percentage}%)"
        return 0
    else
        echo "Unable to determine current brightness level"
        return 1
    fi
}

# Usage
get_current_brightness

Advanced Brightness Management

Adaptive Brightness Control

#!/bin/bash

# Adaptive brightness based on time of day and conditions
adaptive_brightness_control() {
    local mode="${1:-auto}"
    local location_lat="${2:-}"
    local location_lon="${3:-}"
    
    echo "=== Adaptive Brightness Control ==="
    echo "Mode: $mode"
    echo "Date: $(date)"
    echo ""
    
    case "$mode" in
        "auto")
            automatic_brightness_adjustment
            ;;
        "schedule")
            scheduled_brightness_adjustment
            ;;
        "ambient")
            ambient_light_brightness "$location_lat" "$location_lon"
            ;;
        "work_hours")
            work_hours_brightness
            ;;
        "battery_saver")
            battery_aware_brightness
            ;;
        *)
            echo "Unknown mode: $mode"
            echo "Available modes: auto, schedule, ambient, work_hours, battery_saver"
            return 1
            ;;
    esac
}

# Automatic brightness based on time of day
automatic_brightness_adjustment() {
    local current_hour=$(date +%H)
    local current_minute=$(date +%M)
    local time_decimal=$(echo "$current_hour + $current_minute / 60" | bc -l)
    
    echo "--- Automatic Brightness Adjustment ---"
    echo "Current time: $current_hour:$(printf "%02d" $current_minute)"
    
    local brightness_level
    
    if (( $(echo "$time_decimal >= 6 && $time_decimal < 9" | bc -l) )); then
        # Morning: Gradual increase
        brightness_level="0.4"
        echo "Time period: Morning (6:00-9:00) - Setting moderate brightness"
    elif (( $(echo "$time_decimal >= 9 && $time_decimal < 17" | bc -l) )); then
        # Work hours: Full brightness
        brightness_level="0.8"
        echo "Time period: Work hours (9:00-17:00) - Setting high brightness"
    elif (( $(echo "$time_decimal >= 17 && $time_decimal < 20" | bc -l) )); then
        # Evening: Medium brightness
        brightness_level="0.6"
        echo "Time period: Evening (17:00-20:00) - Setting medium brightness"
    elif (( $(echo "$time_decimal >= 20 && $time_decimal < 22" | bc -l) )); then
        # Night: Low brightness
        brightness_level="0.3"
        echo "Time period: Night (20:00-22:00) - Setting low brightness"
    else
        # Late night/early morning: Very low
        brightness_level="0.1"
        echo "Time period: Late night/Early morning - Setting very low brightness"
    fi
    
    set_brightness "$brightness_level"
}

# Scheduled brightness changes
scheduled_brightness_adjustment() {
    echo "--- Scheduled Brightness Adjustment ---"
    
    # Define schedule (hour:brightness_level)
    local schedule=(
        "06:00:0.3"  # Dawn
        "08:00:0.6"  # Morning
        "09:00:0.8"  # Work start
        "12:00:0.9"  # Midday
        "17:00:0.7"  # Work end
        "19:00:0.5"  # Evening
        "21:00:0.3"  # Night
        "23:00:0.1"  # Late night
    )
    
    local current_time=$(date +%H:%M)
    echo "Current time: $current_time"
    
    # Find the appropriate brightness level for current time
    local target_brightness="0.5"  # Default
    
    for schedule_entry in "${schedule[@]}"; do
        IFS=':' read -r schedule_time schedule_brightness <<< "$schedule_entry"
        
        if [[ "$current_time" > "$schedule_time" ]] || [[ "$current_time" == "$schedule_time" ]]; then
            target_brightness="$schedule_brightness"
        fi
    done
    
    echo "Scheduled brightness level: $target_brightness"
    set_brightness "$target_brightness"
}

# Battery-aware brightness management
battery_aware_brightness() {
    echo "--- Battery-Aware Brightness Management ---"
    
    # Get battery information
    local battery_info=$(pmset -g batt)
    local battery_percentage=$(echo "$battery_info" | grep -o '[0-9]*%' | head -1 | tr -d '%')
    local power_source=$(echo "$battery_info" | grep -o "AC Power\|Battery Power" | head -1)
    
    echo "Battery level: ${battery_percentage}%"
    echo "Power source: $power_source"
    
    local brightness_level
    
    if [[ "$power_source" == "AC Power" ]]; then
        # On AC power - normal brightness
        brightness_level="0.8"
        echo "On AC power - Setting normal brightness"
    else
        # On battery - adjust based on battery level
        if [[ $battery_percentage -gt 50 ]]; then
            brightness_level="0.6"
            echo "Battery > 50% - Setting medium brightness"
        elif [[ $battery_percentage -gt 20 ]]; then
            brightness_level="0.4"
            echo "Battery 20-50% - Setting low brightness"
        else
            brightness_level="0.2"
            echo "Battery < 20% - Setting very low brightness"
        fi
    fi
    
    set_brightness "$brightness_level"
}

# Usage
adaptive_brightness_control "auto"

Display Environment Analysis

#!/bin/bash

# Analyze display environment and recommend brightness
analyze_display_environment() {
    echo "=== Display Environment Analysis ==="
    echo "Analysis Date: $(date)"
    echo ""
    
    # System information
    echo "--- System Information ---"
    local hostname=$(hostname)
    local os_version=$(sw_vers -productVersion)
    local hardware_model=$(system_profiler SPHardwareDataType | grep "Model Identifier" | awk '{print $3}')
    
    echo "Hostname: $hostname"
    echo "macOS Version: $os_version"
    echo "Hardware Model: $hardware_model"
    
    # Display information
    echo ""
    echo "--- Display Information ---"
    local display_info=$(system_profiler SPDisplaysDataType)
    local display_count=$(echo "$display_info" | grep "Display Type" | wc -l | tr -d ' ')
    
    echo "Number of displays: $display_count"
    
    # Extract display details
    if [[ $display_count -gt 0 ]]; then
        echo "$display_info" | grep -E "(Display Type|Resolution|Main Display)" | while read -r line; do
            echo "  $line"
        done
    fi
    
    # Power and battery analysis
    echo ""
    echo "--- Power Analysis ---"
    local power_info=$(pmset -g batt)
    echo "$power_info"
    
    # Check if device supports ambient light sensor
    echo ""
    echo "--- Ambient Light Sensor ---"
    if ioreg -c IOHIDSystem | grep -q "AmbientLightSensor"; then
        echo "✓ Ambient light sensor detected"
        
        # Try to get ambient light reading
        local ambient_light=$(ioreg -c IOHIDSystem | grep "AmbientLightSensor" -A 10 | grep "AmbientLightValue" | awk '{print $3}')
        if [[ -n "$ambient_light" ]]; then
            echo "Ambient light level: $ambient_light lux"
        fi
    else
        echo "⚠️ No ambient light sensor detected"
    fi
    
    # Recommendations
    echo ""
    echo "--- Brightness Recommendations ---"
    recommend_brightness_settings
}

# Recommend brightness settings based on environment
recommend_brightness_settings() {
    local current_hour=$(date +%H)
    local battery_info=$(pmset -g batt)
    local battery_percentage=$(echo "$battery_info" | grep -o '[0-9]*%' | head -1 | tr -d '%')
    local power_source=$(echo "$battery_info" | grep -o "AC Power\|Battery Power" | head -1)
    
    echo "Based on current conditions:"
    echo "- Time: $current_hour:00"
    echo "- Power: $power_source"
    echo "- Battery: ${battery_percentage}%"
    echo ""
    
    # Time-based recommendations
    if [[ $current_hour -ge 6 && $current_hour -lt 9 ]]; then
        echo "Morning recommendation: 40-60% brightness for gradual eye adjustment"
    elif [[ $current_hour -ge 9 && $current_hour -lt 17 ]]; then
        echo "Work hours recommendation: 70-90% brightness for optimal productivity"
    elif [[ $current_hour -ge 17 && $current_hour -lt 20 ]]; then
        echo "Evening recommendation: 50-70% brightness for comfortable viewing"
    else
        echo "Night recommendation: 10-30% brightness to reduce eye strain"
    fi
    
    # Power-based recommendations
    if [[ "$power_source" == "Battery Power" && $battery_percentage -lt 30 ]]; then
        echo "Low battery recommendation: Reduce brightness to 20-40% to conserve power"
    fi
}

# Usage
analyze_display_environment

Enterprise Display Management System

#!/bin/bash

# MacFleet Display Brightness Management Tool
# Comprehensive display control, energy optimization, and fleet management

# Configuration
SCRIPT_VERSION="1.0.0"
LOG_FILE="/var/log/macfleet_display_management.log"
REPORT_DIR="/etc/macfleet/reports/display"
CONFIG_DIR="/etc/macfleet/display"
POLICY_DIR="/etc/macfleet/policies/display"
SCHEDULE_DIR="/etc/macfleet/schedules/display"

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

# Display management policy templates
declare -A DISPLAY_POLICIES=(
    ["enterprise_standard"]="adaptive_brightness,battery_optimization,work_hours_profile,user_override_limited"
    ["energy_saver"]="aggressive_dimming,battery_priority,low_brightness_default,power_aware_scheduling"
    ["presentation_mode"]="high_brightness,stable_settings,no_auto_dimming,optimal_visibility"
    ["kiosk_display"]="fixed_brightness,no_user_control,scheduled_adjustments,energy_optimized"
    ["healthcare"]="eye_strain_reduction,shift_appropriate,patient_privacy,energy_conscious"
    ["financial"]="security_dimming,privacy_protection,energy_compliance,professional_display"
    ["education"]="classroom_optimized,energy_teaching,adaptive_learning,student_friendly"
    ["retail"]="customer_facing,bright_displays,brand_consistency,operational_hours"
    ["manufacturing"]="industrial_visibility,safety_priority,harsh_environment,energy_efficient"
    ["government"]="security_compliant,energy_mandates,accessibility_aware,audit_ready"
)

# Brightness profiles for different use cases
declare -A BRIGHTNESS_PROFILES=(
    ["work_day"]="morning:0.4,work_start:0.8,lunch:0.9,afternoon:0.8,work_end:0.6"
    ["energy_saver"]="morning:0.3,work_start:0.6,lunch:0.7,afternoon:0.6,work_end:0.4"
    ["presentation"]="all_day:0.9,constant_high:1.0"
    ["night_shift"]="evening:0.4,night:0.2,late_night:0.1,dawn:0.3"
    ["retail_hours"]="open:0.9,peak:1.0,closing:0.7,after_hours:0.2"
    ["healthcare_24"]="day_shift:0.7,evening_shift:0.5,night_shift:0.3,emergency:0.8"
)

# Energy optimization thresholds
declare -A ENERGY_THRESHOLDS=(
    ["battery_critical"]="20:0.2"      # Below 20% battery: 20% brightness
    ["battery_low"]="30:0.4"           # Below 30% battery: 40% brightness
    ["battery_medium"]="50:0.6"        # Below 50% battery: 60% brightness
    ["battery_high"]="80:0.8"          # Above 80% battery: 80% brightness
    ["ac_power"]="100:0.9"             # On AC power: 90% brightness
)

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

# Enhanced brightness control with validation
set_brightness_enhanced() {
    local brightness_level="$1"
    local reason="${2:-Manual adjustment}"
    local user="${3:-$(whoami)}"
    
    log_action "Setting brightness to $brightness_level for user $user - Reason: $reason"
    
    # Validate brightness level
    if ! [[ "$brightness_level" =~ ^[0-9]*\.?[0-9]+$ ]] || 
       (( $(echo "$brightness_level > 1.0" | bc -l) )) || 
       (( $(echo "$brightness_level < 0.0" | bc -l) )); then
        log_action "ERROR: Invalid brightness level: $brightness_level"
        return 1
    fi
    
    # Store previous brightness for rollback capability
    local previous_brightness=$(get_current_brightness_value)
    
    # Apply brightness change
    local brightness_cmd=""
    if command -v brightness >/dev/null 2>&1; then
        brightness_cmd="brightness"
    elif [[ -x "/opt/homebrew/bin/brightness" ]]; then
        brightness_cmd="/opt/homebrew/bin/brightness"
    elif [[ -x "/usr/local/bin/brightness" ]]; then
        brightness_cmd="/usr/local/bin/brightness"
    elif [[ -x "/usr/local/Cellar/brightness/1.2/bin/brightness" ]]; then
        brightness_cmd="/usr/local/Cellar/brightness/1.2/bin/brightness"
    else
        log_action "ERROR: Brightness control command not found"
        return 1
    fi
    
    if $brightness_cmd "$brightness_level" 2>/dev/null; then
        local percentage=$(echo "$brightness_level * 100" | bc)
        log_action "SUCCESS: Brightness set to $brightness_level (${percentage}%)"
        
        # Record change in history
        echo "$(date '+%Y-%m-%d %H:%M:%S'),$user,$previous_brightness,$brightness_level,$reason" >> "$CONFIG_DIR/brightness_history.csv"
        
        return 0
    else
        log_action "ERROR: Failed to set brightness to $brightness_level"
        return 1
    fi
}

# Get current brightness as numeric value
get_current_brightness_value() {
    local current_brightness=""
    
    if command -v brightness >/dev/null 2>&1; then
        current_brightness=$(brightness -l 2>/dev/null | grep -o '[0-9]*\.[0-9]*' | head -1)
    fi
    
    if [[ -n "$current_brightness" ]]; then
        echo "$current_brightness"
    else
        echo "0.5"  # Default fallback
    fi
}

# Apply brightness profile
apply_brightness_profile() {
    local profile_name="$1"
    local override_time="${2:-}"
    
    log_action "Applying brightness profile: $profile_name"
    
    if [[ -z "${BRIGHTNESS_PROFILES[$profile_name]}" ]]; then
        log_action "ERROR: Unknown brightness profile: $profile_name"
        echo "Available profiles: ${!BRIGHTNESS_PROFILES[*]}"
        return 1
    fi
    
    local profile_settings="${BRIGHTNESS_PROFILES[$profile_name]}"
    local current_time="${override_time:-$(date +%H:%M)}"
    local current_hour=$(echo "$current_time" | cut -d: -f1)
    
    echo "=== Applying Brightness Profile: $profile_name ==="
    echo "Current time: $current_time"
    echo "Profile settings: $profile_settings"
    
    # Parse profile settings and find appropriate brightness
    local target_brightness="0.5"  # Default
    local matched_period="default"
    
    IFS=',' read -ra SETTINGS <<< "$profile_settings"
    for setting in "${SETTINGS[@]}"; do
        IFS=':' read -ra TIME_BRIGHTNESS <<< "$setting"
        local time_period="${TIME_BRIGHTNESS[0]}"
        local brightness_value="${TIME_BRIGHTNESS[1]}"
        
        case "$time_period" in
            "morning")
                if [[ $current_hour -ge 6 && $current_hour -lt 9 ]]; then
                    target_brightness="$brightness_value"
                    matched_period="morning"
                fi
                ;;
            "work_start"|"work")
                if [[ $current_hour -ge 9 && $current_hour -lt 12 ]]; then
                    target_brightness="$brightness_value"
                    matched_period="work_start"
                fi
                ;;
            "lunch"|"midday")
                if [[ $current_hour -ge 12 && $current_hour -lt 14 ]]; then
                    target_brightness="$brightness_value"
                    matched_period="lunch"
                fi
                ;;
            "afternoon")
                if [[ $current_hour -ge 14 && $current_hour -lt 17 ]]; then
                    target_brightness="$brightness_value"
                    matched_period="afternoon"
                fi
                ;;
            "work_end"|"evening")
                if [[ $current_hour -ge 17 && $current_hour -lt 20 ]]; then
                    target_brightness="$brightness_value"
                    matched_period="evening"
                fi
                ;;
            "night")
                if [[ $current_hour -ge 20 && $current_hour -lt 23 ]]; then
                    target_brightness="$brightness_value"
                    matched_period="night"
                fi
                ;;
            "late_night")
                if [[ $current_hour -ge 23 || $current_hour -lt 6 ]]; then
                    target_brightness="$brightness_value"
                    matched_period="late_night"
                fi
                ;;
            "all_day"|"constant_high")
                target_brightness="$brightness_value"
                matched_period="all_day"
                ;;
        esac
    done
    
    echo "Matched time period: $matched_period"
    echo "Target brightness: $target_brightness"
    
    # Apply the brightness
    set_brightness_enhanced "$target_brightness" "Profile: $profile_name ($matched_period)"
}

# Energy-aware brightness management
energy_aware_brightness() {
    local policy="${1:-balanced}"
    
    log_action "Starting energy-aware brightness management with policy: $policy"
    
    echo "=== Energy-Aware Brightness Management ==="
    echo "Policy: $policy"
    echo ""
    
    # Get power status
    local battery_info=$(pmset -g batt)
    local battery_percentage=$(echo "$battery_info" | grep -o '[0-9]*%' | head -1 | tr -d '%')
    local power_source=$(echo "$battery_info" | grep -o "AC Power\|Battery Power" | head -1)
    local charging_status=$(echo "$battery_info" | grep -o "charging\|charged\|discharging" | head -1)
    
    echo "--- Power Status ---"
    echo "Power Source: $power_source"
    echo "Battery Level: ${battery_percentage}%"
    echo "Charging Status: $charging_status"
    
    # Determine brightness based on energy policy
    local target_brightness=""
    local energy_reason=""
    
    case "$policy" in
        "aggressive")
            if [[ "$power_source" == "AC Power" ]]; then
                target_brightness="0.8"
                energy_reason="AC power - normal brightness"
            else
                if [[ $battery_percentage -lt 20 ]]; then
                    target_brightness="0.15"
                    energy_reason="Critical battery - minimum brightness"
                elif [[ $battery_percentage -lt 40 ]]; then
                    target_brightness="0.25"
                    energy_reason="Low battery - very low brightness"
                else
                    target_brightness="0.4"
                    energy_reason="Battery power - low brightness"
                fi
            fi
            ;;
        "balanced")
            if [[ "$power_source" == "AC Power" ]]; then
                target_brightness="0.8"
                energy_reason="AC power - normal brightness"
            else
                if [[ $battery_percentage -lt 20 ]]; then
                    target_brightness="0.2"
                    energy_reason="Low battery - reduced brightness"
                elif [[ $battery_percentage -lt 50 ]]; then
                    target_brightness="0.4"
                    energy_reason="Medium battery - moderate brightness"
                else
                    target_brightness="0.6"
                    energy_reason="Good battery - normal brightness"
                fi
            fi
            ;;
        "performance")
            if [[ "$power_source" == "AC Power" ]]; then
                target_brightness="0.9"
                energy_reason="AC power - high brightness"
            else
                if [[ $battery_percentage -lt 15 ]]; then
                    target_brightness="0.3"
                    energy_reason="Critical battery - power saving"
                else
                    target_brightness="0.7"
                    energy_reason="Battery power - maintain visibility"
                fi
            fi
            ;;
    esac
    
    echo ""
    echo "--- Energy Decision ---"
    echo "Policy: $policy"
    echo "Decision: $energy_reason"
    echo "Target Brightness: $target_brightness"
    
    # Apply brightness change
    set_brightness_enhanced "$target_brightness" "$energy_reason"
    
    # Log energy savings estimate
    local current_brightness=$(get_current_brightness_value)
    local energy_savings=$(echo "($current_brightness - $target_brightness) * 20" | bc)  # Rough estimate
    
    if (( $(echo "$energy_savings > 0" | bc -l) )); then
        echo "Estimated energy savings: ${energy_savings}% display power reduction"
        log_action "Energy savings estimated: ${energy_savings}% display power reduction"
    fi
}

# Fleet brightness management
manage_fleet_brightness() {
    local operation="$1"
    local target_brightness="$2"
    local fleet_scope="${3:-local}"
    
    log_action "Fleet brightness management: $operation (scope: $fleet_scope)"
    
    echo "=== Fleet Brightness Management ==="
    echo "Operation: $operation"
    echo "Target Brightness: $target_brightness"
    echo "Fleet Scope: $fleet_scope"
    echo ""
    
    case "$operation" in
        "set_all")
            echo "Setting brightness to $target_brightness across fleet..."
            set_brightness_enhanced "$target_brightness" "Fleet-wide adjustment"
            ;;
        "energy_optimize")
            echo "Optimizing brightness for energy efficiency..."
            energy_aware_brightness "balanced"
            ;;
        "sync_profiles")
            echo "Synchronizing brightness profiles across fleet..."
            apply_brightness_profile "work_day"
            ;;
        "emergency_dim")
            echo "Applying emergency dimming for power conservation..."
            set_brightness_enhanced "0.1" "Emergency power conservation"
            ;;
        "restore_normal")
            echo "Restoring normal brightness levels..."
            apply_brightness_profile "work_day"
            ;;
        *)
            log_action "ERROR: Unknown fleet operation: $operation"
            return 1
            ;;
    esac
    
    # Generate fleet status report
    generate_brightness_status_report
}

# Generate brightness status report
generate_brightness_status_report() {
    local report_file="$REPORT_DIR/brightness_status_$(date +%Y%m%d_%H%M%S).json"
    
    local current_brightness=$(get_current_brightness_value)
    local battery_info=$(pmset -g batt)
    local battery_percentage=$(echo "$battery_info" | grep -o '[0-9]*%' | head -1 | tr -d '%')
    local power_source=$(echo "$battery_info" | grep -o "AC Power\|Battery Power" | head -1)
    
    cat > "$report_file" << EOF
{
    "brightness_status_report": {
        "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
        "hostname": "$(hostname)",
        "script_version": "$SCRIPT_VERSION",
        "display_status": {
            "current_brightness": $current_brightness,
            "brightness_percentage": $(echo "$current_brightness * 100" | bc),
            "power_source": "$power_source",
            "battery_level": $battery_percentage
        },
        "system_info": {
            "os_version": "$(sw_vers -productVersion)",
            "hardware_model": "$(system_profiler SPHardwareDataType | grep 'Model Identifier' | awk '{print $3}')",
            "display_count": $(system_profiler SPDisplaysDataType | grep "Display Type" | wc -l | tr -d ' ')
        }
    }
}
EOF
    
    echo "Brightness status report generated: $report_file"
    log_action "Status report generated: $report_file"
}

# Main execution function
main() {
    local action="${1:-help}"
    local param1="${2:-}"
    local param2="${3:-}"
    local param3="${4:-}"
    local param4="${5:-}"
    
    log_action "=== MacFleet Display Brightness Management Started ==="
    log_action "Action: $action"
    
    case "$action" in
        "set")
            if [[ -z "$param1" ]]; then
                echo "Usage: $0 set <brightness_level> [reason]"
                echo "Brightness level: 0.0-1.0 (0-100%)"
                exit 1
            fi
            set_brightness_enhanced "$param1" "${param2:-Manual setting}"
            ;;
        "get")
            echo "Current brightness: $(get_current_brightness_value)"
            ;;
        "profile")
            if [[ -z "$param1" ]]; then
                echo "Available profiles: ${!BRIGHTNESS_PROFILES[*]}"
                exit 1
            fi
            apply_brightness_profile "$param1" "$param2"
            ;;
        "energy")
            energy_aware_brightness "${param1:-balanced}"
            ;;
        "analyze")
            analyze_display_environment
            ;;
        "fleet")
            if [[ -z "$param1" ]]; then
                echo "Usage: $0 fleet <operation> [brightness] [scope]"
                echo "Operations: set_all, energy_optimize, sync_profiles, emergency_dim, restore_normal"
                exit 1
            fi
            manage_fleet_brightness "$param1" "$param2" "$param3"
            ;;
        "adaptive")
            adaptive_brightness_control "${param1:-auto}"
            ;;
        "install")
            install_brightness_tools
            ;;
        "help")
            echo "Usage: $0 [action] [options...]"
            echo "Actions:"
            echo "  set <level> [reason] - Set brightness level (0.0-1.0)"
            echo "  get - Get current brightness level"
            echo "  profile <name> [time] - Apply brightness profile"
            echo "  energy [policy] - Energy-aware brightness management"
            echo "  analyze - Analyze display environment"
            echo "  fleet <operation> [params] - Fleet brightness management"
            echo "  adaptive [mode] - Adaptive brightness control"
            echo "  install - Install brightness control tools"
            echo "  help - Show this help"
            echo ""
            echo "Profiles: ${!BRIGHTNESS_PROFILES[*]}"
            echo "Policies: ${!DISPLAY_POLICIES[*]}"
            ;;
        *)
            log_action "ERROR: Unknown action: $action"
            echo "Use '$0 help' for usage information"
            exit 1
            ;;
    esac
    
    log_action "=== Display brightness management completed ==="
}

# Execute main function
main "$@"

Important Notes

  • Homebrew Required - The brightness control tool requires Homebrew installation
  • Intel Mac Support - Some brightness commands work only on Intel-based Macs
  • Battery Awareness - Brightness should be adjusted based on power source and battery level
  • User Experience - Sudden brightness changes can be jarring; implement gradual transitions
  • Enterprise Policies - Different work environments require different brightness strategies
  • Energy Conservation - Lower brightness significantly extends battery life
  • Health Considerations - Proper brightness reduces eye strain and fatigue

Disk Utility Management on macOS

Manage storage and disk operations across your MacFleet devices using advanced diskutil commands and enterprise storage management tools. This tutorial covers disk management, storage security, compliance monitoring, and enterprise storage lifecycle management.

Understanding macOS Disk Management

macOS provides several command-line tools for disk and storage management:

  • diskutil - Primary disk utility for volume and partition management
  • df - Display filesystem disk space usage
  • du - Display directory space usage
  • fsck - Filesystem check and repair utility
  • APFS - Apple File System with advanced features

Basic Disk Operations

List All Disks

#!/bin/bash

# Basic disk listing
diskutil list

echo "Disk inventory completed successfully"

Enhanced Disk Information

#!/bin/bash

# Enhanced disk information with detailed analysis
get_comprehensive_disk_info() {
    echo "=== Comprehensive Disk Analysis ==="
    
    # Basic disk list
    echo "Disk Inventory:"
    diskutil list
    
    echo -e "\nDisk Usage Summary:"
    df -h
    
    echo -e "\nAPFS Container Information:"
    diskutil apfs list
    
    echo -e "\nPhysical Disk Information:"
    system_profiler SPStorageDataType
    
    echo -e "\nSMART Status:"
    for disk in $(diskutil list | grep "^/dev/disk[0-9]" | awk '{print $1}'); do
        echo "SMART status for $disk:"
        smartctl -H "$disk" 2>/dev/null || echo "  SMART data not available"
    done
}

# Execute comprehensive analysis
get_comprehensive_disk_info

Storage Management Categories

Storage Type Classifications

#!/bin/bash

# Enterprise storage categories for management and policy enforcement
declare -A STORAGE_CATEGORIES=(
    ["system_critical"]="System volumes, boot partitions, recovery partitions"
    ["user_data"]="User home directories, personal documents, application data"
    ["application_storage"]="Application binaries, frameworks, system libraries"
    ["development_workspace"]="Development environments, source code, build artifacts"
    ["media_content"]="Videos, images, audio files, creative assets"
    ["backup_archives"]="Time Machine, system backups, archive storage"
    ["temporary_cache"]="Cache files, temporary data, system logs"
    ["security_volumes"]="Encrypted volumes, secure containers, key storage"
    ["network_storage"]="Mounted network drives, cloud storage, remote volumes"
    ["external_devices"]="USB drives, external HDDs, removable storage"
)

# Storage risk levels
declare -A RISK_LEVELS=(
    ["system_critical"]="critical"
    ["user_data"]="high"
    ["application_storage"]="medium"
    ["development_workspace"]="medium"
    ["media_content"]="low"
    ["backup_archives"]="high"
    ["temporary_cache"]="low"
    ["security_volumes"]="critical"
    ["network_storage"]="medium"
    ["external_devices"]="high"
)

# Management priorities
declare -A MANAGEMENT_PRIORITIES=(
    ["system_critical"]="highest_protection"
    ["user_data"]="high_protection"
    ["application_storage"]="standard_protection"
    ["development_workspace"]="standard_protection"
    ["media_content"]="basic_protection"
    ["backup_archives"]="highest_protection"
    ["temporary_cache"]="cleanup_priority"
    ["security_volumes"]="highest_protection"
    ["network_storage"]="monitoring_priority"
    ["external_devices"]="security_screening"
)

print_storage_categories() {
    echo "=== Storage Management Categories ==="
    for category in "${!STORAGE_CATEGORIES[@]}"; do
        echo "Category: $category"
        echo "  Description: ${STORAGE_CATEGORIES[$category]}"
        echo "  Risk Level: ${RISK_LEVELS[$category]}"
        echo "  Management Priority: ${MANAGEMENT_PRIORITIES[$category]}"
        echo ""
    done
}

# Display available categories
print_storage_categories

Disk Management Policies

Storage Policy Engine

#!/bin/bash

# Storage management policies for different organizational requirements
declare -A STORAGE_POLICIES=(
    ["enterprise_standard"]="Standard enterprise storage with backup and monitoring"
    ["high_security_financial"]="High-security storage for financial and sensitive data"
    ["creative_workflow"]="Optimized for creative teams with large media files"
    ["development_environment"]="Development-focused with version control and build optimization"
    ["compliance_strict"]="Strict compliance with data retention and audit requirements"
    ["performance_optimized"]="Performance-focused with SSD optimization and caching"
    ["cost_efficient"]="Cost-efficient storage with intelligent tiering and cleanup"
)

# Policy configurations
get_storage_policy() {
    local policy_type="$1"
    
    case "$policy_type" in
        "enterprise_standard")
            cat << EOF
{
    "encryption_required": true,
    "backup_frequency": "daily",
    "retention_period": "90_days",
    "compression_enabled": true,
    "deduplication": true,
    "monitoring_level": "standard",
    "security_scanning": true,
    "automatic_cleanup": false,
    "performance_optimization": "balanced",
    "compliance_frameworks": ["iso27001"],
    "disk_health_monitoring": true,
    "storage_quotas": {
        "user_data": "100GB",
        "application_storage": "50GB",
        "temporary_cache": "10GB"
    }
}
EOF
            ;;
        "high_security_financial")
            cat << EOF
{
    "encryption_required": true,
    "encryption_level": "aes256",
    "backup_frequency": "continuous",
    "retention_period": "2555_days",
    "compression_enabled": false,
    "deduplication": false,
    "monitoring_level": "comprehensive",
    "security_scanning": true,
    "automatic_cleanup": false,
    "performance_optimization": "security_first",
    "compliance_frameworks": ["sox", "pci_dss", "nist"],
    "disk_health_monitoring": true,
    "immutable_backups": true,
    "access_logging": "detailed",
    "integrity_verification": "continuous",
    "storage_quotas": {
        "user_data": "50GB",
        "application_storage": "25GB",
        "temporary_cache": "5GB",
        "audit_logs": "unlimited"
    }
}
EOF
            ;;
        "creative_workflow")
            cat << EOF
{
    "encryption_required": false,
    "backup_frequency": "project_based",
    "retention_period": "365_days",
    "compression_enabled": false,
    "deduplication": false,
    "monitoring_level": "performance",
    "security_scanning": false,
    "automatic_cleanup": true,
    "performance_optimization": "speed_first",
    "compliance_frameworks": ["client_confidentiality"],
    "disk_health_monitoring": true,
    "large_file_optimization": true,
    "cache_acceleration": true,
    "storage_quotas": {
        "user_data": "500GB",
        "media_content": "2TB",
        "project_archives": "1TB",
        "temporary_cache": "100GB"
    }
}
EOF
            ;;
        *)
            echo "Unknown storage policy: $policy_type"
            return 1
            ;;
    esac
}

# Apply storage policy
apply_storage_policy() {
    local policy="$1"
    local config_file="/tmp/storage_policy.json"
    
    echo "Applying storage policy: $policy"
    
    get_storage_policy "$policy" > "$config_file"
    
    if [[ ! -f "$config_file" ]]; then
        echo "❌ Failed to generate policy configuration"
        return 1
    fi
    
    echo "✅ Storage policy applied successfully"
    echo "Configuration: $config_file"
    
    # Display key policy settings
    echo "=== Policy Summary ==="
    echo "Encryption Required: $(jq -r '.encryption_required' "$config_file")"
    echo "Backup Frequency: $(jq -r '.backup_frequency' "$config_file")"
    echo "Retention Period: $(jq -r '.retention_period' "$config_file")"
    echo "Monitoring Level: $(jq -r '.monitoring_level' "$config_file")"
    echo "Performance Optimization: $(jq -r '.performance_optimization' "$config_file")"
    
    return 0
}

Advanced Disk Operations

Secure Disk Erasure

#!/bin/bash

# Enhanced secure disk erasure with verification
secure_erase_volume() {
    local identifier="$1"
    local security_level="$2"
    local new_name="$3"
    local filesystem_type="${4:-APFS}"
    
    echo "=== Secure Volume Erasure ==="
    echo "Target: $identifier"
    echo "Security Level: $security_level"
    echo "New Name: $new_name"
    echo "Filesystem: $filesystem_type"
    
    # Verify disk exists
    if ! diskutil info "$identifier" &>/dev/null; then
        echo "❌ Error: Disk identifier '$identifier' not found"
        return 1
    fi
    
    # Get disk information before erasure
    local disk_info
    disk_info=$(diskutil info "$identifier")
    echo "Disk Information:"
    echo "$disk_info"
    
    # Confirmation prompt
    echo ""
    echo "⚠️  WARNING: This will permanently erase all data on $identifier"
    echo "Current volume: $(echo "$disk_info" | grep "Volume Name:" | awk -F': ' '{print $2}')"
    echo "Size: $(echo "$disk_info" | grep "Disk Size:" | awk -F': ' '{print $2}')"
    
    read -p "Type 'CONFIRM' to proceed with erasure: " confirmation
    if [[ "$confirmation" != "CONFIRM" ]]; then
        echo "❌ Operation cancelled by user"
        return 1
    fi
    
    # Perform secure erasure based on security level
    case "$security_level" in
        "basic")
            echo "Performing basic erasure..."
            diskutil eraseVolume "$filesystem_type" "$new_name" "$identifier"
            ;;
        "secure")
            echo "Performing secure erasure (DoD 5220.22-M)..."
            diskutil secureErase freespace 3 "$identifier"
            diskutil eraseVolume "$filesystem_type" "$new_name" "$identifier"
            ;;
        "military")
            echo "Performing military-grade erasure (7-pass)..."
            diskutil secureErase freespace 4 "$identifier"
            diskutil eraseVolume "$filesystem_type" "$new_name" "$identifier"
            ;;
        *)
            echo "❌ Unknown security level: $security_level"
            return 1
            ;;
    esac
    
    # Verify erasure completion
    if diskutil info "$identifier" | grep -q "Volume Name.*$new_name"; then
        echo "✅ Secure erasure completed successfully"
        echo "New volume: $new_name"
        echo "Filesystem: $filesystem_type"
        
        # Log the operation
        audit_log "Secure erasure completed: $identifier -> $new_name (Security: $security_level)"
        
        return 0
    else
        echo "❌ Erasure verification failed"
        return 1
    fi
}

# Usage example
# secure_erase_volume "disk2s1" "secure" "CleanVolume" "APFS"

Volume Health Monitoring

#!/bin/bash

# Comprehensive volume health monitoring and assessment
monitor_volume_health() {
    local identifier="$1"
    local health_report="/tmp/volume_health_$(date +%Y%m%d_%H%M%S).json"
    
    echo "=== Volume Health Monitoring ==="
    echo "Target Volume: $identifier"
    
    # Initialize health report
    cat > "$health_report" << EOF
{
    "volume_identifier": "$identifier",
    "scan_timestamp": "$(date -Iseconds)",
    "hostname": "$(hostname)",
    "health_checks": {}
}
EOF
    
    # Volume verification
    echo "Running volume verification..."
    local verify_output
    verify_output=$(diskutil verifyVolume "$identifier" 2>&1)
    local verify_status=$?
    
    # Parse verification results
    local verification_passed=false
    if [[ $verify_status -eq 0 ]] && echo "$verify_output" | grep -q "appears to be OK"; then
        verification_passed=true
    fi
    
    # SMART status check (if supported)
    echo "Checking SMART status..."
    local smart_status="unknown"
    local physical_disk
    physical_disk=$(diskutil info "$identifier" | grep "Part of Whole" | awk '{print $4}')
    
    if [[ -n "$physical_disk" ]]; then
        if smartctl -H "$physical_disk" 2>/dev/null | grep -q "PASSED"; then
            smart_status="passed"
        elif smartctl -H "$physical_disk" 2>/dev/null | grep -q "FAILED"; then
            smart_status="failed"
        fi
    fi
    
    # Disk usage analysis
    echo "Analyzing disk usage..."
    local disk_usage
    disk_usage=$(df -h "$identifier" 2>/dev/null | tail -1)
    local usage_percent
    usage_percent=$(echo "$disk_usage" | awk '{print $5}' | tr -d '%')
    
    # Performance test
    echo "Running performance test..."
    local write_speed read_speed
    local test_file="/Volumes/$(diskutil info "$identifier" | grep "Mount Point" | awk -F': ' '{print $2}' | xargs)/speed_test_$$"
    
    if [[ -w "$(dirname "$test_file")" ]]; then
        # Write test (10MB)
        write_speed=$(dd if=/dev/zero of="$test_file" bs=1m count=10 2>&1 | grep "bytes/sec" | awk '{print $(NF-1)}')
        
        # Read test
        read_speed=$(dd if="$test_file" of=/dev/null bs=1m 2>&1 | grep "bytes/sec" | awk '{print $(NF-1)}')
        
        # Cleanup
        rm -f "$test_file"
    else
        write_speed="not_available"
        read_speed="not_available"
    fi
    
    # Update health report
    jq --argjson verification "$verification_passed" \
       --arg smart_status "$smart_status" \
       --argjson usage_percent "${usage_percent:-0}" \
       --arg write_speed "$write_speed" \
       --arg read_speed "$read_speed" \
       '.health_checks = {
          "filesystem_verification": $verification,
          "smart_status": $smart_status,
          "disk_usage_percent": $usage_percent,
          "write_speed_mbps": $write_speed,
          "read_speed_mbps": $read_speed
        }' "$health_report" > "${health_report}.tmp" && mv "${health_report}.tmp" "$health_report"
    
    # Health assessment
    local health_score=100
    local issues=()
    
    if [[ "$verification_passed" != "true" ]]; then
        ((health_score -= 30))
        issues+=("filesystem_corruption")
    fi
    
    if [[ "$smart_status" == "failed" ]]; then
        ((health_score -= 50))
        issues+=("smart_failure")
    fi
    
    if [[ ${usage_percent:-0} -gt 90 ]]; then
        ((health_score -= 20))
        issues+=("disk_space_critical")
    elif [[ ${usage_percent:-0} -gt 80 ]]; then
        ((health_score -= 10))
        issues+=("disk_space_warning")
    fi
    
    # Add health score and issues to report
    jq --argjson health_score "$health_score" \
       --argjson issues "$(printf '%s\n' "${issues[@]}" | jq -R . | jq -s .)" \
       '.health_assessment = {
          "overall_score": $health_score,
          "issues_detected": $issues,
          "recommendations": []
        }' "$health_report" > "${health_report}.tmp" && mv "${health_report}.tmp" "$health_report"
    
    # Display results
    echo ""
    echo "Health Assessment Results:"
    echo "  Overall Health Score: $health_score/100"
    echo "  Filesystem Verification: $([ "$verification_passed" = "true" ] && echo "✅ PASSED" || echo "❌ FAILED")"
    echo "  SMART Status: $smart_status"
    echo "  Disk Usage: ${usage_percent:-0}%"
    echo "  Write Speed: $write_speed"
    echo "  Read Speed: $read_speed"
    
    if [[ ${#issues[@]} -gt 0 ]]; then
        echo "  Issues Detected:"
        for issue in "${issues[@]}"; do
            echo "    - $issue"
        done
    else
        echo "  ✅ No issues detected"
    fi
    
    echo "  Health Report: $health_report"
    
    # Log health check
    audit_log "Volume health check completed: $identifier (Score: $health_score/100)"
    
    return 0
}

Enterprise Storage Management System

#!/bin/bash

# MacFleet Enterprise Storage Management System
# Comprehensive disk and storage management

# Configuration
CONFIG_DIR="/etc/macfleet/storage"
LOG_FILE="/var/log/macfleet_storage_management.log"
DATA_DIR="/var/data/macfleet/storage"
REPORTS_DIR="/var/reports/macfleet/storage"
AUDIT_LOG="/var/log/macfleet_storage_audit.log"
BACKUP_DIR="/var/backups/macfleet/storage"

# Create required directories
create_directories() {
    local directories=("$CONFIG_DIR" "$DATA_DIR" "$REPORTS_DIR" "$BACKUP_DIR")
    
    for dir in "${directories[@]}"; do
        if [[ ! -d "$dir" ]]; then
            sudo mkdir -p "$dir"
            sudo chmod 755 "$dir"
        fi
    done
}

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

log_error() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') [ERROR] $1" | tee -a "$LOG_FILE" >&2
}

audit_log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') [AUDIT] $1" | tee -a "$AUDIT_LOG"
}

# Storage inventory management
initialize_storage_database() {
    local db_file="$DATA_DIR/storage_inventory.json"
    
    if [[ ! -f "$db_file" ]]; then
        cat > "$db_file" << EOF
{
    "version": "1.0",
    "created": "$(date -Iseconds)",
    "storage_devices": {},
    "volume_configurations": {},
    "health_monitoring": {},
    "performance_metrics": {},
    "security_assessments": {}
}
EOF
        log_action "Storage database initialized: $db_file"
    fi
}

# Comprehensive storage discovery
discover_storage_infrastructure() {
    local discovery_file="$DATA_DIR/storage_discovery_$(date +%Y%m%d_%H%M%S).json"
    
    log_action "Starting comprehensive storage discovery"
    
    echo "=== Storage Infrastructure Discovery ==="
    
    # Physical storage devices
    echo "Discovering physical storage devices..."
    local physical_devices
    physical_devices=$(system_profiler SPStorageDataType -json)
    
    # Logical volumes and partitions
    echo "Analyzing logical volumes..."
    local logical_volumes
    logical_volumes=$(diskutil list -plist | plutil -convert json -o -)
    
    # APFS containers and volumes
    echo "Examining APFS containers..."
    local apfs_containers
    apfs_containers=$(diskutil apfs list -plist | plutil -convert json -o -)
    
    # Network mounted volumes
    echo "Checking network volumes..."
    local network_volumes
    network_volumes=$(mount | grep -E "(nfs|smb|afp)" | jq -R . | jq -s .)
    
    # External devices
    echo "Detecting external devices..."
    local external_devices
    external_devices=$(diskutil list external -plist | plutil -convert json -o -)
    
    # Encryption status
    echo "Assessing encryption status..."
    local encryption_status=()
    while IFS= read -r volume; do
        if [[ -n "$volume" ]]; then
            local encrypted="false"
            if diskutil info "$volume" | grep -q "FileVault.*Yes"; then
                encrypted="true"
            fi
            encryption_status+=("{\"volume\": \"$volume\", \"encrypted\": $encrypted}")
        fi
    done <<< "$(diskutil list | grep -E "^\s+[0-9]+:" | awk '{print $NF}')"
    
    # Generate comprehensive discovery report
    cat > "$discovery_file" << EOF
{
    "discovery_timestamp": "$(date -Iseconds)",
    "hostname": "$(hostname)",
    "physical_storage": $physical_devices,
    "logical_volumes": $logical_volumes,
    "apfs_containers": $apfs_containers,
    "network_volumes": $network_volumes,
    "external_devices": $external_devices,
    "encryption_status": [$(IFS=,; echo "${encryption_status[*]}")],
    "system_info": {
        "os_version": "$(sw_vers -productVersion)",
        "total_storage": "$(df -h / | tail -1 | awk '{print $2}')",
        "available_storage": "$(df -h / | tail -1 | awk '{print $4}')"
    }
}
EOF
    
    log_action "Storage discovery completed: $discovery_file"
    
    # Display summary
    echo ""
    echo "Discovery Summary:"
    echo "  Physical Devices: $(echo "$physical_devices" | jq '.SPStorageDataType | length' 2>/dev/null || echo "0")"
    echo "  Logical Volumes: $(echo "$logical_volumes" | jq '.AllDisks | length' 2>/dev/null || echo "0")"
    echo "  APFS Containers: $(echo "$apfs_containers" | jq '.Containers | length' 2>/dev/null || echo "0")"
    echo "  Network Volumes: $(echo "$network_volumes" | jq '. | length' 2>/dev/null || echo "0")"
    echo "  External Devices: $(echo "$external_devices" | jq '.AllDisks | length' 2>/dev/null || echo "0")"
    echo "  Discovery Report: $discovery_file"
    
    return 0
}

# Automated storage optimization
optimize_storage_performance() {
    local optimization_profile="$1"
    local optimization_report="$REPORTS_DIR/storage_optimization_$(date +%Y%m%d_%H%M%S).json"
    
    log_action "Starting storage optimization (Profile: $optimization_profile)"
    
    echo "=== Storage Performance Optimization ==="
    echo "Optimization Profile: $optimization_profile"
    
    # Initialize optimization report
    cat > "$optimization_report" << EOF
{
    "optimization_profile": "$optimization_profile",
    "start_timestamp": "$(date -Iseconds)",
    "hostname": "$(hostname)",
    "optimizations_performed": [],
    "performance_improvements": {},
    "recommendations": []
}
EOF
    
    local optimizations_performed=()
    
    case "$optimization_profile" in
        "performance")
            echo "Applying performance optimizations..."
            
            # Enable TRIM for SSDs
            if sudo trimforce enable 2>/dev/null; then
                optimizations_performed+=("trim_enabled")
                echo "  ✅ TRIM enabled for SSD optimization"
            fi
            
            # Optimize APFS
            for container in $(diskutil apfs list | grep "Container" | awk '{print $2}'); do
                if diskutil apfs defragment "$container" 2>/dev/null; then
                    optimizations_performed+=("apfs_defragment_$container")
                    echo "  ✅ APFS container $container defragmented"
                fi
            done
            
            # Clear system caches
            sudo purge
            optimizations_performed+=("system_cache_cleared")
            echo "  ✅ System caches cleared"
            ;;
            
        "security")
            echo "Applying security optimizations..."
            
            # Enable FileVault if not already enabled
            if ! fdesetup status | grep -q "FileVault is On"; then
                echo "  ⚠️  FileVault not enabled - recommend enabling for security"
                optimizations_performed+=("filevault_recommendation")
            else
                echo "  ✅ FileVault already enabled"
            fi
            
            # Secure delete free space
            for volume in $(df | grep "^/dev" | awk '{print $1}'); do
                if diskutil secureErase freespace 1 "$volume" 2>/dev/null; then
                    optimizations_performed+=("secure_delete_$volume")
                    echo "  ✅ Secure delete performed on $volume"
                fi
            done
            ;;
            
        "storage_cleanup")
            echo "Performing storage cleanup..."
            
            # Clean system logs
            local log_space_before
            log_space_before=$(du -sh /var/log 2>/dev/null | awk '{print $1}')
            
            sudo log erase --all 2>/dev/null
            optimizations_performed+=("system_logs_cleaned")
            
            # Clean user caches
            local cache_space_before
            cache_space_before=$(du -sh ~/Library/Caches 2>/dev/null | awk '{print $1}')
            
            find ~/Library/Caches -type f -atime +30 -delete 2>/dev/null
            optimizations_performed+=("user_caches_cleaned")
            
            # Clean downloads folder
            find ~/Downloads -type f -atime +90 -delete 2>/dev/null
            optimizations_performed+=("downloads_cleaned")
            
            echo "  ✅ System cleanup completed"
            ;;
            
        *)
            echo "❌ Unknown optimization profile: $optimization_profile"
            return 1
            ;;
    esac
    
    # Update optimization report
    jq --argjson optimizations "$(printf '%s\n' "${optimizations_performed[@]}" | jq -R . | jq -s .)" \
       '.optimizations_performed = $optimizations | .end_timestamp = "'"$(date -Iseconds)"'"' \
       "$optimization_report" > "${optimization_report}.tmp" && mv "${optimization_report}.tmp" "$optimization_report"
    
    echo ""
    echo "Optimization Results:"
    echo "  Profile: $optimization_profile"
    echo "  Optimizations Performed: ${#optimizations_performed[@]}"
    echo "  Report: $optimization_report"
    
    audit_log "Storage optimization completed: $optimization_profile (${#optimizations_performed[@]} optimizations)"
    
    return 0
}

# Bulk volume operations
bulk_volume_operations() {
    local operation="$1"
    local volume_list="$2"
    local operation_report="$REPORTS_DIR/bulk_operations_$(date +%Y%m%d_%H%M%S).json"
    
    log_action "Starting bulk volume operations: $operation"
    
    if [[ ! -f "$volume_list" ]]; then
        log_error "Volume list file not found: $volume_list"
        return 1
    fi
    
    echo "=== Bulk Volume Operations ==="
    echo "Operation: $operation"
    echo "Volume List: $volume_list"
    
    # Initialize operation report
    cat > "$operation_report" << EOF
{
    "operation_type": "$operation",
    "start_timestamp": "$(date -Iseconds)",
    "hostname": "$(hostname)",
    "total_volumes": 0,
    "successful_operations": 0,
    "failed_operations": 0,
    "operation_details": []
}
EOF
    
    local total_volumes=0
    local successful_operations=0
    local failed_operations=0
    
    # Process each volume in the list
    while IFS= read -r volume_entry; do
        if [[ -n "$volume_entry" && ! "$volume_entry" =~ ^# ]]; then
            ((total_volumes++))
            
            # Parse volume entry (format: identifier|name|filesystem)
            IFS='|' read -r identifier name filesystem <<< "$volume_entry"
            
            echo "Processing volume: $identifier"
            
            local operation_success=false
            local operation_message=""
            
            case "$operation" in
                "verify")
                    if diskutil verifyVolume "$identifier" &>/dev/null; then
                        operation_success=true
                        operation_message="Volume verification passed"
                        ((successful_operations++))
                    else
                        operation_message="Volume verification failed"
                        ((failed_operations++))
                    fi
                    ;;
                    
                "repair")
                    if diskutil repairVolume "$identifier" &>/dev/null; then
                        operation_success=true
                        operation_message="Volume repair completed"
                        ((successful_operations++))
                    else
                        operation_message="Volume repair failed"
                        ((failed_operations++))
                    fi
                    ;;
                    
                "mount")
                    if diskutil mount "$identifier" &>/dev/null; then
                        operation_success=true
                        operation_message="Volume mounted successfully"
                        ((successful_operations++))
                    else
                        operation_message="Volume mount failed"
                        ((failed_operations++))
                    fi
                    ;;
                    
                "unmount")
                    if diskutil unmount "$identifier" &>/dev/null; then
                        operation_success=true
                        operation_message="Volume unmounted successfully"
                        ((successful_operations++))
                    else
                        operation_message="Volume unmount failed"
                        ((failed_operations++))
                    fi
                    ;;
                    
                *)
                    operation_message="Unknown operation: $operation"
                    ((failed_operations++))
                    ;;
            esac
            
            echo "  Result: $([ "$operation_success" = "true" ] && echo "✅ SUCCESS" || echo "❌ FAILED") - $operation_message"
            
            # Add to operation report
            local operation_detail=$(cat << EOF
{
    "identifier": "$identifier",
    "name": "$name",
    "filesystem": "$filesystem",
    "success": $operation_success,
    "message": "$operation_message",
    "timestamp": "$(date -Iseconds)"
}
EOF
)
            
            jq --argjson detail "$operation_detail" \
               '.operation_details += [$detail]' \
               "$operation_report" > "${operation_report}.tmp" && mv "${operation_report}.tmp" "$operation_report"
        fi
    done < "$volume_list"
    
    # Update final statistics
    jq --argjson total "$total_volumes" \
       --argjson successful "$successful_operations" \
       --argjson failed "$failed_operations" \
       '.total_volumes = $total | .successful_operations = $successful | .failed_operations = $failed | .end_timestamp = "'"$(date -Iseconds)"'"' \
       "$operation_report" > "${operation_report}.tmp" && mv "${operation_report}.tmp" "$operation_report"
    
    echo ""
    echo "Bulk Operation Summary:"
    echo "  Total Volumes: $total_volumes"
    echo "  Successful: $successful_operations"
    echo "  Failed: $failed_operations"
    echo "  Success Rate: $(( successful_operations * 100 / total_volumes ))%"
    echo "  Operation Report: $operation_report"
    
    log_action "Bulk volume operations completed: $operation ($successful_operations/$total_volumes successful)"
    
    return 0
}

# Fleet-wide storage management
deploy_storage_management() {
    local fleet_config="$1"
    local storage_policy="$2"
    
    log_action "Starting fleet-wide storage management deployment"
    
    if [[ ! -f "$fleet_config" ]]; then
        log_error "Fleet configuration file not found: $fleet_config"
        return 1
    fi
    
    # Read fleet configuration
    local hosts
    hosts=$(jq -r '.hosts[]' "$fleet_config")
    
    echo "Deploying storage management to fleet..."
    echo "Storage Policy: $storage_policy"
    
    # Deploy to each host
    while IFS= read -r host; do
        if [[ -n "$host" ]]; then
            echo "Deploying to: $host"
            
            # Copy storage management script to remote host
            scp "$0" "root@${host}:/tmp/macfleet_storage.sh" || {
                log_error "Failed to copy script to $host"
                continue
            }
            
            # Apply storage policy on remote host
            ssh "root@${host}" "chmod +x /tmp/macfleet_storage.sh && /tmp/macfleet_storage.sh apply_policy '$storage_policy' &" || {
                log_error "Failed to apply storage policy on $host"
                continue
            }
            
            log_action "✅ Storage management deployed on: $host"
        fi
    done <<< "$hosts"
    
    log_action "Fleet storage deployment completed"
}

# Generate comprehensive storage reports
generate_storage_report() {
    local report_type="$1"
    local report_name="${2:-storage_report_$(date +%Y%m%d_%H%M%S)}"
    local report_file="$REPORTS_DIR/${report_name}.json"
    
    log_action "Generating storage report: $report_name (Type: $report_type)"
    
    case "$report_type" in
        "inventory")
            generate_storage_inventory_report "$report_file"
            ;;
        "health_assessment")
            generate_health_assessment_report "$report_file"
            ;;
        "performance_analysis")
            generate_performance_analysis_report "$report_file"
            ;;
        "security_audit")
            generate_security_audit_report "$report_file"
            ;;
        "compliance")
            generate_compliance_report "$report_file"
            ;;
        *)
            log_error "Unknown report type: $report_type"
            return 1
            ;;
    esac
    
    log_action "✅ Storage report generated: $report_file"
    echo "Report saved to: $report_file"
}

# Main function with command routing
main() {
    local command="$1"
    shift
    
    # Initialize
    create_directories
    initialize_storage_database
    
    case "$command" in
        "list")
            # Enhanced disk listing
            get_comprehensive_disk_info
            ;;
        "health_check")
            monitor_volume_health "$@"
            ;;
        "secure_erase")
            secure_erase_volume "$@"
            ;;
        "discover")
            discover_storage_infrastructure
            ;;
        "optimize")
            optimize_storage_performance "$@"
            ;;
        "bulk_operations")
            bulk_volume_operations "$@"
            ;;
        "apply_policy")
            apply_storage_policy "$@"
            ;;
        "fleet_deploy")
            deploy_storage_management "$@"
            ;;
        "generate_report")
            generate_storage_report "$@"
            ;;
        "show_categories")
            print_storage_categories
            ;;
        "show_policies")
            for policy in enterprise_standard high_security_financial creative_workflow development_environment compliance_strict performance_optimized cost_efficient; do
                echo "Policy: $policy"
                get_storage_policy "$policy" | jq .
                echo ""
            done
            ;;
        *)
            echo "MacFleet Enterprise Storage Management System"
            echo "Usage: $0 <command> [options]"
            echo ""
            echo "Commands:"
            echo "  list                                       - Enhanced disk listing and analysis"
            echo "  health_check <identifier>                 - Comprehensive volume health monitoring"
            echo "  secure_erase <identifier> <level> <name>  - Secure volume erasure"
            echo "  discover                                   - Storage infrastructure discovery"
            echo "  optimize <profile>                        - Storage performance optimization"
            echo "  bulk_operations <operation> <volume_list> - Bulk volume operations"
            echo "  apply_policy <policy>                     - Apply storage management policy"
            echo "  fleet_deploy <fleet_config> <policy>     - Deploy to fleet"
            echo "  generate_report <type> [name]             - Generate storage reports"
            echo "  show_categories                           - Show storage categories"
            echo "  show_policies                             - Show storage policies"
            echo ""
            echo "Examples:"
            echo "  $0 list"
            echo "  $0 health_check disk1s1"
            echo "  $0 secure_erase disk2s1 secure CleanDisk"
            echo "  $0 optimize performance"
            echo "  $0 generate_report inventory"
            ;;
    esac
}

# Execute main function with all arguments
main "$@"

Fleet Deployment Configuration

Fleet Configuration Example

{
    "fleet_name": "MacFleet Enterprise Storage",
    "deployment_date": "2025-07-07",
    "hosts": [
        "mac-workstation-01.company.com",
        "mac-server-01.company.com",
        "mac-dev-01.company.com"
    ],
    "storage_policies": {
        "default": "enterprise_standard",
        "secure_hosts": "high_security_financial",
        "creative_hosts": "creative_workflow"
    },
    "monitoring_schedule": {
        "health_checks": "daily",
        "performance_monitoring": "weekly",
        "security_audits": "monthly"
    }
}

Volume List Example for Bulk Operations

# Volume List for Bulk Operations
# Format: identifier|name|filesystem
disk1s1|Macintosh HD|APFS
disk2s1|Data Volume|APFS
disk3s1|Backup Drive|APFS
disk4s1|External Storage|ExFAT

Security Considerations

Storage Security

  • Encryption Enforcement - Ensure all sensitive volumes are encrypted with FileVault
  • Secure Erasure - Multiple security levels for proper data destruction
  • Access Controls - Monitor and control access to storage resources
  • Integrity Monitoring - Continuous verification of storage integrity
  • Threat Detection - Scan for unauthorized access and suspicious activities

Compliance Framework

  • Data Retention - Automated enforcement of data retention policies
  • Audit Trails - Comprehensive logging of all storage operations
  • Encryption Standards - Compliance with AES-256 and other encryption requirements
  • Backup Verification - Automated verification of backup integrity
  • Disaster Recovery - Storage-focused disaster recovery procedures

Performance Optimization

Storage Performance

  • SSD Optimization - TRIM enablement and wear leveling optimization
  • APFS Optimization - Container defragmentation and snapshot management
  • Cache Management - Intelligent caching and memory optimization
  • I/O Monitoring - Real-time monitoring of storage I/O performance
  • Bottleneck Detection - Automated detection and resolution of performance issues

Troubleshooting Guide

Common Issues

Disk Verification Failures

  • Run First Aid from Disk Utility
  • Boot from Recovery Mode for system volume repairs
  • Check for hardware issues with Apple Diagnostics

Performance Degradation

  • Monitor SMART status for drive health
  • Check for fragmentation on older filesystems
  • Verify adequate free space (maintain 10-15% free)

Mount/Unmount Issues

  • Check for processes using the volume: lsof /Volumes/VolumeName
  • Force unmount if necessary: diskutil unmount force /dev/diskXsY
  • Verify filesystem integrity before remounting

Diagnostic Commands

# Check disk health
diskutil verifyVolume disk1s1

# Monitor disk I/O
iostat -d 1

# Check filesystem usage
df -h

# View SMART status
smartctl -a /dev/disk0

Important Notes

  • Data Safety - Always backup critical data before performing disk operations
  • Administrative Privileges - Most disk operations require sudo/administrator access
  • Testing - Test all scripts on non-production systems before fleet deployment
  • Recovery Planning - Maintain bootable recovery drives and backup strategies
  • Monitoring - Implement continuous monitoring for early problem detection
  • Documentation - Keep detailed records of all storage configurations and changes