Tutorial

New updates and improvements to Macfleet.

Manage Bluetooth Menu on Status Bar in macOS

Managing the visibility of system menus in the status bar is essential for maintaining a consistent user experience across your Mac fleet. This tutorial shows you how to control the Bluetooth menu display on macOS devices using shell scripts.

Why Manage Bluetooth Menu Visibility

Controlling the Bluetooth menu visibility helps with:

  • Consistent user experience: Standardize interface elements across all devices
  • Quick access management: Provide users with convenient Bluetooth controls
  • Support efficiency: Reduce support tickets by ensuring easy access to Bluetooth settings
  • Enterprise compliance: Maintain consistent UI standards across the organization
  • User productivity: Enable quick Bluetooth connection management

Understanding Control Center Configuration

macOS uses the Control Center preference system to manage status bar items. The Bluetooth menu is controlled through the com.apple.controlcenter.plist file with these key values:

  • Value 18: Show Bluetooth menu in status bar
  • Value 0: Hide Bluetooth menu from status bar

Basic Bluetooth Menu Management

Show Bluetooth Menu in Status Bar

#!/bin/bash

# Script to show Bluetooth menu on status bar
CurrentUser=$(ls -l /dev/console | awk '/ / { print $3 }')
CurrentUserUID=$(id -u "$CurrentUser")

launchctl asuser $CurrentUserUID sudo -iu "$CurrentUser" defaults -currentHost write com.apple.controlcenter.plist Bluetooth -int 18

echo "Bluetooth menu enabled on status bar for user: $CurrentUser"

Hide Bluetooth Menu from Status Bar

#!/bin/bash

# Script to hide Bluetooth menu from status bar
CurrentUser=$(ls -l /dev/console | awk '/ / { print $3 }')
CurrentUserUID=$(id -u "$CurrentUser")

launchctl asuser $CurrentUserUID sudo -iu "$CurrentUser" defaults -currentHost write com.apple.controlcenter.plist Bluetooth -int 0

echo "Bluetooth menu hidden from status bar for user: $CurrentUser"

Enhanced Bluetooth Menu Management

Comprehensive Bluetooth Status Script

#!/bin/bash

# Enhanced Bluetooth menu management with validation
DEVICE_NAME=$(scutil --get ComputerName)
CURRENT_USER=$(ls -l /dev/console | awk '/ / { print $3 }')
CURRENT_USER_UID=$(id -u "$CURRENT_USER")
LOG_FILE="/var/log/macfleet_bluetooth_menu.log"

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

# Function to get current Bluetooth menu status
get_bluetooth_status() {
    local status=$(launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults -currentHost read com.apple.controlcenter.plist Bluetooth 2>/dev/null)
    echo "$status"
}

# Function to show Bluetooth menu
show_bluetooth_menu() {
    launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults -currentHost write com.apple.controlcenter.plist Bluetooth -int 18
    log_message "Bluetooth menu enabled on $DEVICE_NAME for user $CURRENT_USER"
}

# Function to hide Bluetooth menu
hide_bluetooth_menu() {
    launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults -currentHost write com.apple.controlcenter.plist Bluetooth -int 0
    log_message "Bluetooth menu hidden on $DEVICE_NAME for user $CURRENT_USER"
}

# Function to validate current state
validate_bluetooth_state() {
    local current_status=$(get_bluetooth_status)
    log_message "Current Bluetooth menu status: $current_status"
    
    if [ "$current_status" = "18" ]; then
        echo "✅ Bluetooth menu is currently visible in status bar"
    elif [ "$current_status" = "0" ]; then
        echo "❌ Bluetooth menu is currently hidden from status bar"
    else
        echo "⚠️  Bluetooth menu status is undefined or not set"
    fi
}

# Main execution
log_message "Starting Bluetooth menu management on $DEVICE_NAME"

# Check current status
validate_bluetooth_state

# Example: Show Bluetooth menu (uncomment to use)
# show_bluetooth_menu

# Example: Hide Bluetooth menu (uncomment to use)
# hide_bluetooth_menu

# Verify change
validate_bluetooth_state
log_message "Bluetooth menu management completed"

Interactive Bluetooth Menu Manager

#!/bin/bash

# Interactive Bluetooth menu manager
CURRENT_USER=$(ls -l /dev/console | awk '/ / { print $3 }')
CURRENT_USER_UID=$(id -u "$CURRENT_USER")

# Function to get current status
get_current_status() {
    local status=$(launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults -currentHost read com.apple.controlcenter.plist Bluetooth 2>/dev/null)
    case "$status" in
        18) echo "visible" ;;
        0) echo "hidden" ;;
        *) echo "undefined" ;;
    esac
}

# Function to toggle Bluetooth menu
toggle_bluetooth_menu() {
    local current_status=$(get_current_status)
    
    if [ "$current_status" = "visible" ]; then
        launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults -currentHost write com.apple.controlcenter.plist Bluetooth -int 0
        echo "Bluetooth menu has been hidden from status bar"
    else
        launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults -currentHost write com.apple.controlcenter.plist Bluetooth -int 18
        echo "Bluetooth menu has been shown in status bar"
    fi
}

# Display current status
echo "MacFleet Bluetooth Menu Manager"
echo "==============================="
echo "Device: $(scutil --get ComputerName)"
echo "User: $CURRENT_USER"
echo "Current Bluetooth menu status: $(get_current_status)"
echo ""

# Provide options
echo "Options:"
echo "1. Show Bluetooth menu"
echo "2. Hide Bluetooth menu"
echo "3. Toggle Bluetooth menu"
echo "4. Check current status"
echo ""

read -p "Enter your choice (1-4): " choice

case $choice in
    1)
        launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults -currentHost write com.apple.controlcenter.plist Bluetooth -int 18
        echo "✅ Bluetooth menu is now visible in status bar"
        ;;
    2)
        launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults -currentHost write com.apple.controlcenter.plist Bluetooth -int 0
        echo "❌ Bluetooth menu is now hidden from status bar"
        ;;
    3)
        toggle_bluetooth_menu
        ;;
    4)
        echo "Current status: $(get_current_status)"
        ;;
    *)
        echo "Invalid choice. Please run the script again."
        ;;
esac

Advanced Control Center Management

Comprehensive Control Center Configuration

#!/bin/bash

# Comprehensive Control Center menu management
CURRENT_USER=$(ls -l /dev/console | awk '/ / { print $3 }')
CURRENT_USER_UID=$(id -u "$CURRENT_USER")

# Define Control Center menu items and their values
declare -A control_center_items=(
    ["Bluetooth"]="18"
    ["WiFi"]="18"
    ["AirDrop"]="18"
    ["Focus"]="18"
    ["StageManager"]="18"
    ["Display"]="18"
    ["Sound"]="18"
    ["NowPlaying"]="18"
    ["ScreenMirroring"]="18"
    ["Battery"]="18"
    ["Clock"]="18"
    ["UserSwitcher"]="18"
)

# Function to configure Control Center item
configure_control_center_item() {
    local item="$1"
    local value="$2"
    local action="$3"
    
    launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults -currentHost write com.apple.controlcenter.plist "$item" -int "$value"
    
    if [ "$value" = "18" ]; then
        echo "✅ $item: Enabled in status bar"
    else
        echo "❌ $item: Disabled in status bar"
    fi
}

# Function to show all Control Center items
show_all_items() {
    echo "Enabling all Control Center items..."
    for item in "${!control_center_items[@]}"; do
        configure_control_center_item "$item" "18"
    done
}

# Function to hide all Control Center items
hide_all_items() {
    echo "Disabling all Control Center items..."
    for item in "${!control_center_items[@]}"; do
        configure_control_center_item "$item" "0"
    done
}

# Function to show current status of all items
show_current_status() {
    echo "Current Control Center Status:"
    echo "=============================="
    
    for item in "${!control_center_items[@]}"; do
        local current_value=$(launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" defaults -currentHost read com.apple.controlcenter.plist "$item" 2>/dev/null)
        
        case "$current_value" in
            18) echo "✅ $item: Visible" ;;
            0) echo "❌ $item: Hidden" ;;
            *) echo "⚠️  $item: Not configured" ;;
        esac
    done
}

# Function to configure essential items only
configure_essential_items() {
    echo "Configuring essential Control Center items..."
    
    # Essential items for most users
    essential_items=("Bluetooth" "WiFi" "Sound" "Battery" "Clock")
    
    # Hide all items first
    hide_all_items
    
    # Show only essential items
    for item in "${essential_items[@]}"; do
        configure_control_center_item "$item" "18"
    done
}

# Main menu
echo "MacFleet Control Center Manager"
echo "==============================="
echo "Device: $(scutil --get ComputerName)"
echo "User: $CURRENT_USER"
echo ""

show_current_status

echo ""
echo "Management Options:"
echo "1. Show all Control Center items"
echo "2. Hide all Control Center items"
echo "3. Show essential items only"
echo "4. Show only Bluetooth menu"
echo "5. Hide only Bluetooth menu"
echo "6. Check current status"
echo ""

read -p "Enter your choice (1-6): " choice

case $choice in
    1) show_all_items ;;
    2) hide_all_items ;;
    3) configure_essential_items ;;
    4) configure_control_center_item "Bluetooth" "18" ;;
    5) configure_control_center_item "Bluetooth" "0" ;;
    6) show_current_status ;;
    *) echo "Invalid choice. Please run the script again." ;;
esac

echo ""
echo "Configuration completed. Changes may require logout/login to take full effect."

Enterprise Deployment Scripts

Bulk Bluetooth Menu Configuration

#!/bin/bash

# Bulk Bluetooth menu configuration for enterprise deployment
COMPANY_NAME="MacFleet"
DEPLOYMENT_DATE=$(date +"%Y-%m-%d")
LOG_FILE="/var/log/macfleet_bluetooth_deployment.log"
REPORT_FILE="/tmp/bluetooth_deployment_report_$(date +%Y%m%d_%H%M%S).txt"

# Configuration settings
BLUETOOTH_ENABLED=true  # Set to false to disable
FORCE_RESTART_CONTROL_CENTER=true

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

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

# Function to configure Bluetooth menu
configure_bluetooth_menu() {
    local enable_bluetooth="$1"
    local current_user=$(ls -l /dev/console | awk '/ / { print $3 }')
    local current_user_uid=$(id -u "$current_user")
    
    if [ "$enable_bluetooth" = true ]; then
        launchctl asuser $current_user_uid sudo -iu "$current_user" defaults -currentHost write com.apple.controlcenter.plist Bluetooth -int 18
        log_message "Bluetooth menu enabled for user $current_user"
        echo "✅ Bluetooth menu enabled"
    else
        launchctl asuser $current_user_uid sudo -iu "$current_user" defaults -currentHost write com.apple.controlcenter.plist Bluetooth -int 0
        log_message "Bluetooth menu disabled for user $current_user"
        echo "❌ Bluetooth menu disabled"
    fi
}

# Function to restart Control Center
restart_control_center() {
    local current_user=$(ls -l /dev/console | awk '/ / { print $3 }')
    local current_user_uid=$(id -u "$current_user")
    
    # Kill Control Center process to force reload
    launchctl asuser $current_user_uid sudo -iu "$current_user" killall ControlCenter 2>/dev/null
    log_message "Control Center restarted for user $current_user"
}

# Function to validate deployment
validate_deployment() {
    local current_user=$(ls -l /dev/console | awk '/ / { print $3 }')
    local current_user_uid=$(id -u "$current_user")
    local bluetooth_status=$(launchctl asuser $current_user_uid sudo -iu "$current_user" defaults -currentHost read com.apple.controlcenter.plist Bluetooth 2>/dev/null)
    
    if [ "$BLUETOOTH_ENABLED" = true ] && [ "$bluetooth_status" = "18" ]; then
        echo "✅ Deployment successful - Bluetooth menu is visible"
        log_message "Deployment validation successful"
        return 0
    elif [ "$BLUETOOTH_ENABLED" = false ] && [ "$bluetooth_status" = "0" ]; then
        echo "✅ Deployment successful - Bluetooth menu is hidden"
        log_message "Deployment validation successful"
        return 0
    else
        echo "❌ Deployment validation failed"
        log_message "Deployment validation failed - Expected: $BLUETOOTH_ENABLED, Got: $bluetooth_status"
        return 1
    fi
}

# Main deployment process
echo "$COMPANY_NAME Bluetooth Menu Deployment" > "$REPORT_FILE"
echo "=========================================" >> "$REPORT_FILE"
echo "Date: $DEPLOYMENT_DATE" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"

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

log_message "Starting Bluetooth menu deployment"
echo "Starting deployment..." >> "$REPORT_FILE"

# Configure Bluetooth menu
configure_bluetooth_menu $BLUETOOTH_ENABLED

# Restart Control Center if requested
if [ "$FORCE_RESTART_CONTROL_CENTER" = true ]; then
    restart_control_center
    sleep 2
fi

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

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

Remote Bluetooth Menu Management

#!/bin/bash

# Remote Bluetooth menu management with JSON reporting
CENTRAL_SERVER="your-macfleet-server.com"
DEVICE_ID=$(system_profiler SPHardwareDataType | grep "Serial Number" | awk '{print $4}')
REPORT_FILE="/tmp/bluetooth_menu_report_${DEVICE_ID}.json"

# Function to create JSON report
create_json_report() {
    local device_name=$(scutil --get ComputerName)
    local device_user=$(ls -l /dev/console | awk '/ / { print $3 }')
    local device_user_uid=$(id -u "$device_user")
    local os_version=$(sw_vers -productVersion)
    local timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
    
    # Get current Bluetooth menu status
    local bluetooth_status=$(launchctl asuser $device_user_uid sudo -iu "$device_user" defaults -currentHost read com.apple.controlcenter.plist Bluetooth 2>/dev/null)
    
    cat > "$REPORT_FILE" << EOF
{
  "device_info": {
    "device_id": "$DEVICE_ID",
    "device_name": "$device_name",
    "user": "$device_user",
    "os_version": "$os_version",
    "timestamp": "$timestamp"
  },
  "bluetooth_menu": {
    "status": "$bluetooth_status",
    "visible": $([ "$bluetooth_status" = "18" ] && echo "true" || echo "false"),
    "configured": $([ -n "$bluetooth_status" ] && echo "true" || echo "false")
  },
  "control_center": {
    "items": {
EOF

    # Check other Control Center items
    local items=("WiFi" "AirDrop" "Focus" "Display" "Sound" "NowPlaying" "Battery" "Clock")
    local first_item=true
    
    for item in "${items[@]}"; do
        local item_status=$(launchctl asuser $device_user_uid sudo -iu "$device_user" defaults -currentHost read com.apple.controlcenter.plist "$item" 2>/dev/null)
        
        if [ "$first_item" = false ]; then
            echo "," >> "$REPORT_FILE"
        fi
        
        echo "      \"$item\": {" >> "$REPORT_FILE"
        echo "        \"status\": \"$item_status\"," >> "$REPORT_FILE"
        echo "        \"visible\": $([ "$item_status" = "18" ] && echo "true" || echo "false")" >> "$REPORT_FILE"
        echo "      }" >> "$REPORT_FILE"
        
        first_item=false
    done
    
    echo "" >> "$REPORT_FILE"
    echo "    }" >> "$REPORT_FILE"
    echo "  }" >> "$REPORT_FILE"
    echo "}" >> "$REPORT_FILE"
}

# Function to apply configuration from server
apply_server_config() {
    local config_url="https://$CENTRAL_SERVER/api/device-config/$DEVICE_ID"
    
    # Download configuration (example)
    # curl -s "$config_url" -o "/tmp/device_config.json"
    
    # For demonstration, we'll use a local example
    echo "Applying server configuration..."
    
    # Example: Enable Bluetooth menu
    local current_user=$(ls -l /dev/console | awk '/ / { print $3 }')
    local current_user_uid=$(id -u "$current_user")
    
    launchctl asuser $current_user_uid sudo -iu "$current_user" defaults -currentHost write com.apple.controlcenter.plist Bluetooth -int 18
    
    echo "Server configuration applied successfully"
}

# Main execution
echo "MacFleet Remote Bluetooth Menu Management"
echo "========================================"
echo "Device ID: $DEVICE_ID"

# Create initial report
create_json_report

# Display current status
echo "Current Bluetooth menu status: $(grep -o '"visible": [^,]*' "$REPORT_FILE" | head -1 | cut -d' ' -f2)"

# Apply server configuration if needed
# apply_server_config

# Create final report
create_json_report

echo "Report generated: $REPORT_FILE"
echo "Device reporting completed"

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

Best Practices for Status Bar Management

1. User Experience Considerations

  • Maintain consistent status bar layouts across all devices
  • Provide essential tools while avoiding clutter
  • Consider user workflow requirements

2. Deployment Strategy

  • Test configuration changes on a small group first
  • Document standard configurations for different user types
  • Provide rollback procedures

3. Change Management

  • Notify users of interface changes in advance
  • Provide training materials for new configurations
  • Monitor support requests after changes

4. Monitoring and Maintenance

  • Regular audits of status bar configurations
  • Automated compliance checking
  • User feedback collection

Troubleshooting Common Issues

Issue: Changes Not Taking Effect

# Force Control Center restart
killall ControlCenter
sleep 2

# Check if preferences are properly written
defaults -currentHost read com.apple.controlcenter.plist Bluetooth

Issue: Permission Denied

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

# Check user permissions
id "$current_user"

Issue: macOS Version Compatibility

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

# For macOS 12.0 and below, use different preference location
if [[ "$macos_version" < "12.0" ]]; then
    echo "Using legacy preferences location"
    # Use different defaults domain for older versions
fi

Issue: Preferences Not Persisting

# Force preferences synchronization
defaults -currentHost synchronize

# Check if preferences file exists
ls -la ~/Library/Preferences/ByHost/com.apple.controlcenter.*

Conclusion

Managing Bluetooth menu visibility in the status bar is a simple but effective way to standardize the user experience across your Mac fleet. These scripts provide:

  • Consistent interface: Standardized status bar layouts
  • Remote management: Centralized control over UI elements
  • User productivity: Quick access to essential controls
  • Enterprise compliance: Maintaining organizational standards

Regular implementation of these status bar management practices will help ensure a consistent and productive user experience across your entire Mac fleet.

For more advanced Control Center management, consider integrating these scripts with your existing device management and configuration tools.

Bluetooth Management on macOS

Control and manage Bluetooth settings across your MacFleet devices using advanced command-line tools. This tutorial covers Bluetooth status monitoring, power state management, and enterprise-grade fleet control with comprehensive logging and security features.

Understanding macOS Bluetooth Management

macOS provides comprehensive Bluetooth control through several mechanisms:

  • defaults - Direct manipulation of Bluetooth preferences via plist files
  • bluetoothd - The core Bluetooth daemon that handles all Bluetooth operations
  • launchctl - Service management for starting/stopping Bluetooth services
  • blued - Legacy Bluetooth daemon name used in older macOS versions

The primary configuration file is located at /Library/Preferences/com.apple.Bluetooth with the ControllerPowerState key controlling the power state.

Basic Bluetooth Status Management

Check Bluetooth Status

#!/bin/bash

# Check current Bluetooth power state
check_bluetooth_status() {
    local status
    status=$(defaults read /Library/Preferences/com.apple.Bluetooth ControllerPowerState 2>/dev/null)
    
    if [[ "$status" == "1" ]]; then
        echo "Bluetooth is ON"
        return 0
    elif [[ "$status" == "0" ]]; then
        echo "Bluetooth is OFF"
        return 1
    else
        echo "Bluetooth status unknown or not configured"
        return 2
    fi
}

# Execute status check
check_bluetooth_status

Turn Bluetooth ON

#!/bin/bash

# Turn Bluetooth ON using defaults and daemon restart
turn_bluetooth_on() {
    echo "Turning Bluetooth ON..."
    
    # Set Bluetooth power state to ON
    sudo defaults write /Library/Preferences/com.apple.Bluetooth ControllerPowerState -int 1
    
    # Restart Bluetooth daemon (try both modern and legacy daemon names)
    if pgrep bluetoothd >/dev/null 2>&1; then
        sudo killall -HUP bluetoothd
        echo "Bluetooth daemon (bluetoothd) restarted"
    elif pgrep blued >/dev/null 2>&1; then
        sudo killall -HUP blued
        echo "Bluetooth daemon (blued) restarted"
    else
        echo "Warning: Bluetooth daemon not found"
    fi
    
    # Wait for changes to take effect
    sleep 3
    
    # Verify the change
    if check_bluetooth_status >/dev/null; then
        echo "✅ Bluetooth successfully turned ON"
        return 0
    else
        echo "❌ Failed to turn Bluetooth ON"
        return 1
    fi
}

# Helper function for status checking
check_bluetooth_status() {
    local status
    status=$(defaults read /Library/Preferences/com.apple.Bluetooth ControllerPowerState 2>/dev/null)
    [[ "$status" == "1" ]]
}

# Execute
turn_bluetooth_on

Turn Bluetooth OFF

#!/bin/bash

# Turn Bluetooth OFF using defaults and daemon restart
turn_bluetooth_off() {
    echo "Turning Bluetooth OFF..."
    
    # Set Bluetooth power state to OFF
    sudo defaults write /Library/Preferences/com.apple.Bluetooth ControllerPowerState -int 0
    
    # Restart Bluetooth daemon
    if pgrep bluetoothd >/dev/null 2>&1; then
        sudo killall -HUP bluetoothd
        echo "Bluetooth daemon (bluetoothd) restarted"
    elif pgrep blued >/dev/null 2>&1; then
        sudo killall -HUP blued
        echo "Bluetooth daemon (blued) restarted"
    else
        echo "Warning: Bluetooth daemon not found"
    fi
    
    # Wait for changes to take effect
    sleep 3
    
    # Verify the change
    if ! check_bluetooth_status >/dev/null; then
        echo "✅ Bluetooth successfully turned OFF"
        return 0
    else
        echo "❌ Failed to turn Bluetooth OFF"
        return 1
    fi
}

# Helper function for status checking
check_bluetooth_status() {
    local status
    status=$(defaults read /Library/Preferences/com.apple.Bluetooth ControllerPowerState 2>/dev/null)
    [[ "$status" == "1" ]]
}

# Execute
turn_bluetooth_off

Advanced Bluetooth Management with launchctl

Using launchctl for Service Management

#!/bin/bash

# Advanced Bluetooth control using launchctl service management
bluetooth_service_control() {
    local action="$1"  # on, off, restart, status
    local daemon_name
    
    # Determine the correct daemon name based on macOS version
    if launchctl list | grep -q "com.apple.bluetoothd"; then
        daemon_name="com.apple.bluetoothd"
    elif launchctl list | grep -q "com.apple.blued"; then
        daemon_name="com.apple.blued"
    else
        echo "❌ Bluetooth daemon not found in launchctl"
        return 1
    fi
    
    case "$action" in
        "on")
            echo "Enabling Bluetooth..."
            sudo defaults write /Library/Preferences/com.apple.Bluetooth ControllerPowerState -int 1
            sudo launchctl stop "$daemon_name"
            sleep 2
            sudo launchctl start "$daemon_name"
            sleep 3
            echo "✅ Bluetooth enabled using launchctl"
            ;;
        "off")
            echo "Disabling Bluetooth..."
            sudo defaults write /Library/Preferences/com.apple.Bluetooth ControllerPowerState -int 0
            sudo launchctl stop "$daemon_name"
            sleep 2
            sudo launchctl start "$daemon_name"
            sleep 3
            echo "✅ Bluetooth disabled using launchctl"
            ;;
        "restart")
            echo "Restarting Bluetooth service..."
            sudo launchctl stop "$daemon_name"
            sleep 2
            sudo launchctl start "$daemon_name"
            sleep 3
            echo "✅ Bluetooth service restarted"
            ;;
        "status")
            echo "Bluetooth daemon status: $daemon_name"
            if launchctl list | grep -q "$daemon_name"; then
                echo "✅ Bluetooth service is running"
                
                # Check power state
                local power_state
                power_state=$(defaults read /Library/Preferences/com.apple.Bluetooth ControllerPowerState 2>/dev/null)
                echo "Power state: $([[ "$power_state" == "1" ]] && echo "ON" || echo "OFF")"
            else
                echo "❌ Bluetooth service is not running"
            fi
            ;;
        *)
            echo "Usage: bluetooth_service_control {on|off|restart|status}"
            return 1
            ;;
    esac
}

# Examples
bluetooth_service_control "status"
# bluetooth_service_control "on"
# bluetooth_service_control "off"
# bluetooth_service_control "restart"

Enterprise Bluetooth Management System

#!/bin/bash

# MacFleet Enterprise Bluetooth Management System
# Comprehensive Bluetooth control with logging, monitoring, and fleet management

# Configuration
LOG_FILE="/var/log/macfleet_bluetooth.log"
CONFIG_FILE="/etc/macfleet/bluetooth_config.conf"
BACKUP_DIR="/var/backups/macfleet/bluetooth"
API_ENDPOINT="https://api.macfleet.com/v1/bluetooth"

# Create directory structure
setup_directories() {
    mkdir -p "$(dirname "$LOG_FILE")" "$BACKUP_DIR" "$(dirname "$CONFIG_FILE")"
    touch "$LOG_FILE"
}

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

# Get detailed Bluetooth information
get_bluetooth_info() {
    local info_json="{"
    
    # Power state
    local power_state
    power_state=$(defaults read /Library/Preferences/com.apple.Bluetooth ControllerPowerState 2>/dev/null || echo "unknown")
    info_json+="\"power_state\": \"$power_state\","
    
    # Daemon status
    local daemon_running=false
    if pgrep bluetoothd >/dev/null 2>&1 || pgrep blued >/dev/null 2>&1; then
        daemon_running=true
    fi
    info_json+="\"daemon_running\": $daemon_running,"
    
    # macOS version
    local macos_version
    macos_version=$(sw_vers -productVersion)
    info_json+="\"macos_version\": \"$macos_version\","
    
    # System hardware
    local hardware_model
    hardware_model=$(system_profiler SPHardwareDataType | grep "Model Name" | awk -F': ' '{print $2}' | xargs)
    info_json+="\"hardware_model\": \"$hardware_model\","
    
    # Bluetooth controller info
    local bt_controller=""
    if system_profiler SPBluetoothDataType >/dev/null 2>&1; then
        bt_controller=$(system_profiler SPBluetoothDataType | grep -A5 "Apple Bluetooth Software" | grep "Version" | awk -F': ' '{print $2}' | xargs)
    fi
    info_json+="\"bluetooth_version\": \"$bt_controller\","
    
    # Timestamp
    info_json+="\"timestamp\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\""
    info_json+="}"
    
    echo "$info_json"
}

# Backup current Bluetooth configuration
backup_bluetooth_config() {
    local backup_file="$BACKUP_DIR/bluetooth_backup_$(date +%Y%m%d_%H%M%S).plist"
    
    if [[ -f "/Library/Preferences/com.apple.Bluetooth.plist" ]]; then
        cp "/Library/Preferences/com.apple.Bluetooth.plist" "$backup_file"
        log_action "Bluetooth configuration backed up to: $backup_file"
        echo "$backup_file"
    else
        log_action "WARNING: Bluetooth preference file not found for backup"
        return 1
    fi
}

# Set Bluetooth state with comprehensive validation
set_bluetooth_state() {
    local desired_state="$1"  # "on" or "off"
    local force_restart="${2:-false}"
    
    # Validate input
    if [[ "$desired_state" != "on" && "$desired_state" != "off" ]]; then
        log_action "ERROR: Invalid state specified. Use 'on' or 'off'"
        return 1
    fi
    
    # Get current state
    local current_state
    current_state=$(defaults read /Library/Preferences/com.apple.Bluetooth ControllerPowerState 2>/dev/null)
    
    local target_value
    if [[ "$desired_state" == "on" ]]; then
        target_value=1
    else
        target_value=0
    fi
    
    # Check if change is needed
    if [[ "$current_state" == "$target_value" && "$force_restart" == "false" ]]; then
        log_action "Bluetooth already in desired state: $desired_state"
        return 0
    fi
    
    # Create backup before changes
    backup_bluetooth_config
    
    # Set new state
    log_action "Setting Bluetooth state to: $desired_state"
    sudo defaults write /Library/Preferences/com.apple.Bluetooth ControllerPowerState -int "$target_value"
    
    # Restart Bluetooth daemon
    restart_bluetooth_daemon
    
    # Wait for changes to propagate
    sleep 5
    
    # Verify the change
    local new_state
    new_state=$(defaults read /Library/Preferences/com.apple.Bluetooth ControllerPowerState 2>/dev/null)
    
    if [[ "$new_state" == "$target_value" ]]; then
        log_action "✅ Bluetooth successfully set to: $desired_state"
        return 0
    else
        log_action "❌ Failed to set Bluetooth to: $desired_state"
        return 1
    fi
}

# Restart Bluetooth daemon with error handling
restart_bluetooth_daemon() {
    log_action "Restarting Bluetooth daemon..."
    
    # Try modern bluetoothd first
    if pgrep bluetoothd >/dev/null 2>&1; then
        if sudo killall -HUP bluetoothd 2>/dev/null; then
            log_action "Bluetooth daemon (bluetoothd) restarted successfully"
            return 0
        else
            log_action "WARNING: Failed to restart bluetoothd with HUP signal"
        fi
    fi
    
    # Try legacy blued
    if pgrep blued >/dev/null 2>&1; then
        if sudo killall -HUP blued 2>/dev/null; then
            log_action "Bluetooth daemon (blued) restarted successfully"
            return 0
        else
            log_action "WARNING: Failed to restart blued with HUP signal"
        fi
    fi
    
    # Try launchctl approach
    local daemon_service=""
    if launchctl list | grep -q "com.apple.bluetoothd"; then
        daemon_service="com.apple.bluetoothd"
    elif launchctl list | grep -q "com.apple.blued"; then
        daemon_service="com.apple.blued"
    fi
    
    if [[ -n "$daemon_service" ]]; then
        log_action "Attempting launchctl restart for: $daemon_service"
        sudo launchctl stop "$daemon_service" 2>/dev/null
        sleep 2
        sudo launchctl start "$daemon_service" 2>/dev/null
        log_action "Bluetooth service restarted via launchctl"
        return 0
    fi
    
    log_action "ERROR: Could not restart Bluetooth daemon"
    return 1
}

# Monitor Bluetooth connectivity and paired devices
monitor_bluetooth_devices() {
    log_action "Starting Bluetooth device monitoring..."
    
    # Get current power state
    local power_state
    power_state=$(defaults read /Library/Preferences/com.apple.Bluetooth ControllerPowerState 2>/dev/null)
    
    if [[ "$power_state" != "1" ]]; then
        log_action "Bluetooth is OFF - no devices to monitor"
        return 0
    fi
    
    # Check for system_profiler availability
    if ! command -v system_profiler >/dev/null 2>&1; then
        log_action "WARNING: system_profiler not available for device monitoring"
        return 1
    fi
    
    # Get Bluetooth device information
    local bt_devices
    bt_devices=$(system_profiler SPBluetoothDataType 2>/dev/null | grep -A10 "Devices:" || echo "No devices found")
    
    log_action "Bluetooth devices status:"
    echo "$bt_devices" | while IFS= read -r line; do
        log_action "  $line"
    done
    
    # Count connected devices
    local connected_count
    connected_count=$(echo "$bt_devices" | grep -c "Connected: Yes" || echo "0")
    log_action "Total connected Bluetooth devices: $connected_count"
    
    return 0
}

# Generate comprehensive Bluetooth report
generate_bluetooth_report() {
    local report_file="/tmp/bluetooth_report_$(date +%Y%m%d_%H%M%S).json"
    
    log_action "Generating Bluetooth report: $report_file"
    
    {
        echo "{"
        echo "  \"report_type\": \"bluetooth_status\","
        echo "  \"timestamp\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\","
        echo "  \"hostname\": \"$(hostname)\","
        echo "  \"device_info\": $(get_bluetooth_info),"
        
        # System information
        echo "  \"system_info\": {"
        echo "    \"macos_version\": \"$(sw_vers -productVersion)\","
        echo "    \"build_version\": \"$(sw_vers -buildVersion)\","
        echo "    \"hardware_uuid\": \"$(system_profiler SPHardwareDataType | grep 'Hardware UUID' | awk -F': ' '{print $2}' | xargs)\""
        echo "  },"
        
        # Bluetooth preferences
        echo "  \"bluetooth_preferences\": {"
        if [[ -f "/Library/Preferences/com.apple.Bluetooth.plist" ]]; then
            echo "    \"preferences_file_exists\": true,"
            echo "    \"file_size\": $(stat -f%z "/Library/Preferences/com.apple.Bluetooth.plist"),"
            echo "    \"last_modified\": \"$(stat -f%Sm -t%Y-%m-%dT%H:%M:%SZ "/Library/Preferences/com.apple.Bluetooth.plist")\""
        else
            echo "    \"preferences_file_exists\": false"
        fi
        echo "  }"
        echo "}"
    } > "$report_file"
    
    log_action "Bluetooth report generated successfully"
    echo "$report_file"
}

# Security compliance check
check_bluetooth_security() {
    log_action "Performing Bluetooth security compliance check..."
    
    local security_issues=()
    
    # Check if Bluetooth is enabled when it should be disabled
    if [[ -f "$CONFIG_FILE" ]] && grep -q "BLUETOOTH_POLICY=disabled" "$CONFIG_FILE"; then
        local current_state
        current_state=$(defaults read /Library/Preferences/com.apple.Bluetooth ControllerPowerState 2>/dev/null)
        
        if [[ "$current_state" == "1" ]]; then
            security_issues+=("Bluetooth enabled despite policy requiring disabled state")
        fi
    fi
    
    # Check for Bluetooth discoverability (if system_profiler available)
    if command -v system_profiler >/dev/null 2>&1; then
        local discoverable
        discoverable=$(system_profiler SPBluetoothDataType 2>/dev/null | grep -i "discoverable" || echo "unknown")
        
        if echo "$discoverable" | grep -qi "yes"; then
            security_issues+=("Bluetooth is discoverable - potential security risk")
        fi
    fi
    
    # Report security status
    if [[ ${#security_issues[@]} -eq 0 ]]; then
        log_action "✅ Bluetooth security compliance check passed"
        return 0
    else
        log_action "⚠️  Bluetooth security issues found:"
        for issue in "${security_issues[@]}"; do
            log_action "  - $issue"
        done
        return 1
    fi
}

# Main management function
main() {
    local action="${1:-status}"
    local parameter="$2"
    
    setup_directories
    log_action "MacFleet Bluetooth Management started with action: $action"
    
    case "$action" in
        "on"|"enable")
            set_bluetooth_state "on"
            ;;
        "off"|"disable")
            set_bluetooth_state "off"
            ;;
        "restart"|"reload")
            restart_bluetooth_daemon
            ;;
        "status"|"info")
            get_bluetooth_info | python3 -m json.tool 2>/dev/null || get_bluetooth_info
            ;;
        "monitor")
            monitor_bluetooth_devices
            ;;
        "report")
            generate_bluetooth_report
            ;;
        "security")
            check_bluetooth_security
            ;;
        "backup")
            backup_bluetooth_config
            ;;
        "force-on")
            set_bluetooth_state "on" true
            ;;
        "force-off")
            set_bluetooth_state "off" true
            ;;
        *)
            echo "Usage: $0 {on|off|restart|status|monitor|report|security|backup|force-on|force-off}"
            echo ""
            echo "Commands:"
            echo "  on/enable    - Turn Bluetooth ON"
            echo "  off/disable  - Turn Bluetooth OFF"
            echo "  restart      - Restart Bluetooth daemon"
            echo "  status       - Show detailed Bluetooth status"
            echo "  monitor      - Monitor connected devices"
            echo "  report       - Generate comprehensive report"
            echo "  security     - Run security compliance check"
            echo "  backup       - Backup current configuration"
            echo "  force-on     - Force Bluetooth ON (restart daemon)"
            echo "  force-off    - Force Bluetooth OFF (restart daemon)"
            exit 1
            ;;
    esac
    
    log_action "MacFleet Bluetooth Management completed with action: $action"
}

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

Quick Management Functions

Simple Status Check

#!/bin/bash

# Quick Bluetooth status check with color output
bluetooth_quick_status() {
    local status
    status=$(defaults read /Library/Preferences/com.apple.Bluetooth ControllerPowerState 2>/dev/null)
    
    case "$status" in
        "1")
            echo "🔵 Bluetooth: ON"
            ;;
        "0")
            echo "⚪ Bluetooth: OFF"
            ;;
        *)
            echo "❓ Bluetooth: UNKNOWN"
            ;;
    esac
}

bluetooth_quick_status

Toggle Bluetooth State

#!/bin/bash

# Toggle Bluetooth between ON and OFF states
toggle_bluetooth() {
    local current_state
    current_state=$(defaults read /Library/Preferences/com.apple.Bluetooth ControllerPowerState 2>/dev/null)
    
    if [[ "$current_state" == "1" ]]; then
        echo "Bluetooth is ON, turning OFF..."
        sudo defaults write /Library/Preferences/com.apple.Bluetooth ControllerPowerState -int 0
        sudo killall -HUP bluetoothd 2>/dev/null || sudo killall -HUP blued 2>/dev/null
        echo "✅ Bluetooth turned OFF"
    else
        echo "Bluetooth is OFF, turning ON..."
        sudo defaults write /Library/Preferences/com.apple.Bluetooth ControllerPowerState -int 1
        sudo killall -HUP bluetoothd 2>/dev/null || sudo killall -HUP blued 2>/dev/null
        echo "✅ Bluetooth turned ON"
    fi
}

toggle_bluetooth

Configuration Templates

Bluetooth Policy Configuration

# /etc/macfleet/bluetooth_config.conf
# MacFleet Bluetooth Management Configuration

# Policy settings
BLUETOOTH_POLICY="enabled"  # enabled, disabled, user_controlled
AUTO_DISABLE_ON_IDLE="false"
IDLE_TIMEOUT_MINUTES="30"

# Security settings
ALLOW_DISCOVERABLE="false"
REQUIRE_PAIRING_CONFIRMATION="true"
LOG_DEVICE_CONNECTIONS="true"

# Monitoring settings
MONITOR_INTERVAL_SECONDS="300"
ALERT_ON_NEW_DEVICES="true"
COMPLIANCE_CHECK_ENABLED="true"

# Backup settings
AUTO_BACKUP_ENABLED="true"
BACKUP_RETENTION_DAYS="30"

Troubleshooting Common Issues

Bluetooth Daemon Not Responding

#!/bin/bash

# Troubleshoot and fix Bluetooth daemon issues
fix_bluetooth_daemon() {
    echo "Diagnosing Bluetooth daemon issues..."
    
    # Check if daemon is running
    if ! pgrep bluetoothd >/dev/null 2>&1 && ! pgrep blued >/dev/null 2>&1; then
        echo "❌ No Bluetooth daemon found running"
        
        # Try to start via launchctl
        if launchctl list | grep -q "com.apple.bluetoothd"; then
            echo "Starting bluetoothd via launchctl..."
            sudo launchctl start com.apple.bluetoothd
        elif launchctl list | grep -q "com.apple.blued"; then
            echo "Starting blued via launchctl..."
            sudo launchctl start com.apple.blued
        else
            echo "❌ Bluetooth service not found in launchctl"
            return 1
        fi
    fi
    
    # Force restart if still having issues
    echo "Force restarting Bluetooth system..."
    sudo pkill -f bluetooth
    sleep 3
    
    # Restart via launchctl
    for service in "com.apple.bluetoothd" "com.apple.blued"; do
        if launchctl list | grep -q "$service"; then
            sudo launchctl stop "$service" 2>/dev/null
            sleep 2
            sudo launchctl start "$service" 2>/dev/null
            echo "Restarted service: $service"
        fi
    done
    
    # Verify recovery
    sleep 5
    if pgrep bluetoothd >/dev/null 2>&1 || pgrep blued >/dev/null 2>&1; then
        echo "✅ Bluetooth daemon recovery successful"
        return 0
    else
        echo "❌ Bluetooth daemon recovery failed"
        return 1
    fi
}

fix_bluetooth_daemon

Reset Bluetooth Configuration

#!/bin/bash

# Reset Bluetooth to factory defaults
reset_bluetooth_config() {
    echo "⚠️  Resetting Bluetooth configuration to defaults..."
    
    # Create backup
    if [[ -f "/Library/Preferences/com.apple.Bluetooth.plist" ]]; then
        cp "/Library/Preferences/com.apple.Bluetooth.plist" "/tmp/bluetooth_backup_$(date +%s).plist"
        echo "Backup created in /tmp/"
    fi
    
    # Stop Bluetooth services
    sudo launchctl stop com.apple.bluetoothd 2>/dev/null
    sudo launchctl stop com.apple.blued 2>/dev/null
    
    # Remove configuration files
    sudo rm -f "/Library/Preferences/com.apple.Bluetooth.plist"
    sudo rm -f "/Library/Preferences/ByHost/com.apple.Bluetooth.*.plist"
    
    # Restart services
    sudo launchctl start com.apple.bluetoothd 2>/dev/null
    sudo launchctl start com.apple.blued 2>/dev/null
    
    # Set default state
    sleep 3
    sudo defaults write /Library/Preferences/com.apple.Bluetooth ControllerPowerState -int 1
    sudo killall -HUP bluetoothd 2>/dev/null || sudo killall -HUP blued 2>/dev/null
    
    echo "✅ Bluetooth configuration reset completed"
}

# Uncomment to execute
# reset_bluetooth_config

Important Technical Notes

Daemon Management

  • bluetoothd: Modern Bluetooth daemon (macOS 10.10+)
  • blued: Legacy Bluetooth daemon (older macOS versions)
  • killall -HUP: Sends hangup signal to restart daemon gracefully
  • launchctl: Preferred method for service management

Configuration Details

  • File Location: /Library/Preferences/com.apple.Bluetooth
  • Power State Key: ControllerPowerState
  • Values: 1 (ON), 0 (OFF)
  • Persistence: Changes persist across reboots

Security Considerations

  1. Administrative Privileges: All Bluetooth modifications require sudo
  2. Daemon Restart: Changes only take effect after daemon restart
  3. User Impact: Turning off Bluetooth disconnects all paired devices
  4. Policy Compliance: Monitor for unauthorized Bluetooth changes

Best Practices

  1. Always backup configurations before making changes
  2. Test daemon restart methods for your macOS version
  3. Monitor for delays - daemon restart can take several seconds
  4. Implement logging for audit trails and troubleshooting
  5. Use launchctl for more reliable service management
  6. Validate changes after applying modifications
  7. Consider user impact when disabling Bluetooth remotely
  8. Test scripts thoroughly before fleet deployment

Remember to validate all scripts on test devices before deploying across your MacFleet environment, and be aware that Bluetooth changes may take a few minutes to fully propagate through the system.

Battery Management on macOS

Monitor and manage battery health, performance, and lifecycle across your MacFleet devices using advanced battery monitoring tools and enterprise battery management systems. This tutorial covers battery health monitoring, power optimization, compliance tracking, and enterprise battery lifecycle management.

Understanding macOS Battery Management

macOS provides several command-line tools for battery management and monitoring:

  • pmset - Power management settings and battery status monitoring
  • system_profiler - Comprehensive system and battery information
  • ioreg - I/O Registry information including battery details
  • Battery Health Management - macOS built-in battery optimization
  • Low Power Mode - System-level power conservation

Basic Battery Operations

View Battery Status

#!/bin/bash

# Basic battery status
pmset -g batt

echo "Battery status retrieved successfully"

Enhanced Battery Information

#!/bin/bash

# Comprehensive battery information with detailed analysis
get_comprehensive_battery_info() {
    echo "=== Comprehensive Battery Analysis ==="
    
    # Basic battery status
    echo "Battery Status Overview:"
    pmset -g batt
    
    echo -e "\nDetailed Battery Health:"
    system_profiler SPPowerDataType
    
    echo -e "\nPower Management Settings:"
    pmset -g
    
    echo -e "\nBattery Registry Information:"
    ioreg -n AppleSmartBattery -r
    
    echo -e "\nThermal State:"
    pmset -g therm
    
    echo -e "\nPower Source Details:"
    pmset -g ps
}

# Execute comprehensive analysis
get_comprehensive_battery_info

Battery Management Categories

Battery Device Classifications

#!/bin/bash

# Enterprise battery management categories for monitoring and policy enforcement
declare -A BATTERY_DEVICE_CATEGORIES=(
    ["executive_mobile"]="Executive MacBooks requiring maximum uptime and reliability"
    ["creative_workstation"]="High-performance MacBooks for creative professionals with intensive usage"
    ["developer_laptop"]="Development MacBooks with consistent high CPU usage and long sessions"
    ["field_service"]="Field service MacBooks requiring extended battery life and durability"
    ["education_fleet"]="Educational MacBooks with shared usage patterns and budget constraints"
    ["conference_room"]="Meeting room MacBooks for presentations and video conferencing"
    ["backup_devices"]="Backup and loaner devices with infrequent usage patterns"
    ["legacy_systems"]="Older MacBooks requiring specialized battery management"
    ["testing_lab"]="Testing and QA devices with variable usage patterns"
    ["kiosk_display"]="Kiosk MacBooks with continuous operation requirements"
)

# Battery health thresholds
declare -A HEALTH_THRESHOLDS=(
    ["executive_mobile"]="excellent:90,good:80,warning:70,critical:60"
    ["creative_workstation"]="excellent:85,good:75,warning:65,critical:55"
    ["developer_laptop"]="excellent:85,good:75,warning:65,critical:55"
    ["field_service"]="excellent:95,good:85,warning:75,critical:65"
    ["education_fleet"]="excellent:80,good:70,warning:60,critical:50"
    ["conference_room"]="excellent:85,good:75,warning:65,critical:55"
    ["backup_devices"]="excellent:75,good:65,warning:55,critical:45"
    ["legacy_systems"]="excellent:70,good:60,warning:50,critical:40"
    ["testing_lab"]="excellent:80,good:70,warning:60,critical:50"
    ["kiosk_display"]="excellent:90,good:80,warning:70,critical:60"
)

# Usage pattern classifications
declare -A USAGE_PATTERNS=(
    ["executive_mobile"]="intensive_daily"
    ["creative_workstation"]="heavy_continuous"
    ["developer_laptop"]="consistent_high"
    ["field_service"]="extended_mobile"
    ["education_fleet"]="shared_moderate"
    ["conference_room"]="intermittent_plugged"
    ["backup_devices"]="minimal_occasional"
    ["legacy_systems"]="light_maintenance"
    ["testing_lab"]="variable_testing"
    ["kiosk_display"]="continuous_plugged"
)

print_battery_categories() {
    echo "=== Battery Management Categories ==="
    for category in "${!BATTERY_DEVICE_CATEGORIES[@]}"; do
        echo "Category: $category"
        echo "  Description: ${BATTERY_DEVICE_CATEGORIES[$category]}"
        echo "  Health Thresholds: ${HEALTH_THRESHOLDS[$category]}"
        echo "  Usage Pattern: ${USAGE_PATTERNS[$category]}"
        echo ""
    done
}

# Display available categories
print_battery_categories

Battery Management Policies

Power Management Policy Engine

#!/bin/bash

# Battery management policies for different organizational requirements
declare -A BATTERY_POLICIES=(
    ["maximum_performance"]="Performance-first policy with minimal power restrictions"
    ["balanced_efficiency"]="Balanced performance and battery life optimization"
    ["extended_battery_life"]="Maximum battery life with performance optimization"
    ["enterprise_standard"]="Standard enterprise battery management with monitoring"
    ["high_security_mobile"]="Security-focused mobile battery management"
    ["creative_professional"]="Optimized for creative workflows with high power demands"
    ["field_operations"]="Extended operation for field service and remote work"
    ["compliance_strict"]="Strict compliance with battery health and lifecycle tracking"
)

# Policy configurations
get_battery_policy() {
    local policy_type="$1"
    
    case "$policy_type" in
        "maximum_performance")
            cat << EOF
{
    "power_mode": "high_performance",
    "battery_health_management": false,
    "low_power_mode_threshold": 5,
    "sleep_settings": {
        "display_sleep": 30,
        "system_sleep": 60,
        "disk_sleep": 10
    },
    "processor_performance": "maximum",
    "graphics_switching": "high_performance_gpu",
    "background_app_refresh": true,
    "location_services": "full",
    "notification_optimization": false,
    "thermal_management": "performance_first",
    "charging_optimization": false,
    "battery_monitoring": "basic",
    "compliance_tracking": false,
    "lifecycle_management": false
}
EOF
            ;;
        "extended_battery_life")
            cat << EOF
{
    "power_mode": "low_power_extended",
    "battery_health_management": true,
    "low_power_mode_threshold": 20,
    "sleep_settings": {
        "display_sleep": 5,
        "system_sleep": 10,
        "disk_sleep": 5
    },
    "processor_performance": "efficient",
    "graphics_switching": "integrated_gpu_only",
    "background_app_refresh": false,
    "location_services": "essential_only",
    "notification_optimization": true,
    "thermal_management": "battery_first",
    "charging_optimization": true,
    "optimized_charging": true,
    "battery_monitoring": "comprehensive",
    "compliance_tracking": true,
    "lifecycle_management": true,
    "usage_analytics": true
}
EOF
            ;;
        "enterprise_standard")
            cat << EOF
{
    "power_mode": "balanced",
    "battery_health_management": true,
    "low_power_mode_threshold": 15,
    "sleep_settings": {
        "display_sleep": 15,
        "system_sleep": 30,
        "disk_sleep": 10
    },
    "processor_performance": "balanced",
    "graphics_switching": "automatic",
    "background_app_refresh": true,
    "location_services": "standard",
    "notification_optimization": true,
    "thermal_management": "balanced",
    "charging_optimization": true,
    "optimized_charging": true,
    "battery_monitoring": "enterprise",
    "compliance_tracking": true,
    "lifecycle_management": true,
    "usage_analytics": true,
    "health_alerting": true,
    "fleet_reporting": true,
    "maintenance_scheduling": true
}
EOF
            ;;
        "field_operations")
            cat << EOF
{
    "power_mode": "extended_field",
    "battery_health_management": true,
    "low_power_mode_threshold": 25,
    "sleep_settings": {
        "display_sleep": 3,
        "system_sleep": 5,
        "disk_sleep": 3
    },
    "processor_performance": "efficient_high",
    "graphics_switching": "integrated_preferred",
    "background_app_refresh": "selective",
    "location_services": "gps_optimized",
    "notification_optimization": true,
    "thermal_management": "conservative",
    "charging_optimization": true,
    "optimized_charging": true,
    "battery_monitoring": "field_focused",
    "compliance_tracking": true,
    "lifecycle_management": true,
    "usage_analytics": true,
    "field_reporting": true,
    "emergency_mode": true,
    "offline_capability": true
}
EOF
            ;;
        *)
            echo "Unknown battery policy: $policy_type"
            return 1
            ;;
    esac
}

# Apply battery policy
apply_battery_policy() {
    local policy="$1"
    local config_file="/tmp/battery_policy.json"
    
    echo "Applying battery policy: $policy"
    
    get_battery_policy "$policy" > "$config_file"
    
    if [[ ! -f "$config_file" ]]; then
        echo "❌ Failed to generate policy configuration"
        return 1
    fi
    
    echo "✅ Battery policy applied successfully"
    echo "Configuration: $config_file"
    
    # Display key policy settings
    echo "=== Policy Summary ==="
    echo "Power Mode: $(jq -r '.power_mode' "$config_file")"
    echo "Battery Health Management: $(jq -r '.battery_health_management' "$config_file")"
    echo "Low Power Threshold: $(jq -r '.low_power_mode_threshold' "$config_file")%"
    echo "Processor Performance: $(jq -r '.processor_performance' "$config_file")"
    echo "Charging Optimization: $(jq -r '.charging_optimization' "$config_file")"
    
    # Apply actual power management settings
    apply_power_settings "$config_file"
    
    return 0
}

# Apply power management settings
apply_power_settings() {
    local config_file="$1"
    
    echo "Applying power management settings..."
    
    # Extract settings from JSON
    local display_sleep
    display_sleep=$(jq -r '.sleep_settings.display_sleep' "$config_file")
    local system_sleep
    system_sleep=$(jq -r '.sleep_settings.system_sleep' "$config_file")
    local disk_sleep
    disk_sleep=$(jq -r '.sleep_settings.disk_sleep' "$config_file")
    
    # Apply sleep settings
    sudo pmset -c displaysleep "$display_sleep" || echo "Warning: Could not set display sleep"
    sudo pmset -c sleep "$system_sleep" || echo "Warning: Could not set system sleep"
    sudo pmset -c disksleep "$disk_sleep" || echo "Warning: Could not set disk sleep"
    
    # Apply battery-specific settings
    sudo pmset -b displaysleep $((display_sleep / 2)) || echo "Warning: Could not set battery display sleep"
    sudo pmset -b sleep $((system_sleep / 2)) || echo "Warning: Could not set battery system sleep"
    
    echo "✅ Power settings applied successfully"
}

Advanced Battery Monitoring

Battery Health Analytics

#!/bin/bash

# Comprehensive battery health monitoring and analytics
monitor_battery_health() {
    local device_category="$1"
    local monitoring_profile="${2:-standard}"
    local health_report="/tmp/battery_health_$(date +%Y%m%d_%H%M%S).json"
    
    echo "=== Battery Health Monitoring ==="
    echo "Device Category: $device_category"
    echo "Monitoring Profile: $monitoring_profile"
    
    # Initialize health report
    cat > "$health_report" << EOF
{
    "device_category": "$device_category",
    "monitoring_profile": "$monitoring_profile",
    "scan_timestamp": "$(date -Iseconds)",
    "hostname": "$(hostname)",
    "battery_analysis": {}
}
EOF
    
    # Extract battery information
    echo "Collecting battery data..."
    local battery_info
    battery_info=$(system_profiler SPPowerDataType)
    
    # Parse key battery metrics
    local cycle_count
    cycle_count=$(echo "$battery_info" | grep "Cycle Count:" | awk -F': ' '{print $2}' | tr -d ' ')
    
    local condition
    condition=$(echo "$battery_info" | grep "Condition:" | awk -F': ' '{print $2}' | tr -d ' ')
    
    local max_capacity
    max_capacity=$(echo "$battery_info" | grep "Maximum Capacity:" | awk -F': ' '{print $2}' | tr -d ' %')
    
    local state_of_charge
    state_of_charge=$(echo "$battery_info" | grep "State of Charge" | awk -F': ' '{print $2}' | tr -d ' %')
    
    local charging_status
    charging_status=$(pmset -g batt | grep -o "charging\|discharging\|charged" | head -1)
    
    local time_remaining
    time_remaining=$(pmset -g batt | grep -o "[0-9][0-9]*:[0-9][0-9]* remaining" | awk '{print $1}')
    
    local power_source
    power_source=$(pmset -g batt | grep "Now drawing from" | awk -F"'" '{print $2}')
    
    # Advanced battery analytics
    echo "Performing advanced analytics..."
    
    # Calculate battery health score
    local health_score=100
    
    # Cycle count impact
    if [[ $cycle_count -gt 1000 ]]; then
        ((health_score -= 20))
    elif [[ $cycle_count -gt 500 ]]; then
        ((health_score -= 10))
    fi
    
    # Capacity impact
    if [[ $max_capacity -lt 80 ]]; then
        ((health_score -= 25))
    elif [[ $max_capacity -lt 90 ]]; then
        ((health_score -= 15))
    fi
    
    # Condition impact
    if [[ "$condition" == "Service Recommended" ]]; then
        ((health_score -= 30))
    elif [[ "$condition" == "Replace Soon" ]]; then
        ((health_score -= 50))
    elif [[ "$condition" == "Replace Now" ]]; then
        ((health_score -= 70))
    fi
    
    # Determine health status
    local health_status="excellent"
    if [[ $health_score -lt 60 ]]; then
        health_status="critical"
    elif [[ $health_score -lt 70 ]]; then
        health_status="poor"
    elif [[ $health_score -lt 80 ]]; then
        health_status="warning"
    elif [[ $health_score -lt 90 ]]; then
        health_status="good"
    fi
    
    # Temperature monitoring
    local temperature_celsius="unknown"
    if command -v powermetrics &>/dev/null; then
        temperature_celsius=$(sudo powermetrics -n 1 -s battery | grep "Temperature:" | awk '{print $2}' | tr -d '°C' 2>/dev/null || echo "unknown")
    fi
    
    # Update health report with collected data
    jq --argjson cycle_count "${cycle_count:-0}" \
       --arg condition "$condition" \
       --argjson max_capacity "${max_capacity:-0}" \
       --argjson state_of_charge "${state_of_charge:-0}" \
       --arg charging_status "$charging_status" \
       --arg time_remaining "$time_remaining" \
       --arg power_source "$power_source" \
       --argjson health_score "$health_score" \
       --arg health_status "$health_status" \
       --arg temperature "$temperature_celsius" \
       '.battery_analysis = {
          "cycle_count": $cycle_count,
          "condition": $condition,
          "maximum_capacity_percent": $max_capacity,
          "current_charge_percent": $state_of_charge,
          "charging_status": $charging_status,
          "time_remaining": $time_remaining,
          "power_source": $power_source,
          "health_score": $health_score,
          "health_status": $health_status,
          "temperature_celsius": $temperature
        }' "$health_report" > "${health_report}.tmp" && mv "${health_report}.tmp" "$health_report"
    
    # Generate recommendations
    local recommendations=()
    
    if [[ $cycle_count -gt 800 ]]; then
        recommendations+=("Consider battery replacement planning")
    fi
    
    if [[ $max_capacity -lt 85 ]]; then
        recommendations+=("Monitor battery capacity degradation")
    fi
    
    if [[ "$condition" != "Normal" ]]; then
        recommendations+=("Schedule battery service appointment")
    fi
    
    if [[ $state_of_charge -lt 20 && "$charging_status" == "discharging" ]]; then
        recommendations+=("Connect to power source immediately")
    fi
    
    # Add recommendations to report
    jq --argjson recommendations "$(printf '%s\n' "${recommendations[@]}" | jq -R . | jq -s .)" \
       '.recommendations = $recommendations' \
       "$health_report" > "${health_report}.tmp" && mv "${health_report}.tmp" "$health_report"
    
    # Display results
    echo ""
    echo "Battery Health Analysis Results:"
    echo "  Overall Health Score: $health_score/100 ($health_status)"
    echo "  Cycle Count: ${cycle_count:-0}"
    echo "  Condition: $condition"
    echo "  Maximum Capacity: ${max_capacity:-0}%"
    echo "  Current Charge: ${state_of_charge:-0}%"
    echo "  Charging Status: $charging_status"
    echo "  Time Remaining: ${time_remaining:-N/A}"
    echo "  Power Source: $power_source"
    echo "  Temperature: ${temperature_celsius}°C"
    
    if [[ ${#recommendations[@]} -gt 0 ]]; then
        echo "  Recommendations:"
        for rec in "${recommendations[@]}"; do
            echo "    - $rec"
        done
    else
        echo "  ✅ No immediate action required"
    fi
    
    echo "  Health Report: $health_report"
    
    # Log health monitoring
    audit_log "Battery health monitoring completed: $device_category (Score: $health_score/100, Status: $health_status)"
    
    return 0
}

Enterprise Battery Management System

#!/bin/bash

# MacFleet Enterprise Battery Management System
# Comprehensive battery monitoring, optimization, and lifecycle management

# Configuration
CONFIG_DIR="/etc/macfleet/battery"
LOG_FILE="/var/log/macfleet_battery_management.log"
DATA_DIR="/var/data/macfleet/battery"
REPORTS_DIR="/var/reports/macfleet/battery"
AUDIT_LOG="/var/log/macfleet_battery_audit.log"
BACKUP_DIR="/var/backups/macfleet/battery"

# 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"
}

# Battery database management
initialize_battery_database() {
    local db_file="$DATA_DIR/battery_fleet_database.json"
    
    if [[ ! -f "$db_file" ]]; then
        cat > "$db_file" << EOF
{
    "version": "1.0",
    "created": "$(date -Iseconds)",
    "fleet_devices": {},
    "battery_policies": {},
    "health_monitoring": {},
    "performance_metrics": {},
    "maintenance_schedule": {},
    "compliance_tracking": {}
}
EOF
        log_action "Battery fleet database initialized: $db_file"
    fi
}

# Fleet-wide battery discovery
discover_battery_fleet() {
    local discovery_file="$DATA_DIR/battery_fleet_discovery_$(date +%Y%m%d_%H%M%S).json"
    
    log_action "Starting fleet-wide battery discovery"
    
    echo "=== Battery Fleet Discovery ==="
    
    # Device identification
    local device_serial
    device_serial=$(system_profiler SPHardwareDataType | grep "Serial Number" | awk -F': ' '{print $2}' | tr -d ' ')
    
    local device_model
    device_model=$(system_profiler SPHardwareDataType | grep "Model Name" | awk -F': ' '{print $2}' | tr -d ' ')
    
    local device_identifier
    device_identifier=$(system_profiler SPHardwareDataType | grep "Model Identifier" | awk -F': ' '{print $2}' | tr -d ' ')
    
    # Battery hardware information
    echo "Analyzing battery hardware..."
    local battery_hardware
    battery_hardware=$(ioreg -n AppleSmartBattery -r | grep -E "(MaxCapacity|DesignCapacity|CycleCount|Temperature|Voltage|Current)")
    
    local max_capacity_mah
    max_capacity_mah=$(echo "$battery_hardware" | grep "MaxCapacity" | awk -F'= ' '{print $2}' | tr -d ' ')
    
    local design_capacity_mah
    design_capacity_mah=$(echo "$battery_hardware" | grep "DesignCapacity" | awk -F'= ' '{print $2}' | tr -d ' ')
    
    local current_voltage
    current_voltage=$(echo "$battery_hardware" | grep "Voltage" | awk -F'= ' '{print $2}' | tr -d ' ')
    
    local current_amperage
    current_amperage=$(echo "$battery_hardware" | grep "Current" | awk -F'= ' '{print $2}' | tr -d ' ')
    
    # Power management configuration
    echo "Examining power management configuration..."
    local power_config
    power_config=$(pmset -g custom)
    
    # Battery usage patterns
    echo "Analyzing usage patterns..."
    local usage_stats=()
    
    # Check if battery health management is enabled
    local health_mgmt_enabled
    health_mgmt_enabled=$(pmset -g | grep "Battery Health Management" | awk '{print $4}' || echo "unknown")
    
    # Check optimized battery charging
    local optimized_charging
    optimized_charging=$(pmset -g | grep "Optimized Battery Charging" | awk '{print $4}' || echo "unknown")
    
    # Generate discovery report
    cat > "$discovery_file" << EOF
{
    "discovery_timestamp": "$(date -Iseconds)",
    "device_info": {
        "hostname": "$(hostname)",
        "serial_number": "$device_serial",
        "model_name": "$device_model",
        "model_identifier": "$device_identifier",
        "os_version": "$(sw_vers -productVersion)"
    },
    "battery_hardware": {
        "max_capacity_mah": ${max_capacity_mah:-0},
        "design_capacity_mah": ${design_capacity_mah:-0},
        "current_voltage": ${current_voltage:-0},
        "current_amperage": ${current_amperage:-0}
    },
    "power_management": {
        "health_management_enabled": "$health_mgmt_enabled",
        "optimized_charging_enabled": "$optimized_charging"
    },
    "discovery_metadata": {
        "discovery_method": "enterprise_automated",
        "discovery_version": "1.0"
    }
}
EOF
    
    log_action "Battery fleet discovery completed: $discovery_file"
    
    # Display summary
    echo ""
    echo "Discovery Summary:"
    echo "  Device: $device_model ($device_identifier)"
    echo "  Serial: $device_serial"
    echo "  Battery Capacity: ${max_capacity_mah:-0} mAh (Design: ${design_capacity_mah:-0} mAh)"
    echo "  Health Management: $health_mgmt_enabled"
    echo "  Optimized Charging: $optimized_charging"
    echo "  Discovery Report: $discovery_file"
    
    return 0
}

# Battery optimization engine
optimize_battery_performance() {
    local optimization_profile="$1"
    local target_usage="${2:-standard}"
    local optimization_report="$REPORTS_DIR/battery_optimization_$(date +%Y%m%d_%H%M%S).json"
    
    log_action "Starting battery optimization (Profile: $optimization_profile, Usage: $target_usage)"
    
    echo "=== Battery Performance Optimization ==="
    echo "Optimization Profile: $optimization_profile"
    echo "Target Usage: $target_usage"
    
    # Initialize optimization report
    cat > "$optimization_report" << EOF
{
    "optimization_profile": "$optimization_profile",
    "target_usage": "$target_usage",
    "start_timestamp": "$(date -Iseconds)",
    "hostname": "$(hostname)",
    "optimizations_applied": [],
    "performance_improvements": {},
    "recommendations": []
}
EOF
    
    local optimizations_applied=()
    local performance_before={}
    local performance_after={}
    
    # Capture baseline performance
    echo "Capturing baseline performance..."
    local baseline_charge
    baseline_charge=$(pmset -g batt | grep -o "[0-9]*%" | tr -d '%' | head -1)
    
    case "$optimization_profile" in
        "maximum_battery_life")
            echo "Applying maximum battery life optimizations..."
            
            # Enable low power mode
            sudo pmset -b lowpowermode 1 2>/dev/null && {
                optimizations_applied+=("low_power_mode_enabled")
                echo "  ✅ Low power mode enabled"
            }
            
            # Reduce display brightness
            if command -v brightness &>/dev/null; then
                brightness 0.3 && {
                    optimizations_applied+=("display_brightness_reduced")
                    echo "  ✅ Display brightness reduced"
                }
            fi
            
            # Optimize sleep settings for battery
            sudo pmset -b displaysleep 2 sleep 5 disksleep 3 && {
                optimizations_applied+=("sleep_settings_optimized")
                echo "  ✅ Sleep settings optimized for battery"
            }
            
            # Disable unnecessary services
            sudo pmset -b ttyskeepawake 0 && {
                optimizations_applied+=("tty_sleep_optimized")
                echo "  ✅ TTY sleep optimization enabled"
            }
            ;;
            
        "balanced_performance")
            echo "Applying balanced performance optimizations..."
            
            # Enable battery health management
            if pmset -g | grep -q "Battery Health Management.*0"; then
                # Note: Battery Health Management can't be controlled via pmset in newer macOS versions
                optimizations_applied+=("health_management_status_checked")
                echo "  ℹ️  Battery Health Management status verified"
            fi
            
            # Optimize charging patterns
            sudo pmset -b acwake 0 && {
                optimizations_applied+=("ac_wake_optimized")
                echo "  ✅ AC wake optimization applied"
            }
            
            # Set balanced sleep settings
            sudo pmset -b displaysleep 10 sleep 15 disksleep 10 && {
                optimizations_applied+=("balanced_sleep_settings")
                echo "  ✅ Balanced sleep settings applied"
            }
            ;;
            
        "performance_priority")
            echo "Applying performance priority optimizations..."
            
            # Disable power nap on battery
            sudo pmset -b powernap 0 && {
                optimizations_applied+=("power_nap_disabled")
                echo "  ✅ Power Nap disabled on battery"
            }
            
            # Optimize for performance
            sudo pmset -b displaysleep 30 sleep 60 disksleep 30 && {
                optimizations_applied+=("performance_sleep_settings")
                echo "  ✅ Performance-focused sleep settings applied"
            }
            
            # Keep system awake during critical tasks
            sudo pmset -b ttyskeepawake 1 && {
                optimizations_applied+=("system_awake_optimization")
                echo "  ✅ System awake optimization for performance"
            }
            ;;
            
        "field_operations")
            echo "Applying field operations optimizations..."
            
            # Ultra-conservative power settings
            sudo pmset -b displaysleep 1 sleep 3 disksleep 1 && {
                optimizations_applied+=("ultra_conservative_sleep")
                echo "  ✅ Ultra-conservative sleep settings for field use"
            }
            
            # Disable all wake events
            sudo pmset -b wake 0 womp 0 && {
                optimizations_applied+=("wake_events_disabled")
                echo "  ✅ Wake events disabled for maximum battery conservation"
            }
            
            # Enable hibernation
            sudo pmset -b hibernatemode 25 && {
                optimizations_applied+=("hibernation_enabled")
                echo "  ✅ Hibernation enabled for extended standby"
            }
            ;;
            
        *)
            echo "❌ Unknown optimization profile: $optimization_profile"
            return 1
            ;;
    esac
    
    # Wait for changes to take effect
    echo "Waiting for optimizations to take effect..."
    sleep 5
    
    # Capture post-optimization performance
    local optimized_charge
    optimized_charge=$(pmset -g batt | grep -o "[0-9]*%" | tr -d '%' | head -1)
    
    # Update optimization report
    jq --argjson optimizations "$(printf '%s\n' "${optimizations_applied[@]}" | jq -R . | jq -s .)" \
       --argjson baseline_charge "${baseline_charge:-0}" \
       --argjson optimized_charge "${optimized_charge:-0}" \
       '.optimizations_applied = $optimizations |
        .performance_improvements = {
          "baseline_charge": $baseline_charge,
          "optimized_charge": $optimized_charge,
          "charge_preservation": ($optimized_charge - $baseline_charge)
        } |
        .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 Applied: ${#optimizations_applied[@]}"
    echo "  Baseline Charge: ${baseline_charge:-0}%"
    echo "  Current Charge: ${optimized_charge:-0}%"
    echo "  Report: $optimization_report"
    
    audit_log "Battery optimization completed: $optimization_profile (${#optimizations_applied[@]} optimizations)"
    
    return 0
}

# Fleet battery analytics
generate_fleet_analytics() {
    local analytics_type="$1"
    local time_period="${2:-30_days}"
    local analytics_report="$REPORTS_DIR/battery_analytics_${analytics_type}_$(date +%Y%m%d_%H%M%S).json"
    
    log_action "Generating fleet battery analytics: $analytics_type ($time_period)"
    
    echo "=== Fleet Battery Analytics ==="
    echo "Analytics Type: $analytics_type"
    echo "Time Period: $time_period"
    
    case "$analytics_type" in
        "health_overview")
            generate_health_overview_analytics "$analytics_report" "$time_period"
            ;;
        "usage_patterns")
            generate_usage_patterns_analytics "$analytics_report" "$time_period"
            ;;
        "performance_trends")
            generate_performance_trends_analytics "$analytics_report" "$time_period"
            ;;
        "maintenance_forecast")
            generate_maintenance_forecast_analytics "$analytics_report" "$time_period"
            ;;
        "compliance_report")
            generate_compliance_analytics "$analytics_report" "$time_period"
            ;;
        *)
            log_error "Unknown analytics type: $analytics_type"
            return 1
            ;;
    esac
    
    log_action "✅ Fleet analytics generated: $analytics_report"
    echo "Analytics report saved to: $analytics_report"
}

# Battery compliance monitoring
monitor_battery_compliance() {
    local compliance_framework="$1"
    local compliance_report="$REPORTS_DIR/battery_compliance_$(date +%Y%m%d_%H%M%S).json"
    
    log_action "Starting battery compliance monitoring: $compliance_framework"
    
    echo "=== Battery Compliance Monitoring ==="
    echo "Framework: $compliance_framework"
    
    # Initialize compliance report
    cat > "$compliance_report" << EOF
{
    "compliance_framework": "$compliance_framework",
    "scan_timestamp": "$(date -Iseconds)",
    "hostname": "$(hostname)",
    "compliance_checks": {},
    "violations": [],
    "recommendations": []
}
EOF
    
    local violations=()
    local compliance_score=100
    
    case "$compliance_framework" in
        "enterprise_standard")
            # Check battery health management
            if ! pmset -g | grep -q "Battery Health Management.*1"; then
                violations+=("battery_health_management_disabled")
                ((compliance_score -= 20))
            fi
            
            # Check optimized charging
            if ! pmset -g | grep -q "Optimized Battery Charging.*1"; then
                violations+=("optimized_charging_disabled")
                ((compliance_score -= 15))
            fi
            
            # Check power source logging
            if [[ ! -f "/var/log/powermanagement.log" ]]; then
                violations+=("power_management_logging_missing")
                ((compliance_score -= 10))
            fi
            ;;
            
        "environmental_compliance")
            # Check battery condition
            local condition
            condition=$(system_profiler SPPowerDataType | grep "Condition:" | awk -F': ' '{print $2}' | tr -d ' ')
            
            if [[ "$condition" != "Normal" ]]; then
                violations+=("battery_condition_degraded")
                ((compliance_score -= 30))
            fi
            
            # Check cycle count
            local cycle_count
            cycle_count=$(system_profiler SPPowerDataType | grep "Cycle Count:" | awk -F': ' '{print $2}' | tr -d ' ')
            
            if [[ $cycle_count -gt 1000 ]]; then
                violations+=("high_cycle_count_environmental_concern")
                ((compliance_score -= 25))
            fi
            ;;
            
        *)
            echo "❌ Unknown compliance framework: $compliance_framework"
            return 1
            ;;
    esac
    
    # Update compliance report
    jq --argjson violations "$(printf '%s\n' "${violations[@]}" | jq -R . | jq -s .)" \
       --argjson compliance_score "$compliance_score" \
       '.violations = $violations |
        .compliance_score = $compliance_score |
        .end_timestamp = "'"$(date -Iseconds)"'"' \
       "$compliance_report" > "${compliance_report}.tmp" && mv "${compliance_report}.tmp" "$compliance_report"
    
    echo ""
    echo "Compliance Results:"
    echo "  Framework: $compliance_framework"
    echo "  Compliance Score: $compliance_score/100"
    echo "  Violations Found: ${#violations[@]}"
    
    if [[ ${#violations[@]} -gt 0 ]]; then
        echo "  Violations:"
        for violation in "${violations[@]}"; do
            echo "    - $violation"
        done
    else
        echo "  ✅ No violations found"
    fi
    
    echo "  Compliance Report: $compliance_report"
    
    audit_log "Battery compliance monitoring completed: $compliance_framework (Score: $compliance_score/100)"
    
    return 0
}

# Main function with command routing
main() {
    local command="$1"
    shift
    
    # Initialize
    create_directories
    initialize_battery_database
    
    case "$command" in
        "status")
            # Enhanced battery status
            get_comprehensive_battery_info
            ;;
        "health_check")
            monitor_battery_health "$@"
            ;;
        "discover_fleet")
            discover_battery_fleet
            ;;
        "optimize")
            optimize_battery_performance "$@"
            ;;
        "apply_policy")
            apply_battery_policy "$@"
            ;;
        "fleet_analytics")
            generate_fleet_analytics "$@"
            ;;
        "compliance_check")
            monitor_battery_compliance "$@"
            ;;
        "show_categories")
            print_battery_categories
            ;;
        "show_policies")
            for policy in maximum_performance balanced_efficiency extended_battery_life enterprise_standard high_security_mobile creative_professional field_operations compliance_strict; do
                echo "Policy: $policy"
                get_battery_policy "$policy" | jq .
                echo ""
            done
            ;;
        *)
            echo "MacFleet Enterprise Battery Management System"
            echo "Usage: $0 <command> [options]"
            echo ""
            echo "Commands:"
            echo "  status                                    - Enhanced battery status and information"
            echo "  health_check <category> [profile]        - Comprehensive battery health monitoring"
            echo "  discover_fleet                           - Fleet-wide battery discovery"
            echo "  optimize <profile> [usage]               - Battery performance optimization"
            echo "  apply_policy <policy>                    - Apply battery management policy"
            echo "  fleet_analytics <type> [period]          - Generate fleet battery analytics"
            echo "  compliance_check <framework>             - Battery compliance monitoring"
            echo "  show_categories                          - Show battery device categories"
            echo "  show_policies                            - Show battery management policies"
            echo ""
            echo "Examples:"
            echo "  $0 status"
            echo "  $0 health_check executive_mobile enterprise"
            echo "  $0 optimize maximum_battery_life mobile"
            echo "  $0 apply_policy enterprise_standard"
            echo "  $0 fleet_analytics health_overview 30_days"
            echo "  $0 compliance_check enterprise_standard"
            ;;
    esac
}

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

Fleet Deployment Configuration

Fleet Configuration Example

{
    "fleet_name": "MacFleet Enterprise Battery Management",
    "deployment_date": "2025-07-07",
    "devices": [
        {
            "hostname": "mac-executive-01.company.com",
            "category": "executive_mobile",
            "policy": "enterprise_standard"
        },
        {
            "hostname": "mac-creative-01.company.com", 
            "category": "creative_workstation",
            "policy": "creative_professional"
        },
        {
            "hostname": "mac-field-01.company.com",
            "category": "field_service",
            "policy": "field_operations"
        }
    ],
    "monitoring_schedule": {
        "health_checks": "daily",
        "performance_analytics": "weekly",
        "compliance_audits": "monthly"
    }
}

Security Considerations

Battery Security

  • Power Management Integrity - Ensure power management settings cannot be tampered with
  • Battery Health Monitoring - Continuous monitoring for security-related battery issues
  • Thermal Management - Monitor battery temperature for security and safety
  • Charging Security - Secure charging protocols and malware protection
  • Physical Security - Monitor for battery tampering or replacement

Compliance Framework

  • Environmental Compliance - Battery disposal and lifecycle compliance
  • Health & Safety - Battery safety monitoring and incident reporting
  • Energy Efficiency - Power consumption tracking and optimization
  • Asset Management - Battery replacement and maintenance tracking
  • Audit Trails - Comprehensive logging of all battery-related operations

Performance Optimization

Battery Performance

  • Charging Optimization - Intelligent charging patterns and health preservation
  • Power Efficiency - System-level power consumption optimization
  • Thermal Management - Temperature-based performance optimization
  • Usage Analytics - Pattern recognition and optimization recommendations
  • Lifecycle Extension - Proactive measures to extend battery lifespan

Troubleshooting Guide

Common Issues

Battery Not Charging

  • Check charging cable and adapter functionality
  • Verify charging port for debris or damage
  • Reset SMC (System Management Controller)
  • Check for software-based charging restrictions

Rapid Battery Drain

  • Identify power-hungry applications with Activity Monitor
  • Check for runaway processes consuming CPU
  • Verify display brightness and other power settings
  • Monitor background app refresh and location services

Battery Health Degradation

  • Monitor cycle count and capacity trends
  • Check for extreme temperature exposure
  • Verify charging patterns and optimize for longevity
  • Consider battery replacement based on health metrics

Diagnostic Commands

# Comprehensive battery status
pmset -g batt

# Detailed battery health
system_profiler SPPowerDataType

# Power management settings
pmset -g

# Battery registry information
ioreg -n AppleSmartBattery -r

# Thermal state monitoring
pmset -g therm

Important Notes

  • Battery Safety - Monitor temperature and charging patterns for safety
  • Lifecycle Management - Proactive monitoring and replacement planning
  • Environmental Impact - Proper battery disposal and recycling procedures
  • Performance Impact - Balance battery optimization with system performance needs
  • Compliance Requirements - Maintain compliance with environmental and safety standards
  • Documentation - Keep detailed records of battery health and maintenance activities

Battery Charging Limit Management on macOS

Manage battery charging limits across your MacFleet devices to optimize battery health and implement enterprise power management policies. This tutorial covers installation of battery management tools, charging limit configuration, persistence settings, and comprehensive fleet-wide battery health monitoring.

Understanding Battery Charging Limits

Battery charging limits help preserve battery health by preventing overcharging, especially beneficial for devices that remain plugged in continuously:

Why Set Charging Limits?

  • Battery Longevity - Prevents degradation from constant 100% charge
  • Heat Reduction - Lower charge levels generate less heat during operation
  • Enterprise Cost Savings - Extended battery life reduces replacement costs
  • Power Management - Optimized charging for stationary workstations
  • Environmental Benefits - Longer battery life reduces electronic waste

Battery Management Tools

  • bclm - Battery Charge Limit Max (primary tool)
  • SMC - System Management Controller (hardware interface)
  • Homebrew - Package manager for macOS tools
  • Power Management - Built-in macOS power controls

Prerequisites and Installation

Install Homebrew Package Manager

#!/bin/bash

# Install Homebrew package manager
echo "🍺 Installing Homebrew package manager..."

# Check if Homebrew is already installed
if command -v brew >/dev/null 2>&1; then
    echo "ℹ️ Homebrew is already installed"
    echo "Homebrew version: $(brew --version | head -1)"
else
    echo "Installing Homebrew..."
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    
    if [[ $? -eq 0 ]]; then
        echo "✅ Homebrew installed successfully"
    else
        echo "❌ Homebrew installation failed"
        exit 1
    fi
fi

# Verify installation and add to PATH if needed
if [[ -f /opt/homebrew/bin/brew ]]; then
    echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zprofile
    eval "$(/opt/homebrew/bin/brew shellenv)"
elif [[ -f /usr/local/bin/brew ]]; then
    echo 'eval "$(/usr/local/bin/brew shellenv)"' >> ~/.zprofile
    eval "$(/usr/local/bin/brew shellenv)"
fi

echo "Homebrew location: $(which brew)"

Install BCLM (Battery Charge Limit Max)

#!/bin/bash

# Install bclm (Battery Charge Limit Max)
echo "🔋 Installing bclm (Battery Charge Limit Max)..."

# Ensure Homebrew is available
if ! command -v brew >/dev/null 2>&1; then
    echo "❌ Homebrew not found. Please install Homebrew first."
    exit 1
fi

# Install bclm
echo "Adding zackelia/formulae tap..."
if brew tap zackelia/formulae; then
    echo "✅ Tap added successfully"
else
    echo "❌ Failed to add tap"
    exit 1
fi

echo "Installing bclm..."
if brew install bclm; then
    echo "✅ bclm installed successfully"
else
    echo "❌ bclm installation failed"
    exit 1
fi

# Verify installation
if command -v bclm >/dev/null 2>&1; then
    echo "bclm location: $(which bclm)"
    echo "Testing bclm access..."
    
    # Test read access (doesn't require sudo)
    if bclm read >/dev/null 2>&1; then
        echo "✅ bclm is working correctly"
        echo "Current charging limit: $(bclm read)%"
    else
        echo "⚠️ bclm installed but may require additional permissions"
    fi
else
    echo "❌ bclm not found in PATH"
    exit 1
fi

Basic Charging Limit Management

Set Charging Limit

#!/bin/bash

# Set battery charging limit
LIMIT="$1"

if [[ -z "$LIMIT" ]]; then
    echo "❌ Usage: $0 <percentage>"
    echo "Example: $0 80"
    echo "Valid range: 50-100"
    exit 1
fi

# Validate limit range
if [[ "$LIMIT" -lt 50 || "$LIMIT" -gt 100 ]]; then
    echo "❌ Invalid limit: $LIMIT"
    echo "Charging limit must be between 50% and 100%"
    exit 1
fi

echo "🔋 Setting battery charging limit to $LIMIT%..."

# Get current limit for comparison
CURRENT_LIMIT=$(bclm read 2>/dev/null)
if [[ -n "$CURRENT_LIMIT" ]]; then
    echo "Current limit: $CURRENT_LIMIT%"
fi

# Set new charging limit
if sudo bclm write "$LIMIT"; then
    echo "✅ Charging limit set to $LIMIT%"
    
    # Verify the setting
    NEW_LIMIT=$(bclm read 2>/dev/null)
    if [[ "$NEW_LIMIT" == "$LIMIT" ]]; then
        echo "✅ Setting verified: $NEW_LIMIT%"
    else
        echo "⚠️ Warning: Verification shows $NEW_LIMIT% instead of $LIMIT%"
    fi
else
    echo "❌ Failed to set charging limit"
    exit 1
fi

echo "ℹ️ Note: Restart may be required for changes to take effect"

Read Current Charging Limit

#!/bin/bash

# Read current battery charging limit
echo "🔍 Reading current battery charging limit..."

if command -v bclm >/dev/null 2>&1; then
    CURRENT_LIMIT=$(bclm read 2>/dev/null)
    
    if [[ -n "$CURRENT_LIMIT" ]]; then
        echo "Current charging limit: $CURRENT_LIMIT%"
        
        # Provide context about the limit
        if [[ "$CURRENT_LIMIT" -eq 100 ]]; then
            echo "ℹ️ Battery charges to maximum capacity (no limit set)"
        elif [[ "$CURRENT_LIMIT" -ge 80 ]]; then
            echo "ℹ️ Conservative charging limit for battery longevity"
        elif [[ "$CURRENT_LIMIT" -ge 60 ]]; then
            echo "ℹ️ Moderate charging limit for extended battery life"
        else
            echo "ℹ️ Aggressive charging limit for maximum battery preservation"
        fi
    else
        echo "❌ Unable to read charging limit"
        echo "This may indicate bclm is not properly installed or lacks permissions"
        exit 1
    fi
else
    echo "❌ bclm not found. Please install bclm first."
    exit 1
fi

Make Charging Limit Persistent

#!/bin/bash

# Make charging limit persistent across reboots
echo "💾 Making charging limit persistent..."

if ! command -v bclm >/dev/null 2>&1; then
    echo "❌ bclm not found. Please install bclm first."
    exit 1
fi

# Get current limit
CURRENT_LIMIT=$(bclm read 2>/dev/null)
if [[ -z "$CURRENT_LIMIT" ]]; then
    echo "❌ Unable to read current charging limit"
    exit 1
fi

echo "Current charging limit: $CURRENT_LIMIT%"

# Make persistent
if sudo bclm persist; then
    echo "✅ Charging limit ($CURRENT_LIMIT%) is now persistent"
    echo "The limit will be maintained across system reboots"
else
    echo "❌ Failed to make charging limit persistent"
    exit 1
fi

echo "ℹ️ To remove persistence, run: sudo bclm unpersist"

Remove Charging Limit Persistence

#!/bin/bash

# Remove charging limit persistence
echo "🔄 Removing charging limit persistence..."

if ! command -v bclm >/dev/null 2>&1; then
    echo "❌ bclm not found. Please install bclm first."
    exit 1
fi

# Get current limit before removing persistence
CURRENT_LIMIT=$(bclm read 2>/dev/null)
if [[ -n "$CURRENT_LIMIT" ]]; then
    echo "Current charging limit: $CURRENT_LIMIT%"
fi

# Remove persistence
if sudo bclm unpersist; then
    echo "✅ Charging limit persistence removed"
    echo "The limit may reset to 100% after next reboot"
else
    echo "❌ Failed to remove charging limit persistence"
    exit 1
fi

echo "ℹ️ To restore persistence, run: sudo bclm persist"

Advanced Battery Management

Enterprise Battery Health Check

#!/bin/bash

# Comprehensive battery health assessment
echo "🔋 Performing comprehensive battery health check..."

# Check if battery is present
if ! system_profiler SPPowerDataType | grep -q "Battery Information"; then
    echo "❌ No battery found on this system"
    exit 1
fi

echo "=== Battery Health Assessment ==="

# Get battery information
BATTERY_INFO=$(system_profiler SPPowerDataType)

# Extract key metrics
CYCLE_COUNT=$(echo "$BATTERY_INFO" | grep "Cycle Count" | awk '{print $3}')
CONDITION=$(echo "$BATTERY_INFO" | grep "Condition" | awk '{print $2}')
MAX_CAPACITY=$(echo "$BATTERY_INFO" | grep "Maximum Capacity" | awk '{print $3}' | sed 's/%//')

echo "Battery Condition: $CONDITION"
echo "Cycle Count: $CYCLE_COUNT"
echo "Maximum Capacity: $MAX_CAPACITY%"

# Check charging limit if bclm is available
if command -v bclm >/dev/null 2>&1; then
    CHARGING_LIMIT=$(bclm read 2>/dev/null)
    if [[ -n "$CHARGING_LIMIT" ]]; then
        echo "Charging Limit: $CHARGING_LIMIT%"
    else
        echo "Charging Limit: Not set (100%)"
    fi
fi

# Power adapter information
POWER_ADAPTER=$(echo "$BATTERY_INFO" | grep -A5 "AC Charger Information" | grep "Wattage" | awk '{print $2}')
if [[ -n "$POWER_ADAPTER" ]]; then
    echo "Power Adapter: ${POWER_ADAPTER}W"
fi

# Health assessment
echo -e "\n=== Health Assessment ==="

if [[ "$CONDITION" == "Normal" ]]; then
    echo "✅ Battery condition is normal"
elif [[ "$CONDITION" == "Replace Soon" ]]; then
    echo "⚠️ Battery should be replaced soon"
elif [[ "$CONDITION" == "Replace Now" ]]; then
    echo "❌ Battery needs immediate replacement"
else
    echo "ℹ️ Battery condition: $CONDITION"
fi

if [[ -n "$CYCLE_COUNT" ]]; then
    if [[ "$CYCLE_COUNT" -lt 500 ]]; then
        echo "✅ Cycle count is healthy ($CYCLE_COUNT cycles)"
    elif [[ "$CYCLE_COUNT" -lt 1000 ]]; then
        echo "⚠️ Moderate cycle count ($CYCLE_COUNT cycles)"
    else
        echo "❌ High cycle count ($CYCLE_COUNT cycles)"
    fi
fi

if [[ -n "$MAX_CAPACITY" ]]; then
    if [[ "$MAX_CAPACITY" -ge 90 ]]; then
        echo "✅ Maximum capacity is excellent ($MAX_CAPACITY%)"
    elif [[ "$MAX_CAPACITY" -ge 80 ]]; then
        echo "✅ Maximum capacity is good ($MAX_CAPACITY%)"
    elif [[ "$MAX_CAPACITY" -ge 70 ]]; then
        echo "⚠️ Maximum capacity is declining ($MAX_CAPACITY%)"
    else
        echo "❌ Maximum capacity is poor ($MAX_CAPACITY%)"
    fi
fi

# Recommendations
echo -e "\n=== Recommendations ==="

if [[ -z "$CHARGING_LIMIT" || "$CHARGING_LIMIT" -eq 100 ]]; then
    echo "💡 Consider setting a charging limit (80-90%) for better battery health"
fi

if [[ "$CYCLE_COUNT" -gt 1000 && "$MAX_CAPACITY" -lt 80 ]]; then
    echo "💡 Battery replacement may be needed soon"
fi

Optimized Charging Limit Recommendations

#!/bin/bash

# Provide charging limit recommendations based on usage patterns
echo "🎯 Analyzing optimal charging limit recommendations..."

# Get device model and usage information
DEVICE_MODEL=$(system_profiler SPHardwareDataType | grep "Model Name" | awk -F': ' '{print $2}')
UPTIME=$(uptime | awk '{print $3}' | sed 's/,//')

echo "Device: $DEVICE_MODEL"
echo "Current uptime: $UPTIME"

# Check if device is primarily plugged in
AC_POWER_COUNT=$(pmset -g log | grep -c "Using AC" 2>/dev/null || echo "0")
BATTERY_POWER_COUNT=$(pmset -g log | grep -c "Using Batt" 2>/dev/null || echo "0")

echo -e "\n=== Usage Pattern Analysis ==="

if [[ "$AC_POWER_COUNT" -gt "$BATTERY_POWER_COUNT" ]]; then
    USAGE_TYPE="Desktop/Stationary"
    RECOMMENDED_LIMIT=80
    echo "Usage pattern: Primarily AC powered"
    echo "Recommendation: Set charging limit to $RECOMMENDED_LIMIT%"
else
    USAGE_TYPE="Mobile/Portable"
    RECOMMENDED_LIMIT=90
    echo "Usage pattern: Frequently on battery"
    echo "Recommendation: Set charging limit to $RECOMMENDED_LIMIT%"
fi

# Get current battery health
BATTERY_CONDITION=$(system_profiler SPPowerDataType | grep "Condition" | awk '{print $2}')
MAX_CAPACITY=$(system_profiler SPPowerDataType | grep "Maximum Capacity" | awk '{print $3}' | sed 's/%//')

if [[ -n "$MAX_CAPACITY" && "$MAX_CAPACITY" -lt 85 ]]; then
    RECOMMENDED_LIMIT=75
    echo "⚠️ Battery health is declining, recommended limit: $RECOMMENDED_LIMIT%"
fi

# Check current setting
if command -v bclm >/dev/null 2>&1; then
    CURRENT_LIMIT=$(bclm read 2>/dev/null)
    
    if [[ -n "$CURRENT_LIMIT" ]]; then
        echo "Current limit: $CURRENT_LIMIT%"
        
        if [[ "$CURRENT_LIMIT" -eq "$RECOMMENDED_LIMIT" ]]; then
            echo "✅ Current setting is optimal"
        else
            echo "💡 Consider adjusting to $RECOMMENDED_LIMIT% for optimal battery health"
        fi
    else
        echo "Current limit: Not set (100%)"
        echo "💡 Recommended action: Set charging limit to $RECOMMENDED_LIMIT%"
    fi
fi

echo -e "\n=== Implementation Command ==="
echo "To set recommended limit: sudo bclm write $RECOMMENDED_LIMIT"
echo "To make persistent: sudo bclm persist"

Enterprise Battery Management Script

#!/bin/bash

# MacFleet Battery Management Tool
# Comprehensive battery charging limit management for enterprise environments

# Configuration
LOG_FILE="/var/log/macfleet_battery.log"
BACKUP_DIR="/var/backups/macfleet/battery"
REPORT_DIR="/var/reports/macfleet/battery"
CONFIG_FILE="/etc/macfleet/battery_policy.conf"

# Battery policy settings
DEFAULT_CHARGING_LIMIT=80
MOBILE_DEVICE_LIMIT=90
STATIONARY_DEVICE_LIMIT=75
ENFORCE_BATTERY_POLICY=false
HEALTH_CHECK_ENABLED=true
ALERT_CAPACITY_THRESHOLD=80
ALERT_CYCLE_THRESHOLD=1000

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

# Setup directories
setup_directories() {
    for dir in "$BACKUP_DIR" "$REPORT_DIR" "$(dirname "$CONFIG_FILE")"; do
        if [[ ! -d "$dir" ]]; then
            sudo mkdir -p "$dir"
            log_action "Created directory: $dir"
        fi
    done
}

# Check if device has a battery
check_battery_presence() {
    if system_profiler SPPowerDataType | grep -q "Battery Information"; then
        return 0
    else
        echo "❌ No battery found on this system"
        log_action "No battery detected on device"
        return 1
    fi
}

# Install battery management tools
install_battery_tools() {
    echo "🔧 Installing battery management tools..."
    log_action "Battery tools installation started"
    
    # Check and install Homebrew
    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 to PATH
        if [[ -f /opt/homebrew/bin/brew ]]; then
            eval "$(/opt/homebrew/bin/brew shellenv)"
        elif [[ -f /usr/local/bin/brew ]]; then
            eval "$(/usr/local/bin/brew shellenv)"
        fi
    fi
    
    # Install bclm
    if ! command -v bclm >/dev/null 2>&1; then
        echo "Installing bclm..."
        brew tap zackelia/formulae && brew install bclm
        
        if command -v bclm >/dev/null 2>&1; then
            echo "✅ bclm installed successfully"
            log_action "bclm installed successfully"
        else
            echo "❌ bclm installation failed"
            log_action "bclm installation failed"
            return 1
        fi
    else
        echo "✅ bclm already installed"
    fi
    
    return 0
}

# Generate comprehensive battery report
generate_battery_report() {
    local report_file="$REPORT_DIR/battery_report_$(date +%Y%m%d_%H%M%S).txt"
    
    echo "📊 Generating comprehensive battery report..."
    
    {
        echo "MacFleet Battery Management Report"
        echo "Generated: $(date)"
        echo "Device: $(hostname)"
        echo "================================="
        echo ""
        
        # System information
        echo "=== System Information ==="
        system_profiler SPHardwareDataType | grep -E "Model Name|Model Identifier|Processor|Memory"
        echo ""
        
        # Battery hardware information
        echo "=== Battery Hardware Information ==="
        local battery_info=$(system_profiler SPPowerDataType)
        echo "$battery_info" | grep -E "Condition|Cycle Count|Maximum Capacity|Manufacturer|Device Name|Pack Lot Code|PCB Lot Code|Firmware Version|Hardware Revision"
        echo ""
        
        # Current charging limit
        echo "=== Charging Limit Configuration ==="
        if command -v bclm >/dev/null 2>&1; then
            local current_limit=$(bclm read 2>/dev/null)
            if [[ -n "$current_limit" ]]; then
                echo "Current charging limit: $current_limit%"
                
                # Check if persistent
                local smc_value=$(sudo bclm read 2>/dev/null)
                if [[ "$smc_value" == "$current_limit" ]]; then
                    echo "Persistence status: Enabled"
                else
                    echo "Persistence status: Disabled"
                fi
            else
                echo "Current charging limit: Not set (100%)"
                echo "Persistence status: N/A"
            fi
        else
            echo "bclm status: Not installed"
        fi
        echo ""
        
        # Power usage analysis
        echo "=== Power Usage Analysis ==="
        echo "Power adapter connected: $(system_profiler SPPowerDataType | grep -q "AC Charger Information" && echo "Yes" || echo "No")"
        
        # Get power adapter info if available
        local adapter_info=$(system_profiler SPPowerDataType | grep -A3 "AC Charger Information" | grep "Wattage")
        if [[ -n "$adapter_info" ]]; then
            echo "Power adapter: $(echo "$adapter_info" | awk '{print $2}')W"
        fi
        
        # Battery temperature and voltage
        echo "Battery temperature: $(ioreg -l | grep Temperature | awk '{print $3/100}' | head -1)°C"
        echo "Battery voltage: $(ioreg -l | grep Voltage | awk '{print $3/1000}' | head -1)V"
        echo ""
        
        # Health assessment
        echo "=== Battery Health Assessment ==="
        local condition=$(echo "$battery_info" | grep "Condition" | awk '{print $2}')
        local cycle_count=$(echo "$battery_info" | grep "Cycle Count" | awk '{print $3}')
        local max_capacity=$(echo "$battery_info" | grep "Maximum Capacity" | awk '{print $3}' | sed 's/%//')
        
        echo "Overall condition: $condition"
        echo "Cycle count: $cycle_count"
        echo "Maximum capacity: $max_capacity%"
        
        # Health scoring
        local health_score=100
        
        if [[ "$condition" != "Normal" ]]; then
            health_score=$((health_score - 20))
        fi
        
        if [[ -n "$cycle_count" ]]; then
            if [[ "$cycle_count" -gt 1000 ]]; then
                health_score=$((health_score - 20))
            elif [[ "$cycle_count" -gt 500 ]]; then
                health_score=$((health_score - 10))
            fi
        fi
        
        if [[ -n "$max_capacity" ]]; then
            if [[ "$max_capacity" -lt 70 ]]; then
                health_score=$((health_score - 30))
            elif [[ "$max_capacity" -lt 80 ]]; then
                health_score=$((health_score - 20))
            elif [[ "$max_capacity" -lt 90 ]]; then
                health_score=$((health_score - 10))
            fi
        fi
        
        echo "Health score: $health_score/100"
        
        # Recommendations
        echo ""
        echo "=== Recommendations ==="
        
        if [[ "$health_score" -ge 80 ]]; then
            echo "✅ Battery health is good"
            echo "💡 Consider setting charging limit to 80% for optimal longevity"
        elif [[ "$health_score" -ge 60 ]]; then
            echo "⚠️ Battery health is declining"
            echo "💡 Set charging limit to 75% and monitor closely"
        else
            echo "❌ Battery health is poor"
            echo "💡 Consider battery replacement and immediate charging limit to 70%"
        fi
        
        # Policy compliance check
        if [[ "$ENFORCE_BATTERY_POLICY" == "true" ]]; then
            echo ""
            echo "=== Policy Compliance ==="
            echo "Battery policy enforcement: ENABLED"
            echo "Default charging limit: $DEFAULT_CHARGING_LIMIT%"
            
            if [[ -n "$current_limit" ]]; then
                if [[ "$current_limit" -eq "$DEFAULT_CHARGING_LIMIT" ]]; then
                    echo "Compliance status: ✅ COMPLIANT"
                else
                    echo "Compliance status: ❌ NON-COMPLIANT"
                    echo "Current: $current_limit%, Required: $DEFAULT_CHARGING_LIMIT%"
                fi
            else
                echo "Compliance status: ❌ NON-COMPLIANT (no limit set)"
            fi
        fi
        
    } > "$report_file"
    
    echo "📊 Report saved to: $report_file"
    log_action "Battery report generated: $report_file"
}

# Set optimal charging limit based on usage pattern
set_optimal_charging_limit() {
    local force_limit="$1"
    
    echo "🎯 Determining optimal charging limit..."
    
    if ! check_battery_presence; then
        return 1
    fi
    
    # Install tools if needed
    if ! command -v bclm >/dev/null 2>&1; then
        if ! install_battery_tools; then
            echo "❌ Failed to install required tools"
            return 1
        fi
    fi
    
    local recommended_limit="$DEFAULT_CHARGING_LIMIT"
    
    # Override with forced limit if provided
    if [[ -n "$force_limit" ]]; then
        recommended_limit="$force_limit"
        echo "Using forced limit: $recommended_limit%"
    else
        # Analyze usage pattern
        echo "Analyzing device usage pattern..."
        
        # Check if device is primarily stationary (simplified detection)
        local model=$(system_profiler SPHardwareDataType | grep "Model Name" | awk -F': ' '{print $2}')
        if echo "$model" | grep -qi "mac studio\|mac pro\|imac"; then
            recommended_limit="$STATIONARY_DEVICE_LIMIT"
            echo "Detected stationary device, recommended limit: $recommended_limit%"
        else
            recommended_limit="$MOBILE_DEVICE_LIMIT"
            echo "Detected mobile device, recommended limit: $recommended_limit%"
        fi
        
        # Adjust based on battery health
        local max_capacity=$(system_profiler SPPowerDataType | grep "Maximum Capacity" | awk '{print $3}' | sed 's/%//')
        if [[ -n "$max_capacity" && "$max_capacity" -lt 85 ]]; then
            recommended_limit=75
            echo "Adjusted for battery health: $recommended_limit%"
        fi
    fi
    
    # Set the charging limit
    echo "Setting charging limit to $recommended_limit%..."
    
    if sudo bclm write "$recommended_limit"; then
        echo "✅ Charging limit set to $recommended_limit%"
        
        # Make persistent
        if sudo bclm persist; then
            echo "✅ Charging limit made persistent"
            log_action "Charging limit set to $recommended_limit% and made persistent"
        else
            echo "⚠️ Failed to make charging limit persistent"
            log_action "Charging limit set to $recommended_limit% but persistence failed"
        fi
        
        # Verify setting
        local verify_limit=$(bclm read 2>/dev/null)
        if [[ "$verify_limit" == "$recommended_limit" ]]; then
            echo "✅ Setting verified: $verify_limit%"
        else
            echo "⚠️ Verification failed: expected $recommended_limit%, got $verify_limit%"
        fi
    else
        echo "❌ Failed to set charging limit"
        log_action "Failed to set charging limit to $recommended_limit%"
        return 1
    fi
}

# Monitor battery health and alert on issues
monitor_battery_health() {
    echo "🔍 Monitoring battery health..."
    
    if ! check_battery_presence; then
        return 1
    fi
    
    local battery_info=$(system_profiler SPPowerDataType)
    local condition=$(echo "$battery_info" | grep "Condition" | awk '{print $2}')
    local cycle_count=$(echo "$battery_info" | grep "Cycle Count" | awk '{print $3}')
    local max_capacity=$(echo "$battery_info" | grep "Maximum Capacity" | awk '{print $3}' | sed 's/%//')
    
    local alerts_triggered=0
    
    # Check condition
    if [[ "$condition" != "Normal" ]]; then
        echo "🚨 ALERT: Battery condition is $condition"
        log_action "ALERT: Battery condition is $condition"
        ((alerts_triggered++))
    fi
    
    # Check cycle count
    if [[ -n "$cycle_count" && "$cycle_count" -gt "$ALERT_CYCLE_THRESHOLD" ]]; then
        echo "🚨 ALERT: High cycle count - $cycle_count cycles"
        log_action "ALERT: High cycle count - $cycle_count cycles"
        ((alerts_triggered++))
    fi
    
    # Check capacity
    if [[ -n "$max_capacity" && "$max_capacity" -lt "$ALERT_CAPACITY_THRESHOLD" ]]; then
        echo "🚨 ALERT: Low maximum capacity - $max_capacity%"
        log_action "ALERT: Low maximum capacity - $max_capacity%"
        ((alerts_triggered++))
    fi
    
    if [[ "$alerts_triggered" -eq 0 ]]; then
        echo "✅ No battery health alerts"
        log_action "Battery health monitoring: No alerts"
    else
        echo "⚠️ $alerts_triggered battery health alert(s) triggered"
        log_action "Battery health monitoring: $alerts_triggered alerts triggered"
    fi
    
    return $alerts_triggered
}

# Main execution function
main() {
    local action="${1:-help}"
    local target="${2:-}"
    
    log_action "=== MacFleet Battery Management Started ==="
    
    setup_directories
    
    case "$action" in
        "install"|"setup")
            install_battery_tools
            ;;
        "report"|"status")
            generate_battery_report
            ;;
        "set")
            if [[ -n "$target" ]]; then
                set_optimal_charging_limit "$target"
            else
                set_optimal_charging_limit
            fi
            ;;
        "read"|"current")
            if command -v bclm >/dev/null 2>&1; then
                local current=$(bclm read 2>/dev/null)
                if [[ -n "$current" ]]; then
                    echo "Current charging limit: $current%"
                else
                    echo "No charging limit set (100%)"
                fi
            else
                echo "❌ bclm not installed"
            fi
            ;;
        "persist")
            if command -v bclm >/dev/null 2>&1; then
                if sudo bclm persist; then
                    echo "✅ Charging limit made persistent"
                else
                    echo "❌ Failed to make charging limit persistent"
                fi
            else
                echo "❌ bclm not installed"
            fi
            ;;
        "unpersist")
            if command -v bclm >/dev/null 2>&1; then
                if sudo bclm unpersist; then
                    echo "✅ Charging limit persistence removed"
                else
                    echo "❌ Failed to remove charging limit persistence"
                fi
            else
                echo "❌ bclm not installed"
            fi
            ;;
        "monitor")
            monitor_battery_health
            ;;
        "health")
            if check_battery_presence; then
                local battery_info=$(system_profiler SPPowerDataType)
                echo "=== Battery Health Summary ==="
                echo "$battery_info" | grep -E "Condition|Cycle Count|Maximum Capacity"
                
                if command -v bclm >/dev/null 2>&1; then
                    local limit=$(bclm read 2>/dev/null)
                    echo "Charging Limit: ${limit:-100}%"
                fi
            fi
            ;;
        "help"|*)
            echo "MacFleet Battery Management Tool"
            echo "Usage: $0 [action] [options]"
            echo ""
            echo "Actions:"
            echo "  install               - Install battery management tools (Homebrew, bclm)"
            echo "  report                - Generate comprehensive battery report"
            echo "  set [limit]           - Set optimal charging limit (or specify percentage)"
            echo "  read                  - Read current charging limit"
            echo "  persist               - Make charging limit persistent"
            echo "  unpersist             - Remove charging limit persistence"
            echo "  monitor               - Monitor battery health and trigger alerts"
            echo "  health                - Show battery health summary"
            echo "  help                  - Show this help message"
            echo ""
            echo "Examples:"
            echo "  $0 install             # Install required tools"
            echo "  $0 set 80              # Set 80% charging limit"
            echo "  $0 set                 # Set optimal limit based on device type"
            echo "  $0 report              # Generate detailed report"
            echo ""
            echo "Charging Limit Guidelines:"
            echo "  50-100%     - Valid range"
            echo "  80%         - Recommended for most devices"
            echo "  75%         - For stationary/desktop Macs"
            echo "  90%         - For mobile/laptop Macs"
            ;;
    esac
    
    log_action "=== MacFleet Battery Management Completed ==="
}

# Execute main function
main "$@"

Battery Health Monitoring

Automated Health Checks

# Schedule daily battery health monitoring
create_health_monitoring_schedule() {
    local plist_file="$HOME/Library/LaunchAgents/com.macfleet.battery-monitor.plist"
    
    cat > "$plist_file" << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.macfleet.battery-monitor</string>
    <key>ProgramArguments</key>
    <array>
        <string>/bin/bash</string>
        <string>$(realpath "$0")</string>
        <string>monitor</string>
    </array>
    <key>StartCalendarInterval</key>
    <dict>
        <key>Hour</key>
        <integer>9</integer>
        <key>Minute</key>
        <integer>0</integer>
    </dict>
    <key>RunAtLoad</key>
    <false/>
</dict>
</plist>
EOF
    
    launchctl load "$plist_file" 2>/dev/null
    echo "✅ Daily battery monitoring scheduled"
}

Charging Limit Recommendations

Device TypeRecommended LimitReasoning
Desktop Macs75-80%Always plugged in, prioritize longevity
Laptop Macs (Stationary)80%Mostly plugged in usage
Laptop Macs (Mobile)90%Need higher capacity for portability
Degraded Battery70-75%Extend remaining battery life

Important Notes

  • Supported Devices - Only works on Mac devices with batteries
  • Administrative Privileges - Requires sudo access for SMC modifications
  • System Compatibility - Compatible with modern macOS versions
  • Restart Requirements - Some changes may require system restart
  • Fleet Deployment - Test on individual devices before bulk deployment
  • Battery Health - Monitor battery condition regularly for optimal results

Manage Badge Notifications on macOS

Control and manage badge notifications across your MacFleet devices using command-line tools. This tutorial covers removing badge notifications for specific apps, managing dock-wide notifications, and implementing enterprise notification policies.

Understanding Badge Notifications

Badge notifications are the red circular icons that appear above application icons in the macOS dock, typically displaying numbers to indicate unread items like emails, messages, or updates. While useful for individual users, enterprise environments often require centralized notification management.

Key Features

  • App-specific control - Remove badges from individual applications
  • Dock-wide management - Clear all badge notifications at once
  • Automatic restoration - Badges reappear when applications are opened
  • System preference integration - Works with macOS notification settings

Remove Badge Notifications for Specific Apps

Basic Badge Removal

#!/bin/bash

# Remove badge notification for a specific application
APP_NAME="Mail"

defaults write com.apple.systempreferences AttentionPrefBundleIDs 0 && killall "$APP_NAME"

echo "Badge notification removed for $APP_NAME"

Enhanced App Badge Management

#!/bin/bash

# Advanced badge notification removal with validation
remove_app_badge() {
    local app_name="$1"
    
    if [[ -z "$app_name" ]]; then
        echo "❌ Error: Application name required"
        return 1
    fi
    
    # Check if application is running
    if pgrep -x "$app_name" > /dev/null; then
        echo "📱 Removing badge notification for $app_name..."
        
        # Remove badge notification
        defaults write com.apple.systempreferences AttentionPrefBundleIDs 0
        
        # Terminate and restart application to apply changes
        if killall "$app_name" 2>/dev/null; then
            echo "✅ Badge notification removed for $app_name"
            echo "ℹ️  Note: Badge will reappear when $app_name is reopened"
        else
            echo "⚠️  Warning: Could not restart $app_name (may not be running)"
        fi
    else
        echo "ℹ️  $app_name is not currently running"
        defaults write com.apple.systempreferences AttentionPrefBundleIDs 0
        echo "✅ Badge notification setting updated for $app_name"
    fi
}

# Usage examples
remove_app_badge "Mail"
remove_app_badge "Messages"
remove_app_badge "Calendar"

Common Applications Badge Removal

#!/bin/bash

# Remove badge notifications for common enterprise applications
COMMON_APPS=("Mail" "Messages" "Calendar" "Reminders" "FaceTime" "App Store" "System Preferences")

echo "🧹 Removing badge notifications for common applications..."

for app in "${COMMON_APPS[@]}"; do
    echo "Processing $app..."
    
    # Set notification preference
    defaults write com.apple.systempreferences AttentionPrefBundleIDs 0
    
    # Kill application if running
    if pgrep -x "$app" > /dev/null; then
        killall "$app" 2>/dev/null
        echo "  ✅ Badge cleared for $app"
    else
        echo "  ⏭️  $app not running, preference updated"
    fi
done

echo "🎉 Badge notification cleanup completed"

Remove All Badge Notifications (Dock-wide)

Basic Dock Badge Clearing

#!/bin/bash

# Remove all badge notifications from the dock
defaults write com.apple.systempreferences AttentionPrefBundleIDs 0 && killall Dock

echo "All badge notifications cleared from dock"

Comprehensive Dock Management

#!/bin/bash

# Advanced dock badge notification management
clear_all_dock_badges() {
    echo "🏗️  Clearing all badge notifications from dock..."
    
    # Backup current dock preferences
    local backup_file="/tmp/dock_backup_$(date +%s).plist"
    defaults export com.apple.dock "$backup_file"
    echo "📋 Dock preferences backed up to: $backup_file"
    
    # Clear badge notifications
    defaults write com.apple.systempreferences AttentionPrefBundleIDs 0
    
    # Get list of running dock applications
    local dock_apps
    dock_apps=$(osascript -e 'tell application "System Events" to get name of every application process whose background only is false')
    
    echo "🔄 Restarting dock to apply changes..."
    killall Dock
    
    # Wait for dock to restart
    sleep 3
    
    echo "✅ All badge notifications cleared from dock"
    echo "ℹ️  Badges will reappear when applications receive new notifications"
    
    return 0
}

# Execute dock badge clearing
clear_all_dock_badges

Enterprise Badge Management Script

#!/bin/bash

# MacFleet Badge Notification Management Tool
# Centralized control of badge notifications across enterprise devices

# Configuration
LOG_FILE="/var/log/macfleet_badges.log"
CONFIG_FILE="/etc/macfleet/badge_policy.conf"
BACKUP_DIR="/var/backups/macfleet/badges"

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

# Create necessary directories
setup_directories() {
    sudo mkdir -p "$(dirname "$LOG_FILE")" 2>/dev/null
    sudo mkdir -p "$BACKUP_DIR" 2>/dev/null
    sudo mkdir -p "$(dirname "$CONFIG_FILE")" 2>/dev/null
}

# Load configuration
load_config() {
    if [[ -f "$CONFIG_FILE" ]]; then
        source "$CONFIG_FILE"
        log_action "Configuration loaded from $CONFIG_FILE"
    else
        # Default configuration
        BADGE_POLICY="disabled"  # Options: enabled, disabled, selective
        ALLOWED_BADGE_APPS=("Calendar" "Reminders")
        BLOCKED_BADGE_APPS=("App Store" "System Preferences")
        AUTO_CLEAR_INTERVAL=3600  # 1 hour
        
        log_action "Using default configuration"
    fi
}

# Backup current badge settings
backup_badge_settings() {
    local backup_file="$BACKUP_DIR/badge_settings_$(date +%Y%m%d_%H%M%S).plist"
    
    defaults export com.apple.systempreferences "$backup_file" 2>/dev/null
    
    if [[ -f "$backup_file" ]]; then
        log_action "Badge settings backed up to: $backup_file"
        echo "$backup_file"
    else
        log_action "Warning: Could not backup badge settings"
        return 1
    fi
}

# Get current badge status
get_badge_status() {
    echo "📊 Current Badge Notification Status:"
    echo "======================================"
    
    # Check system preferences setting
    local attention_pref
    attention_pref=$(defaults read com.apple.systempreferences AttentionPrefBundleIDs 2>/dev/null || echo "not set")
    echo "System AttentionPrefBundleIDs: $attention_pref"
    
    # List applications with potential badges
    echo -e "\n📱 Applications that may show badges:"
    local badge_apps=("Mail" "Messages" "Calendar" "Reminders" "FaceTime" "App Store" "System Preferences" "Contacts")
    
    for app in "${badge_apps[@]}"; do
        if pgrep -x "$app" > /dev/null; then
            echo "  🟢 $app (running)"
        else
            echo "  ⚪ $app (not running)"
        fi
    done
    
    # Check dock processes
    echo -e "\n🏗️  Dock status:"
    if pgrep -x "Dock" > /dev/null; then
        echo "  🟢 Dock is running"
    else
        echo "  🔴 Dock is not running"
    fi
}

# Apply badge policy
apply_badge_policy() {
    log_action "Applying badge policy: $BADGE_POLICY"
    
    case "$BADGE_POLICY" in
        "disabled")
            disable_all_badges
            ;;
        "enabled")
            enable_all_badges
            ;;
        "selective")
            apply_selective_policy
            ;;
        *)
            log_action "Error: Unknown badge policy: $BADGE_POLICY"
            return 1
            ;;
    esac
}

# Disable all badge notifications
disable_all_badges() {
    echo "🚫 Disabling all badge notifications..."
    
    backup_badge_settings
    
    # Set system preference to disable badges
    defaults write com.apple.systempreferences AttentionPrefBundleIDs 0
    
    # Restart dock to apply changes
    killall Dock 2>/dev/null
    
    log_action "All badge notifications disabled"
    echo "✅ All badge notifications have been disabled"
}

# Enable all badge notifications
enable_all_badges() {
    echo "✅ Enabling all badge notifications..."
    
    backup_badge_settings
    
    # Remove the restriction (delete the key)
    defaults delete com.apple.systempreferences AttentionPrefBundleIDs 2>/dev/null
    
    # Restart dock to apply changes
    killall Dock 2>/dev/null
    
    log_action "All badge notifications enabled"
    echo "✅ All badge notifications have been enabled"
}

# Apply selective badge policy
apply_selective_policy() {
    echo "🎯 Applying selective badge policy..."
    
    # For selective policy, we need to manage individual app notifications
    # This requires more complex notification management
    
    for app in "${BLOCKED_BADGE_APPS[@]}"; do
        echo "  🚫 Blocking badges for $app"
        # Kill app to clear current badge
        killall "$app" 2>/dev/null
    done
    
    # Set system preference
    defaults write com.apple.systempreferences AttentionPrefBundleIDs 0
    
    log_action "Selective badge policy applied"
    echo "✅ Selective badge policy has been applied"
}

# Monitor and auto-clear badges
monitor_badges() {
    echo "👁️  Starting badge monitoring (interval: ${AUTO_CLEAR_INTERVAL}s)..."
    
    while true; do
        if [[ "$BADGE_POLICY" == "disabled" ]]; then
            # Clear any badges that may have appeared
            defaults write com.apple.systempreferences AttentionPrefBundleIDs 0
            log_action "Auto-cleared badges during monitoring"
        fi
        
        sleep "$AUTO_CLEAR_INTERVAL"
    done
}

# Generate badge management report
generate_report() {
    local report_file="/tmp/macfleet_badge_report_$(date +%Y%m%d_%H%M%S).txt"
    
    {
        echo "MacFleet Badge Notification Report"
        echo "=================================="
        echo "Generated: $(date)"
        echo "Hostname: $(hostname)"
        echo "Policy: $BADGE_POLICY"
        echo ""
        
        echo "System Configuration:"
        echo "  AttentionPrefBundleIDs: $(defaults read com.apple.systempreferences AttentionPrefBundleIDs 2>/dev/null || echo 'not set')"
        echo ""
        
        echo "Application Status:"
        local apps=("Mail" "Messages" "Calendar" "Reminders" "App Store")
        for app in "${apps[@]}"; do
            if pgrep -x "$app" > /dev/null; then
                echo "  $app: Running"
            else
                echo "  $app: Not running"
            fi
        done
        
        echo ""
        echo "Recent Actions:"
        tail -10 "$LOG_FILE" 2>/dev/null || echo "No recent log entries"
        
    } > "$report_file"
    
    echo "📄 Badge management report generated: $report_file"
    log_action "Report generated: $report_file"
}

# Main function
main() {
    case "${1:-status}" in
        "disable")
            setup_directories
            load_config
            log_action "=== Badge Management: Disable All ==="
            disable_all_badges
            ;;
        "enable")
            setup_directories
            load_config
            log_action "=== Badge Management: Enable All ==="
            enable_all_badges
            ;;
        "policy")
            setup_directories
            load_config
            log_action "=== Badge Management: Apply Policy ==="
            apply_badge_policy
            ;;
        "monitor")
            setup_directories
            load_config
            log_action "=== Badge Management: Start Monitoring ==="
            monitor_badges
            ;;
        "report")
            setup_directories
            load_config
            generate_report
            ;;
        "status"|*)
            setup_directories
            load_config
            get_badge_status
            ;;
    esac
}

# Execute main function with parameters
main "$@"

Badge Notification Management Commands

Quick Reference

TaskCommand
Remove specific app badgedefaults write com.apple.systempreferences AttentionPrefBundleIDs 0 && killall AppName
Clear all dock badgesdefaults write com.apple.systempreferences AttentionPrefBundleIDs 0 && killall Dock
Check current settingdefaults read com.apple.systempreferences AttentionPrefBundleIDs
Reset to defaultdefaults delete com.apple.systempreferences AttentionPrefBundleIDs

Application-Specific Examples

# Common applications
defaults write com.apple.systempreferences AttentionPrefBundleIDs 0 && killall Mail
defaults write com.apple.systempreferences AttentionPrefBundleIDs 0 && killall Messages
defaults write com.apple.systempreferences AttentionPrefBundleIDs 0 && killall "App Store"
defaults write com.apple.systempreferences AttentionPrefBundleIDs 0 && killall Calendar

Troubleshooting

Common Issues

  1. Badges reappear after clearing

    • This is normal behavior; badges return when apps receive new notifications
    • Use monitoring scripts for persistent clearing
  2. Application won't restart

    • Some apps may need manual restart
    • Check if app is set to launch at login
  3. Dock doesn't update

    • Try forcing dock restart: killall Dock && sleep 2 && open /System/Library/CoreServices/Dock.app

Verification Commands

# Check if setting was applied
defaults read com.apple.systempreferences AttentionPrefBundleIDs

# List running applications
ps aux | grep -E "(Mail|Messages|Calendar)" | grep -v grep

# Monitor dock process
ps aux | grep Dock | grep -v grep

Important Notes

  • Temporary effect: Badge notifications will reappear when applications receive new notifications
  • System restart: Settings persist across system restarts
  • User experience: Consider user notification needs before enterprise-wide deployment
  • Application behavior: Some apps may require manual restart to apply changes
  • Testing recommended: Test on individual devices before fleet-wide deployment

Enterprise Deployment

For enterprise deployment, consider:

  1. Policy configuration - Define which applications should show badges
  2. User communication - Inform users about notification changes
  3. Monitoring setup - Implement automated badge clearing if required
  4. Backup procedures - Save original settings before making changes
  5. Rollback plan - Ability to restore original notification behavior