Tutorial

New updates and improvements to Macfleet.

Firewall Management for macOS

Implement enterprise-grade firewall management across your MacFleet deployment with automated security policies, advanced network protection, threat detection, and comprehensive compliance monitoring. This tutorial provides solutions for maintaining robust network security while ensuring regulatory compliance and operational efficiency.

Understanding macOS Firewall Management

macOS provides several firewall management tools and mechanisms:

  • Application Firewall - Built-in firewall that blocks incoming connections
  • socketfilterfw - Command-line tool for firewall configuration
  • pfctl - Packet Filter control utility (advanced filtering)
  • System Preferences - GUI firewall management interface
  • Configuration Profiles - MDM-based firewall policy deployment

Basic Firewall Operations

Enable Firewall

#!/bin/bash

# Enable macOS firewall
sudo defaults write /Library/Preferences/com.apple.alf globalstate -int 1

Disable Firewall

#!/bin/bash

# Disable macOS firewall
sudo defaults write /Library/Preferences/com.apple.alf globalstate -int 0

Check Firewall Status

#!/bin/bash

# Check firewall status
/usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate

Enterprise Firewall Management System

Comprehensive Firewall Management Tool

#!/bin/bash

# MacFleet Enterprise Firewall Management Tool
# Advanced network security and compliance monitoring

# Configuration
CONFIG_FILE="/etc/macfleet/firewall_policy.conf"
LOG_FILE="/var/log/macfleet_firewall.log"
RULES_DIR="/Library/MacFleet/FirewallRules"
AUDIT_LOG="/var/log/macfleet_firewall_audit.log"

# Create directories
mkdir -p "$(dirname "$CONFIG_FILE")" "$(dirname "$LOG_FILE")" "$RULES_DIR" "$(dirname "$AUDIT_LOG")"

# Default firewall policy
cat > "$CONFIG_FILE" 2>/dev/null << 'EOF' || true
# MacFleet Enterprise Firewall Management Policy
# Version: 2.0

# Firewall Enforcement Settings
ENFORCE_FIREWALL_ENABLED=true
AUTO_ENABLE_ON_VIOLATION=true
BLOCK_ALL_INCOMING_DEFAULT=true
ALLOW_SIGNED_APPS=true
STEALTH_MODE_ENABLED=true

# Application Control
WHITELIST_SYSTEM_APPS=true
REQUIRE_APP_SIGNATURES=true
BLOCK_UNSIGNED_APPS=true
LOG_ALL_CONNECTIONS=true
AUTO_BLOCK_SUSPICIOUS_APPS=true

# Network Security Policies
BLOCK_PRIVATE_NETWORKS=false
ALLOW_APPLE_SERVICES=true
BLOCK_P2P_CONNECTIONS=true
MONITOR_OUTBOUND_CONNECTIONS=true
RATE_LIMIT_CONNECTIONS=true

# Advanced Security Features
INTRUSION_DETECTION=true
THREAT_INTELLIGENCE_ENABLED=true
GEO_BLOCKING_ENABLED=false
DLP_INSPECTION=true
MALWARE_DETECTION=true

# Compliance and Monitoring
COMPLIANCE_MONITORING=true
SECURITY_BASELINE_ENFORCEMENT=true
AUTOMATED_REPORTING=true
REAL_TIME_ALERTS=true
INCIDENT_RESPONSE=true

# Policy Templates
DEFAULT_SECURITY_PROFILE="corporate_high"
ALLOWED_PORTS="22,53,80,443,993,995"
BLOCKED_COUNTRIES=""
WHITELIST_DOMAINS="*.apple.com,*.icloud.com"

# Maintenance Settings
AUTO_UPDATE_RULES=true
BACKUP_CONFIGURATIONS=true
LOG_RETENTION_DAYS=90
PERFORMANCE_MONITORING=true
EOF

# Source configuration
source "$CONFIG_FILE" 2>/dev/null || true

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

# Audit logging function
audit_log() {
    local action="$1"
    local result="$2"
    local details="$3"
    echo "$(date '+%Y-%m-%d %H:%M:%S') - ACTION:$action RESULT:$result DETAILS:$details USER:$(whoami)" >> "$AUDIT_LOG"
}

# Get current firewall status
get_firewall_status() {
    echo "=== Current Firewall Status ==="
    
    # Check global firewall state
    local global_state
    global_state=$(/usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate 2>/dev/null | grep -o "enabled\|disabled")
    
    echo "Global Firewall State: $global_state"
    
    # Check stealth mode
    local stealth_mode
    stealth_mode=$(/usr/libexec/ApplicationFirewall/socketfilterfw --getstealthmode 2>/dev/null | grep -o "enabled\|disabled")
    
    echo "Stealth Mode: $stealth_mode"
    
    # Check logging state
    local logging_state
    logging_state=$(/usr/libexec/ApplicationFirewall/socketfilterfw --getloggingmode 2>/dev/null | grep -o "enabled\|disabled")
    
    echo "Logging: $logging_state"
    
    # Check block all mode
    local block_all
    block_all=$(/usr/libexec/ApplicationFirewall/socketfilterfw --getblockall 2>/dev/null | grep -o "enabled\|disabled")
    
    echo "Block All Incoming: $block_all"
    
    # Check allowed applications
    echo -e "\nAllowed Applications:"
    /usr/libexec/ApplicationFirewall/socketfilterfw --listapps 2>/dev/null | grep "ALF" | head -10
    
    return 0
}

# Enable firewall with enterprise settings
enterprise_firewall_enable() {
    local security_profile="${1:-$DEFAULT_SECURITY_PROFILE}"
    
    echo "=== Enabling Enterprise Firewall ==="
    echo "Security Profile: $security_profile"
    
    # Enable global firewall
    log_action "Enabling global firewall"
    if sudo defaults write /Library/Preferences/com.apple.alf globalstate -int 1; then
        echo "āœ… Global firewall enabled"
        audit_log "FIREWALL_ENABLE" "SUCCESS" "Global firewall activated"
    else
        echo "āŒ Failed to enable global firewall"
        audit_log "FIREWALL_ENABLE" "FAILED" "Global firewall activation failed"
        return 1
    fi
    
    # Configure based on security profile
    case "$security_profile" in
        "corporate_high")
            configure_high_security_profile
            ;;
        "corporate_standard")
            configure_standard_security_profile
            ;;
        "developer")
            configure_developer_profile
            ;;
        "kiosk")
            configure_kiosk_profile
            ;;
        *)
            echo "Unknown security profile, using standard configuration"
            configure_standard_security_profile
            ;;
    esac
    
    # Enable stealth mode if required
    if [[ "$STEALTH_MODE_ENABLED" == "true" ]]; then
        enable_stealth_mode
    fi
    
    # Enable logging if required
    if [[ "$LOG_ALL_CONNECTIONS" == "true" ]]; then
        enable_firewall_logging
    fi
    
    # Apply application rules
    configure_application_rules
    
    echo "āœ… Enterprise firewall configuration completed"
    log_action "Enterprise firewall enabled with profile: $security_profile"
    
    return 0
}

# Configure high security profile
configure_high_security_profile() {
    echo "=== Configuring High Security Profile ==="
    
    # Block all incoming connections by default
    sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setblockall on 2>/dev/null
    
    # Enable stealth mode
    sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setstealthmode on 2>/dev/null
    
    # Disable automatic allow for signed apps
    sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setallowsigned off 2>/dev/null
    
    # Block all unsigned applications
    sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setallowsignedapp off 2>/dev/null
    
    echo "High security profile configured"
    log_action "High security firewall profile applied"
}

# Configure standard security profile
configure_standard_security_profile() {
    echo "=== Configuring Standard Security Profile ==="
    
    # Allow essential incoming connections
    sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setblockall off 2>/dev/null
    
    # Enable stealth mode
    sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setstealthmode on 2>/dev/null
    
    # Allow signed applications
    if [[ "$ALLOW_SIGNED_APPS" == "true" ]]; then
        sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setallowsigned on 2>/dev/null
    fi
    
    echo "Standard security profile configured"
    log_action "Standard security firewall profile applied"
}

# Configure developer profile
configure_developer_profile() {
    echo "=== Configuring Developer Profile ==="
    
    # Allow more permissive settings for development
    sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setblockall off 2>/dev/null
    sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setstealthmode off 2>/dev/null
    sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setallowsigned on 2>/dev/null
    sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setallowsignedapp on 2>/dev/null
    
    # Add common development tools
    local dev_apps=(
        "/Applications/Xcode.app"
        "/Applications/Visual Studio Code.app"
        "/Applications/Docker.app"
        "/usr/bin/ssh"
        "/usr/bin/python3"
    )
    
    for app in "${dev_apps[@]}"; do
        if [[ -e "$app" ]]; then
            sudo /usr/libexec/ApplicationFirewall/socketfilterfw --add "$app" 2>/dev/null
            sudo /usr/libexec/ApplicationFirewall/socketfilterfw --unblock "$app" 2>/dev/null
        fi
    done
    
    echo "Developer profile configured"
    log_action "Developer firewall profile applied"
}

# Configure kiosk profile
configure_kiosk_profile() {
    echo "=== Configuring Kiosk Profile ==="
    
    # Maximum security for kiosk devices
    sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setblockall on 2>/dev/null
    sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setstealthmode on 2>/dev/null
    sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setallowsigned off 2>/dev/null
    sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setallowsignedapp off 2>/dev/null
    
    # Only allow essential system applications
    local kiosk_apps=(
        "/System/Library/CoreServices/Finder.app"
        "/Applications/Safari.app"
    )
    
    for app in "${kiosk_apps[@]}"; do
        if [[ -e "$app" ]]; then
            sudo /usr/libexec/ApplicationFirewall/socketfilterfw --add "$app" 2>/dev/null
            sudo /usr/libexec/ApplicationFirewall/socketfilterfw --unblock "$app" 2>/dev/null
        fi
    done
    
    echo "Kiosk profile configured"
    log_action "Kiosk firewall profile applied"
}

# Enable stealth mode
enable_stealth_mode() {
    echo "=== Enabling Stealth Mode ==="
    
    if sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setstealthmode on 2>/dev/null; then
        echo "āœ… Stealth mode enabled"
        log_action "Stealth mode enabled"
        audit_log "STEALTH_MODE" "ENABLED" "Device hidden from network scans"
    else
        echo "āŒ Failed to enable stealth mode"
        log_action "FAILED: Stealth mode enable"
    fi
}

# Enable firewall logging
enable_firewall_logging() {
    echo "=== Enabling Firewall Logging ==="
    
    if sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setloggingmode on 2>/dev/null; then
        echo "āœ… Firewall logging enabled"
        log_action "Firewall logging enabled"
        audit_log "LOGGING" "ENABLED" "All firewall events will be logged"
    else
        echo "āŒ Failed to enable firewall logging"
        log_action "FAILED: Firewall logging enable"
    fi
}

# Configure application rules
configure_application_rules() {
    echo "=== Configuring Application Rules ==="
    
    # Essential system applications
    local essential_apps=(
        "/System/Library/CoreServices/Software Update.app"
        "/usr/sbin/sshd"
        "/usr/bin/ssh"
        "/Applications/App Store.app"
    )
    
    # Add and allow essential applications
    for app in "${essential_apps[@]}"; do
        if [[ -e "$app" ]]; then
            sudo /usr/libexec/ApplicationFirewall/socketfilterfw --add "$app" 2>/dev/null
            sudo /usr/libexec/ApplicationFirewall/socketfilterfw --unblock "$app" 2>/dev/null
            echo "āœ… Allowed: $(basename "$app")"
        fi
    done
    
    # Block known problematic applications
    local blocked_apps=(
        "/Applications/BitTorrent.app"
        "/Applications/P2P Client.app"
    )
    
    for app in "${blocked_apps[@]}"; do
        if [[ -e "$app" ]]; then
            sudo /usr/libexec/ApplicationFirewall/socketfilterfw --add "$app" 2>/dev/null
            sudo /usr/libexec/ApplicationFirewall/socketfilterfw --block "$app" 2>/dev/null
            echo "🚫 Blocked: $(basename "$app")"
        fi
    done
    
    log_action "Application firewall rules configured"
}

# Disable firewall (with safety checks)
enterprise_firewall_disable() {
    local force="${1:-false}"
    local reason="$2"
    
    echo "=== Disabling Enterprise Firewall ==="
    
    if [[ "$force" != "true" ]]; then
        echo "āš ļø  WARNING: Disabling firewall will reduce security"
        echo "Use 'force' parameter to override this warning"
        
        if [[ -z "$reason" ]]; then
            echo "āŒ Reason required for firewall disable operation"
            return 1
        fi
    fi
    
    # Log the disable action
    log_action "SECURITY WARNING: Firewall being disabled - Reason: ${reason:-Manual override}"
    audit_log "FIREWALL_DISABLE" "INITIATED" "Reason: ${reason:-Manual override}"
    
    # Disable global firewall
    if sudo defaults write /Library/Preferences/com.apple.alf globalstate -int 0; then
        echo "āœ… Global firewall disabled"
        audit_log "FIREWALL_DISABLE" "SUCCESS" "Global firewall deactivated"
        
        # Schedule re-enable if temporary
        if [[ "$reason" == *"temporary"* || "$reason" == *"maintenance"* ]]; then
            schedule_firewall_renable
        fi
        
        return 0
    else
        echo "āŒ Failed to disable global firewall"
        audit_log "FIREWALL_DISABLE" "FAILED" "Global firewall deactivation failed"
        return 1
    fi
}

# Schedule firewall re-enable
schedule_firewall_renable() {
    local renable_minutes="${1:-60}"  # Default 1 hour
    
    echo "šŸ•’ Firewall will be automatically re-enabled in $renable_minutes minutes"
    
    # Create background job to re-enable firewall
    (
        sleep $((renable_minutes * 60))
        log_action "Auto re-enabling firewall after maintenance window"
        enterprise_firewall_enable "corporate_standard"
    ) &
    
    local job_pid=$!
    echo "$job_pid" > "/tmp/macfleet_firewall_renable.pid"
    log_action "Firewall re-enable scheduled for $renable_minutes minutes (PID: $job_pid)"
}

# Check firewall compliance
check_firewall_compliance() {
    echo "=== Firewall Compliance Check ==="
    
    local compliance_issues=()
    local compliance_score=100
    
    # Check if firewall is enabled
    local firewall_state
    firewall_state=$(/usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate 2>/dev/null | grep -o "enabled\|disabled")
    
    if [[ "$firewall_state" != "enabled" ]]; then
        compliance_issues+=("Firewall not enabled")
        compliance_score=$((compliance_score - 30))
    fi
    
    # Check stealth mode
    if [[ "$STEALTH_MODE_ENABLED" == "true" ]]; then
        local stealth_state
        stealth_state=$(/usr/libexec/ApplicationFirewall/socketfilterfw --getstealthmode 2>/dev/null | grep -o "enabled\|disabled")
        
        if [[ "$stealth_state" != "enabled" ]]; then
            compliance_issues+=("Stealth mode not enabled")
            compliance_score=$((compliance_score - 15))
        fi
    fi
    
    # Check logging
    if [[ "$LOG_ALL_CONNECTIONS" == "true" ]]; then
        local logging_state
        logging_state=$(/usr/libexec/ApplicationFirewall/socketfilterfw --getloggingmode 2>/dev/null | grep -o "enabled\|disabled")
        
        if [[ "$logging_state" != "enabled" ]]; then
            compliance_issues+=("Firewall logging not enabled")
            compliance_score=$((compliance_score - 10))
        fi
    fi
    
    # Check for unauthorized applications
    local unauthorized_apps
    unauthorized_apps=$(/usr/libexec/ApplicationFirewall/socketfilterfw --listapps 2>/dev/null | grep -i "torrent\|p2p\|limewire" | wc -l)
    
    if [[ $unauthorized_apps -gt 0 ]]; then
        compliance_issues+=("Unauthorized applications detected: $unauthorized_apps")
        compliance_score=$((compliance_score - 20))
    fi
    
    # Report compliance status
    echo "Compliance Score: $compliance_score/100"
    
    if [[ ${#compliance_issues[@]} -eq 0 ]]; then
        echo "āœ… Firewall configuration is compliant"
        audit_log "COMPLIANCE_CHECK" "PASSED" "Score: $compliance_score/100"
        return 0
    else
        echo "āŒ Compliance issues found:"
        printf '  - %s\n' "${compliance_issues[@]}"
        audit_log "COMPLIANCE_CHECK" "FAILED" "Issues: ${#compliance_issues[@]} Score: $compliance_score/100"
        
        # Auto-remediate if enabled
        if [[ "$AUTO_ENABLE_ON_VIOLATION" == "true" ]]; then
            echo "šŸ”§ Auto-remediation enabled, fixing issues..."
            enterprise_firewall_enable "$DEFAULT_SECURITY_PROFILE"
        fi
        
        return 1
    fi
}

# Monitor firewall events
monitor_firewall_events() {
    echo "=== Starting Firewall Event Monitoring ==="
    
    local log_file="/var/log/appfirewall.log"
    
    if [[ ! -f "$log_file" ]]; then
        echo "āš ļø  Firewall log file not found. Enabling logging..."
        enable_firewall_logging
        sleep 2
    fi
    
    echo "Monitoring firewall events... Press Ctrl+C to stop"
    
    # Monitor firewall log in real-time
    tail -f "$log_file" 2>/dev/null | while read -r line; do
        if echo "$line" | grep -q "Deny\|Block"; then
            local app_name
            app_name=$(echo "$line" | awk '{print $8}' | cut -d'(' -f1)
            local action
            action=$(echo "$line" | awk '{print $6}')
            
            echo "🚫 $(date '+%H:%M:%S') - BLOCKED: $app_name ($action)"
            
            # Log security event
            log_action "SECURITY EVENT: $action - Application: $app_name"
            audit_log "FIREWALL_BLOCK" "DETECTED" "App: $app_name Action: $action"
            
            # Check for potential threats
            if echo "$app_name" | grep -i -E "(torrent|p2p|hack|crack|keygen)"; then
                echo "🚨 SECURITY ALERT: Potentially malicious application blocked: $app_name"
                log_action "SECURITY ALERT: Malicious app blocked - $app_name"
            fi
        fi
    done
}

# Generate firewall security report
generate_firewall_report() {
    local report_file="$RULES_DIR/firewall_report_$(date +%Y%m%d_%H%M%S).json"
    
    echo "=== Generating Firewall Security Report ==="
    
    # Get current firewall status
    local firewall_enabled="false"
    local stealth_enabled="false"
    local logging_enabled="false"
    local block_all_enabled="false"
    
    if /usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate 2>/dev/null | grep -q "enabled"; then
        firewall_enabled="true"
    fi
    
    if /usr/libexec/ApplicationFirewall/socketfilterfw --getstealthmode 2>/dev/null | grep -q "enabled"; then
        stealth_enabled="true"
    fi
    
    if /usr/libexec/ApplicationFirewall/socketfilterfw --getloggingmode 2>/dev/null | grep -q "enabled"; then
        logging_enabled="true"
    fi
    
    if /usr/libexec/ApplicationFirewall/socketfilterfw --getblockall 2>/dev/null | grep -q "enabled"; then
        block_all_enabled="true"
    fi
    
    # Count allowed/blocked applications
    local total_apps=0
    local allowed_apps=0
    local blocked_apps=0
    
    if command -v /usr/libexec/ApplicationFirewall/socketfilterfw >/dev/null; then
        total_apps=$(/usr/libexec/ApplicationFirewall/socketfilterfw --listapps 2>/dev/null | grep -c "ALF" || echo 0)
        allowed_apps=$(/usr/libexec/ApplicationFirewall/socketfilterfw --listapps 2>/dev/null | grep -c "ALLOW" || echo 0)
        blocked_apps=$(/usr/libexec/ApplicationFirewall/socketfilterfw --listapps 2>/dev/null | grep -c "BLOCK" || echo 0)
    fi
    
    # Analyze recent security events
    local security_events=0
    local blocked_connections=0
    
    if [[ -f "/var/log/appfirewall.log" ]]; then
        security_events=$(grep -c "$(date '+%Y-%m-%d')" "/var/log/appfirewall.log" 2>/dev/null || echo 0)
        blocked_connections=$(grep -c "Deny\|Block" "/var/log/appfirewall.log" 2>/dev/null || echo 0)
    fi
    
    # Create JSON report
    cat > "$report_file" << EOF
{
  "report_type": "firewall_security",
  "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
  "device_info": {
    "hostname": "$(hostname)",
    "os_version": "$(sw_vers -productVersion)",
    "serial_number": "$(system_profiler SPHardwareDataType | grep "Serial Number" | awk -F: '{print $2}' | xargs)"
  },
  "firewall_status": {
    "global_firewall_enabled": $firewall_enabled,
    "stealth_mode_enabled": $stealth_enabled,
    "logging_enabled": $logging_enabled,
    "block_all_incoming": $block_all_enabled
  },
  "application_rules": {
    "total_applications": $total_apps,
    "allowed_applications": $allowed_apps,
    "blocked_applications": $blocked_apps
  },
  "security_events": {
    "total_events_today": $security_events,
    "blocked_connections": $blocked_connections,
    "last_event": "$(tail -1 /var/log/appfirewall.log 2>/dev/null | awk '{print $1 " " $2 " " $3}' || echo 'N/A')"
  },
  "compliance_status": {
    "policy_compliant": $(check_firewall_compliance >/dev/null 2>&1 && echo true || echo false),
    "security_profile": "$DEFAULT_SECURITY_PROFILE",
    "auto_remediation": $AUTO_ENABLE_ON_VIOLATION
  },
  "recommendations": [
    $([ "$firewall_enabled" != "true" ] && echo '"Enable global firewall",' || echo "")
    $([ "$stealth_enabled" != "true" ] && echo '"Enable stealth mode",' || echo "")
    $([ "$logging_enabled" != "true" ] && echo '"Enable firewall logging",' || echo "")
    "Regular firewall rule review"
  ]
}
EOF
    
    echo "Firewall security report saved to: $report_file"
    log_action "Firewall security report generated: $report_file"
}

# Main function with argument handling
main() {
    log_action "=== MacFleet Firewall Management Tool Started ==="
    
    case "${1:-status}" in
        "enable")
            enterprise_firewall_enable "$2"
            ;;
        "disable")
            enterprise_firewall_disable "$2" "$3"
            ;;
        "status")
            get_firewall_status
            ;;
        "compliance")
            check_firewall_compliance
            ;;
        "monitor")
            monitor_firewall_events
            ;;
        "report")
            generate_firewall_report
            ;;
        "stealth")
            enable_stealth_mode
            ;;
        "logging")
            enable_firewall_logging
            ;;
        "profile")
            enterprise_firewall_enable "$2"
            ;;
        *)
            echo "MacFleet Enterprise Firewall Management Tool"
            echo "Usage: $0 [command] [options]"
            echo ""
            echo "Commands:"
            echo "  enable [profile]              - Enable firewall with security profile"
            echo "  disable [force] [reason]      - Disable firewall (requires reason)"
            echo "  status                        - Show current firewall status"
            echo "  compliance                    - Check firewall compliance"
            echo "  monitor                       - Monitor firewall events in real-time"
            echo "  report                        - Generate security report"
            echo "  stealth                       - Enable stealth mode"
            echo "  logging                       - Enable firewall logging"
            echo "  profile [name]                - Apply specific security profile"
            echo ""
            echo "Security Profiles:"
            echo "  corporate_high                - Maximum security for sensitive environments"
            echo "  corporate_standard            - Standard corporate security (default)"
            echo "  developer                     - Development-friendly settings"
            echo "  kiosk                         - Kiosk/public access security"
            ;;
    esac
    
    log_action "=== Firewall management operation completed ==="
}

# Execute main function
main "$@"

Advanced Firewall Management

Custom Firewall Rules Engine

#!/bin/bash

# Advanced firewall rules management
manage_custom_rules() {
    local action="$1"
    local rule_name="$2"
    local rule_definition="$3"
    
    echo "=== Custom Firewall Rules Management ==="
    
    local rules_file="$RULES_DIR/custom_rules.conf"
    
    case "$action" in
        "add")
            if [[ -z "$rule_name" || -z "$rule_definition" ]]; then
                echo "āŒ Rule name and definition required"
                return 1
            fi
            
            # Add rule to configuration
            echo "$rule_name:$rule_definition" >> "$rules_file"
            echo "āœ… Custom rule '$rule_name' added"
            log_action "Custom firewall rule added: $rule_name"
            
            # Apply rule immediately
            apply_custom_rule "$rule_definition"
            ;;
        "remove")
            if [[ -f "$rules_file" && -n "$rule_name" ]]; then
                grep -v "^$rule_name:" "$rules_file" > "$rules_file.tmp"
                mv "$rules_file.tmp" "$rules_file"
                echo "āœ… Custom rule '$rule_name' removed"
                log_action "Custom firewall rule removed: $rule_name"
            else
                echo "āŒ Rule '$rule_name' not found"
            fi
            ;;
        "list")
            if [[ -f "$rules_file" ]]; then
                echo "Custom firewall rules:"
                cat "$rules_file" | while IFS=':' read -r name definition; do
                    echo "  $name: $definition"
                done
            else
                echo "No custom rules configured"
            fi
            ;;
        "apply")
            apply_all_custom_rules
            ;;
        *)
            echo "Usage: manage_custom_rules [add|remove|list|apply] [rule_name] [definition]"
            ;;
    esac
}

# Apply custom firewall rule
apply_custom_rule() {
    local rule_definition="$1"
    
    # Parse rule definition and apply appropriate firewall command
    if echo "$rule_definition" | grep -q "block_app:"; then
        local app_path
        app_path=$(echo "$rule_definition" | cut -d':' -f2)
        sudo /usr/libexec/ApplicationFirewall/socketfilterfw --add "$app_path" 2>/dev/null
        sudo /usr/libexec/ApplicationFirewall/socketfilterfw --block "$app_path" 2>/dev/null
        echo "Applied block rule for: $app_path"
    elif echo "$rule_definition" | grep -q "allow_app:"; then
        local app_path
        app_path=$(echo "$rule_definition" | cut -d':' -f2)
        sudo /usr/libexec/ApplicationFirewall/socketfilterfw --add "$app_path" 2>/dev/null
        sudo /usr/libexec/ApplicationFirewall/socketfilterfw --unblock "$app_path" 2>/dev/null
        echo "Applied allow rule for: $app_path"
    fi
}

# Apply all custom rules
apply_all_custom_rules() {
    local rules_file="$RULES_DIR/custom_rules.conf"
    
    if [[ -f "$rules_file" ]]; then
        echo "Applying all custom firewall rules..."
        while IFS=':' read -r name definition; do
            if [[ -n "$name" && -n "$definition" ]]; then
                apply_custom_rule "$definition"
            fi
        done < "$rules_file"
        echo "āœ… All custom rules applied"
    else
        echo "No custom rules to apply"
    fi
}

# Example custom rules
create_example_rules() {
    manage_custom_rules "add" "block_bittorrent" "block_app:/Applications/BitTorrent.app"
    manage_custom_rules "add" "allow_docker" "allow_app:/Applications/Docker.app"
    manage_custom_rules "add" "allow_ssh" "allow_app:/usr/bin/ssh"
}

create_example_rules

Network Threat Detection

#!/bin/bash

# Advanced threat detection for firewall
detect_network_threats() {
    echo "=== Network Threat Detection ==="
    
    local threat_indicators=()
    local risk_score=0
    
    # Check for suspicious network connections
    echo "Scanning for suspicious network activity..."
    
    # Check for unusual outbound connections
    local unusual_connections
    unusual_connections=$(netstat -an | grep ESTABLISHED | grep -E ":(6667|6697|1337|31337|4444)" | wc -l)
    
    if [[ $unusual_connections -gt 0 ]]; then
        threat_indicators+=("Suspicious outbound connections detected: $unusual_connections")
        risk_score=$((risk_score + 20))
    fi
    
    # Check for high-risk processes with network access
    local risky_processes=()
    while IFS= read -r line; do
        if echo "$line" | grep -i -E "(torrent|p2p|hack|crack|keygen|bot|trojan)"; then
            risky_processes+=("$line")
            risk_score=$((risk_score + 15))
        fi
    done < <(lsof -i -n | awk '{print $1}' | sort -u)
    
    if [[ ${#risky_processes[@]} -gt 0 ]]; then
        threat_indicators+=("High-risk processes with network access: ${#risky_processes[@]}")
    fi
    
    # Check for firewall bypass attempts
    local bypass_attempts
    bypass_attempts=$(grep -c "socketfilterfw" /var/log/system.log 2>/dev/null || echo 0)
    
    if [[ $bypass_attempts -gt 10 ]]; then
        threat_indicators+=("Potential firewall bypass attempts: $bypass_attempts")
        risk_score=$((risk_score + 25))
    fi
    
    # Report threat assessment
    echo "Threat Risk Score: $risk_score/100"
    
    if [[ ${#threat_indicators[@]} -eq 0 ]]; then
        echo "āœ… No immediate threats detected"
        audit_log "THREAT_SCAN" "CLEAN" "Risk score: $risk_score"
        return 0
    else
        echo "āš ļø  Potential threats detected:"
        printf '  - %s\n' "${threat_indicators[@]}"
        
        # Log security alert
        log_action "SECURITY ALERT: Network threats detected - Risk score: $risk_score"
        audit_log "THREAT_SCAN" "THREATS_FOUND" "Count: ${#threat_indicators[@]} Risk: $risk_score"
        
        # Auto-remediation for high-risk scenarios
        if [[ $risk_score -gt 50 ]]; then
            echo "🚨 High risk detected - Enabling maximum security profile"
            configure_high_security_profile
        fi
        
        return 1
    fi
}

# Automated threat response
automated_threat_response() {
    local threat_level="$1"
    local threat_type="$2"
    
    echo "=== Automated Threat Response ==="
    echo "Threat Level: $threat_level"
    echo "Threat Type: $threat_type"
    
    case "$threat_level" in
        "high")
            # Maximum security measures
            echo "Implementing high-security measures..."
            sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setblockall on 2>/dev/null
            enable_stealth_mode
            log_action "HIGH THREAT RESPONSE: Maximum security enabled"
            ;;
        "medium")
            # Enhanced monitoring
            echo "Enabling enhanced monitoring..."
            enable_firewall_logging
            log_action "MEDIUM THREAT RESPONSE: Enhanced monitoring enabled"
            ;;
        "low")
            # Standard monitoring
            echo "Maintaining standard security posture..."
            log_action "LOW THREAT RESPONSE: Standard monitoring maintained"
            ;;
        *)
            echo "Unknown threat level: $threat_level"
            ;;
    esac
    
    # Send alert if configured
    if [[ "$REAL_TIME_ALERTS" == "true" ]]; then
        send_security_alert "$threat_level" "$threat_type"
    fi
}

# Send security alert
send_security_alert() {
    local threat_level="$1"
    local threat_type="$2"
    
    local alert_message="SECURITY ALERT: $threat_level level $threat_type detected on $(hostname) at $(date)"
    
    # Log the alert
    log_action "SECURITY ALERT SENT: $alert_message"
    
    # In a real implementation, this would send alerts via:
    # - Email to security team
    # - SIEM integration
    # - Slack/Teams notification
    # - MDM console alert
    
    echo "🚨 Security alert sent: $alert_message"
}

# Example usage:
# detect_network_threats
# automated_threat_response "high" "malware_communication"

Monitoring and Compliance

Real-time Security Monitoring

#!/bin/bash

# Comprehensive firewall security monitoring
start_security_monitoring() {
    echo "=== Starting Real-time Security Monitoring ==="
    
    local monitor_pid_file="$RULES_DIR/security_monitor.pid"
    
    # Store monitor PID
    echo $$ > "$monitor_pid_file"
    
    echo "Security monitoring started (PID: $$)"
    
    # Cleanup function
    cleanup() {
        echo "Stopping security monitor..."
        rm -f "$monitor_pid_file"
        exit 0
    }
    
    trap cleanup SIGTERM SIGINT
    
    while true; do
        # Check firewall compliance every 5 minutes
        if ! check_firewall_compliance >/dev/null 2>&1; then
            echo "āš ļø  Compliance violation detected at $(date)"
            
            if [[ "$AUTO_ENABLE_ON_VIOLATION" == "true" ]]; then
                echo "šŸ”§ Auto-remediation triggered"
                enterprise_firewall_enable "$DEFAULT_SECURITY_PROFILE" >/dev/null 2>&1
            fi
        fi
        
        # Run threat detection every 10 minutes
        if [[ $(($(date +%s) % 600)) -eq 0 ]]; then
            detect_network_threats >/dev/null 2>&1
        fi
        
        # Check for firewall configuration changes
        local current_config_hash
        current_config_hash=$(md5 -q /Library/Preferences/com.apple.alf.plist 2>/dev/null || echo "")
        
        if [[ -f "$RULES_DIR/last_config_hash" ]]; then
            local last_hash
            last_hash=$(cat "$RULES_DIR/last_config_hash")
            
            if [[ "$current_config_hash" != "$last_hash" ]]; then
                echo "šŸ”„ Firewall configuration changed at $(date)"
                log_action "Firewall configuration change detected"
                audit_log "CONFIG_CHANGE" "DETECTED" "Hash changed from $last_hash to $current_config_hash"
            fi
        fi
        
        echo "$current_config_hash" > "$RULES_DIR/last_config_hash"
        
        sleep 60  # Check every minute
    done
}

# Stop security monitoring
stop_security_monitoring() {
    local monitor_pid_file="$RULES_DIR/security_monitor.pid"
    
    if [[ -f "$monitor_pid_file" ]]; then
        local monitor_pid
        monitor_pid=$(cat "$monitor_pid_file")
        
        if kill -0 "$monitor_pid" 2>/dev/null; then
            kill "$monitor_pid"
            echo "Security monitor stopped (PID: $monitor_pid)"
            rm -f "$monitor_pid_file"
        else
            echo "Monitor process not found"
            rm -f "$monitor_pid_file"
        fi
    else
        echo "No monitor PID file found"
    fi
}

# Example usage:
# start_security_monitoring &
# stop_security_monitoring

Important Configuration Notes

macOS Firewall Architecture

  • Application Firewall - Controls incoming connections per application
  • Socket Filter Framework - Low-level packet filtering
  • Network Extension Framework - Modern content filtering
  • System Integrity Protection - Protects firewall configuration
  • Privacy Controls - User consent for network access

Enterprise Integration Points

  • MDM Configuration Profiles - Deploy firewall policies centrally
  • SIEM Integration - Forward security logs to monitoring systems
  • Compliance Frameworks - Support for SOC 2, ISO 27001, NIST
  • Incident Response - Automated threat detection and response

Best Practices for Enterprise

  1. Layered Security Approach

    • Combine application firewall with network segmentation
    • Implement endpoint detection and response (EDR)
    • Use network access control (NAC)
    • Deploy intrusion detection systems (IDS)
  2. Policy Management

    • Define clear security baselines
    • Regularly review and update firewall rules
    • Implement change management processes
    • Test security policies regularly
  3. Monitoring and Response

    • Enable comprehensive logging
    • Monitor for configuration changes
    • Implement automated threat detection
    • Establish incident response procedures
  4. Compliance and Auditing

    • Generate regular compliance reports
    • Maintain audit trails
    • Document security exceptions
    • Conduct periodic security assessments

Troubleshooting Common Issues

  • Permission errors - Ensure admin privileges for firewall modifications
  • Application connectivity - Review firewall rules for blocked applications
  • Performance impact - Monitor CPU usage with extensive logging enabled
  • Configuration conflicts - Check for conflicting MDM profiles
  • Log file growth - Implement log rotation and archival

Remember to test firewall configurations thoroughly in a controlled environment before deploying across your entire MacFleet to ensure business continuity while maintaining security.

Finder Customization Management on macOS

Customize and manage Finder preferences across your MacFleet devices using command-line tools. This tutorial covers desktop display options, file visibility settings, interface customization, and enterprise-wide Finder configuration management.

Understanding macOS Finder Customization

Finder is the default file manager for macOS, and its behavior can be extensively customized using the defaults command. Key areas of customization include:

  • Desktop Display - Control what appears on desktop
  • File Visibility - Show/hide files and extensions
  • Interface Elements - Status bars, path displays, and warnings
  • Sorting Behavior - How files and folders are organized

Desktop Display Management

Show Hard Disks on Desktop

#!/bin/bash

# Enable hard disk display on desktop
echo "šŸ–„ļø Enabling hard disk display on desktop..."

defaults write com.apple.finder ShowHardDrivesOnDesktop -bool true
killall Finder

if [ $? -eq 0 ]; then
    echo "āœ… Hard disks will now appear on desktop"
else
    echo "āŒ Failed to update hard disk display setting"
    exit 1
fi

Show External Hard Drives on Desktop

#!/bin/bash

# Enable external drive display on desktop
echo "šŸ’¾ Enabling external drive display on desktop..."

defaults write com.apple.finder ShowExternalHardDrivesOnDesktop -bool true
killall Finder

if [ $? -eq 0 ]; then
    echo "āœ… External drives will now appear on desktop"
else
    echo "āŒ Failed to update external drive display setting"
    exit 1
fi

Show Removable Media on Desktop

#!/bin/bash

# Enable removable media display on desktop
echo "šŸ’æ Enabling removable media display on desktop..."

defaults write com.apple.finder ShowRemovableMediaOnDesktop -bool true
killall Finder

if [ $? -eq 0 ]; then
    echo "āœ… Removable media (CDs, DVDs, iPods) will now appear on desktop"
else
    echo "āŒ Failed to update removable media display setting"
    exit 1
fi

File Visibility Configuration

Show All Filename Extensions

#!/bin/bash

# Enable display of all file extensions
echo "šŸ“„ Enabling display of all file extensions..."

defaults write NSGlobalDomain AppleShowAllExtensions -bool true
killall Finder

if [ $? -eq 0 ]; then
    echo "āœ… All file extensions will now be visible"
    echo "ā„¹ļø  Files like 'document.txt' and 'app.app' will show their extensions"
else
    echo "āŒ Failed to update file extension display setting"
    exit 1
fi

Show Hidden Files

#!/bin/bash

# Enable display of hidden files
echo "šŸ‘ļø Enabling display of hidden files..."

defaults write com.apple.finder AppleShowAllFiles -bool true
killall Finder

if [ $? -eq 0 ]; then
    echo "āœ… Hidden files will now be visible in Finder"
    echo "āš ļø  Warning: Hidden files contain system data - modify with caution"
else
    echo "āŒ Failed to update hidden file display setting"
    exit 1
fi

Interface Enhancement Settings

Enable Status Bar

#!/bin/bash

# Enable Finder status bar
echo "šŸ“Š Enabling Finder status bar..."

defaults write com.apple.finder ShowStatusBar -bool true
killall Finder

if [ $? -eq 0 ]; then
    echo "āœ… Status bar enabled - shows item count and available space"
else
    echo "āŒ Failed to enable status bar"
    exit 1
fi

Show Full Path in Title Bar

#!/bin/bash

# Enable full path display in title bar
echo "šŸ›¤ļø Enabling full path display in title bar..."

defaults write com.apple.finder _FXShowPosixPathInTitle -bool true
killall Finder

if [ $? -eq 0 ]; then
    echo "āœ… Full file paths will now appear in Finder title bar"
else
    echo "āŒ Failed to enable path display in title bar"
    exit 1
fi

Keep Folders on Top When Sorting

#!/bin/bash

# Enable folders-first sorting
echo "šŸ“ Enabling folders-first sorting..."

defaults write com.apple.finder _FXSortFoldersFirst -bool true
killall Finder

if [ $? -eq 0 ]; then
    echo "āœ… Folders will now appear before files when sorting by name"
else
    echo "āŒ Failed to update folder sorting preference"
    exit 1
fi

Security and Warning Settings

Enable Extension Change Warning

#!/bin/bash

# Enable warning before changing file extensions
echo "āš ļø Enabling file extension change warning..."

defaults write com.apple.finder FXEnableExtensionChangeWarning -bool true
killall Finder

if [ $? -eq 0 ]; then
    echo "āœ… Warning dialog will appear before changing file extensions"
else
    echo "āŒ Failed to enable extension change warning"
    exit 1
fi

Enable iCloud Drive Removal Warning

#!/bin/bash

# Enable warning before removing items from iCloud Drive
echo "ā˜ļø Enabling iCloud Drive removal warning..."

defaults write com.apple.finder FXEnableRemoveFromICloudDriveWarning -bool true
killall Finder

if [ $? -eq 0 ]; then
    echo "āœ… Warning dialog will appear before removing items from iCloud Drive"
else
    echo "āŒ Failed to enable iCloud Drive removal warning"
    exit 1
fi

Expand Information Window Panes

#!/bin/bash

# Configure information window panes to be expanded by default
echo "šŸ” Configuring information window panes..."

defaults write com.apple.finder FXInfoPanesExpanded -dict \
    General -bool true \
    OpenWith -bool true \
    Privileges -bool true

killall Finder

if [ $? -eq 0 ]; then
    echo "āœ… General, Open With, and Privileges panes will be expanded by default"
else
    echo "āŒ Failed to configure information window panes"
    exit 1
fi

Enterprise Finder Configuration Script

#!/bin/bash

# MacFleet Finder Customization Tool
# Standardize Finder preferences across fleet devices

# Configuration
LOG_FILE="/var/log/macfleet_finder.log"
BACKUP_DIR="/var/backups/macfleet/finder"
CONFIG_FILE="/etc/macfleet/finder_config.plist"

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

# Create backup directory
setup_directories() {
    if [[ ! -d "$BACKUP_DIR" ]]; then
        mkdir -p "$BACKUP_DIR"
        log_action "Created backup directory: $BACKUP_DIR"
    fi
    
    if [[ ! -d "$(dirname "$CONFIG_FILE")" ]]; then
        mkdir -p "$(dirname "$CONFIG_FILE")"
        log_action "Created configuration directory"
    fi
}

# Backup current Finder preferences
backup_current_settings() {
    local backup_file="$BACKUP_DIR/finder_backup_$(date +%Y%m%d_%H%M%S).plist"
    
    echo "šŸ“¦ Creating backup of current Finder settings..."
    
    # Export current Finder preferences
    defaults export com.apple.finder "$backup_file" 2>/dev/null
    
    if [ $? -eq 0 ]; then
        echo "āœ… Backup created: $backup_file"
        log_action "Backup created: $backup_file"
    else
        echo "āš ļø  Warning: Could not create backup"
        log_action "Warning: Backup creation failed"
    fi
}

# Apply enterprise Finder configuration
apply_finder_configuration() {
    echo "šŸ”§ Applying MacFleet Finder configuration..."
    log_action "Starting Finder configuration deployment"
    
    # Desktop display settings
    echo "Configuring desktop display options..."
    defaults write com.apple.finder ShowHardDrivesOnDesktop -bool true
    defaults write com.apple.finder ShowExternalHardDrivesOnDesktop -bool true
    defaults write com.apple.finder ShowRemovableMediaOnDesktop -bool true
    
    # File visibility settings
    echo "Configuring file visibility options..."
    defaults write NSGlobalDomain AppleShowAllExtensions -bool true
    defaults write com.apple.finder _FXSortFoldersFirst -bool true
    
    # Interface enhancements
    echo "Configuring interface elements..."
    defaults write com.apple.finder ShowStatusBar -bool true
    defaults write com.apple.finder _FXShowPosixPathInTitle -bool true
    
    # Security warnings
    echo "Configuring security warnings..."
    defaults write com.apple.finder FXEnableExtensionChangeWarning -bool true
    defaults write com.apple.finder FXEnableRemoveFromICloudDriveWarning -bool true
    
    # Information window configuration
    echo "Configuring information window panes..."
    defaults write com.apple.finder FXInfoPanesExpanded -dict \
        General -bool true \
        OpenWith -bool true \
        Privileges -bool true
    
    # Restart Finder to apply changes
    echo "Restarting Finder to apply changes..."
    killall Finder
    
    if [ $? -eq 0 ]; then
        echo "āœ… Finder configuration applied successfully"
        log_action "Finder configuration deployment completed successfully"
    else
        echo "āŒ Failed to restart Finder"
        log_action "Error: Failed to restart Finder"
        return 1
    fi
}

# Verify configuration deployment
verify_configuration() {
    echo "šŸ” Verifying Finder configuration..."
    
    local verification_passed=true
    
    # Check desktop display settings
    if [[ "$(defaults read com.apple.finder ShowHardDrivesOnDesktop 2>/dev/null)" == "1" ]]; then
        echo "āœ… Hard drives on desktop: Enabled"
    else
        echo "āŒ Hard drives on desktop: Failed"
        verification_passed=false
    fi
    
    if [[ "$(defaults read com.apple.finder ShowExternalHardDrivesOnDesktop 2>/dev/null)" == "1" ]]; then
        echo "āœ… External drives on desktop: Enabled"
    else
        echo "āŒ External drives on desktop: Failed"
        verification_passed=false
    fi
    
    # Check file visibility
    if [[ "$(defaults read NSGlobalDomain AppleShowAllExtensions 2>/dev/null)" == "1" ]]; then
        echo "āœ… Show all extensions: Enabled"
    else
        echo "āŒ Show all extensions: Failed"
        verification_passed=false
    fi
    
    # Check interface elements
    if [[ "$(defaults read com.apple.finder ShowStatusBar 2>/dev/null)" == "1" ]]; then
        echo "āœ… Status bar: Enabled"
    else
        echo "āŒ Status bar: Failed"
        verification_passed=false
    fi
    
    if $verification_passed; then
        echo "āœ… All Finder configurations verified successfully"
        log_action "Configuration verification passed"
        return 0
    else
        echo "āŒ Some configurations failed verification"
        log_action "Configuration verification failed"
        return 1
    fi
}

# Generate configuration report
generate_report() {
    local report_file="/tmp/finder_config_report_$(date +%Y%m%d_%H%M%S).txt"
    
    {
        echo "MacFleet Finder Configuration Report"
        echo "Generated: $(date)"
        echo "Hostname: $(hostname)"
        echo "User: $(whoami)"
        echo "======================================"
        echo ""
        
        echo "Desktop Display Settings:"
        echo "Hard drives on desktop: $(defaults read com.apple.finder ShowHardDrivesOnDesktop 2>/dev/null || echo 'Not set')"
        echo "External drives on desktop: $(defaults read com.apple.finder ShowExternalHardDrivesOnDesktop 2>/dev/null || echo 'Not set')"
        echo "Removable media on desktop: $(defaults read com.apple.finder ShowRemovableMediaOnDesktop 2>/dev/null || echo 'Not set')"
        echo ""
        
        echo "File Visibility Settings:"
        echo "Show all extensions: $(defaults read NSGlobalDomain AppleShowAllExtensions 2>/dev/null || echo 'Not set')"
        echo "Show hidden files: $(defaults read com.apple.finder AppleShowAllFiles 2>/dev/null || echo 'Not set')"
        echo "Folders first: $(defaults read com.apple.finder _FXSortFoldersFirst 2>/dev/null || echo 'Not set')"
        echo ""
        
        echo "Interface Settings:"
        echo "Status bar: $(defaults read com.apple.finder ShowStatusBar 2>/dev/null || echo 'Not set')"
        echo "Path in title: $(defaults read com.apple.finder _FXShowPosixPathInTitle 2>/dev/null || echo 'Not set')"
        echo ""
        
        echo "Security Settings:"
        echo "Extension change warning: $(defaults read com.apple.finder FXEnableExtensionChangeWarning 2>/dev/null || echo 'Not set')"
        echo "iCloud removal warning: $(defaults read com.apple.finder FXEnableRemoveFromICloudDriveWarning 2>/dev/null || echo 'Not set')"
        
    } > "$report_file"
    
    echo "šŸ“Š Configuration report saved to: $report_file"
    log_action "Configuration report generated: $report_file"
}

# Restore from backup
restore_from_backup() {
    local backup_file="$1"
    
    if [[ ! -f "$backup_file" ]]; then
        echo "āŒ Backup file not found: $backup_file"
        return 1
    fi
    
    echo "šŸ”„ Restoring Finder settings from backup..."
    
    # Import backup
    defaults import com.apple.finder "$backup_file"
    
    if [ $? -eq 0 ]; then
        echo "āœ… Settings restored from backup"
        killall Finder
        log_action "Settings restored from backup: $backup_file"
    else
        echo "āŒ Failed to restore from backup"
        log_action "Error: Failed to restore from backup: $backup_file"
        return 1
    fi
}

# Reset to defaults
reset_to_defaults() {
    echo "šŸ”„ Resetting Finder to default settings..."
    
    # Remove custom settings
    defaults delete com.apple.finder ShowHardDrivesOnDesktop 2>/dev/null
    defaults delete com.apple.finder ShowExternalHardDrivesOnDesktop 2>/dev/null
    defaults delete com.apple.finder ShowRemovableMediaOnDesktop 2>/dev/null
    defaults delete NSGlobalDomain AppleShowAllExtensions 2>/dev/null
    defaults delete com.apple.finder AppleShowAllFiles 2>/dev/null
    defaults delete com.apple.finder ShowStatusBar 2>/dev/null
    defaults delete com.apple.finder _FXShowPosixPathInTitle 2>/dev/null
    defaults delete com.apple.finder _FXSortFoldersFirst 2>/dev/null
    defaults delete com.apple.finder FXEnableExtensionChangeWarning 2>/dev/null
    defaults delete com.apple.finder FXEnableRemoveFromICloudDriveWarning 2>/dev/null
    defaults delete com.apple.finder FXInfoPanesExpanded 2>/dev/null
    
    killall Finder
    
    echo "āœ… Finder reset to default settings"
    log_action "Finder reset to default settings"
}

# Main execution function
main() {
    local action="${1:-deploy}"
    
    log_action "=== MacFleet Finder Customization Started ==="
    
    setup_directories
    
    case "$action" in
        "deploy")
            backup_current_settings
            apply_finder_configuration
            verify_configuration
            generate_report
            ;;
        "verify")
            verify_configuration
            ;;
        "report")
            generate_report
            ;;
        "restore")
            if [[ -n "$2" ]]; then
                restore_from_backup "$2"
            else
                echo "āŒ Please specify backup file path"
                echo "Usage: $0 restore /path/to/backup.plist"
                exit 1
            fi
            ;;
        "reset")
            backup_current_settings
            reset_to_defaults
            ;;
        *)
            echo "Usage: $0 [deploy|verify|report|restore|reset]"
            echo ""
            echo "Commands:"
            echo "  deploy  - Apply MacFleet Finder configuration (default)"
            echo "  verify  - Verify current configuration"
            echo "  report  - Generate configuration report"
            echo "  restore - Restore from backup file"
            echo "  reset   - Reset to default settings"
            exit 1
            ;;
    esac
    
    log_action "=== MacFleet Finder Customization Completed ==="
}

# Execute main function
main "$@"

Configuration Reference

SettingCommandDescription
Hard drives on desktopShowHardDrivesOnDesktopDisplay internal drives on desktop
External drives on desktopShowExternalHardDrivesOnDesktopDisplay external drives on desktop
Removable media on desktopShowRemovableMediaOnDesktopDisplay CDs, DVDs, iPods on desktop
Show all extensionsAppleShowAllExtensionsDisplay file extensions for all files
Show hidden filesAppleShowAllFilesDisplay normally hidden system files
Status barShowStatusBarShow item count and disk space
Path in title_FXShowPosixPathInTitleDisplay full path in window title
Folders first_FXSortFoldersFirstSort folders before files
Extension warningFXEnableExtensionChangeWarningWarn before changing extensions
iCloud warningFXEnableRemoveFromICloudDriveWarningWarn before iCloud removal

Quick Reference Commands

Enable All Desktop Items

# Show all desktop items
defaults write com.apple.finder ShowHardDrivesOnDesktop -bool true
defaults write com.apple.finder ShowExternalHardDrivesOnDesktop -bool true
defaults write com.apple.finder ShowRemovableMediaOnDesktop -bool true
killall Finder

Enable Full Visibility

# Maximum file visibility
defaults write NSGlobalDomain AppleShowAllExtensions -bool true
defaults write com.apple.finder AppleShowAllFiles -bool true
defaults write com.apple.finder ShowStatusBar -bool true
killall Finder

Enable All Security Warnings

# Enable all security warnings
defaults write com.apple.finder FXEnableExtensionChangeWarning -bool true
defaults write com.apple.finder FXEnableRemoveFromICloudDriveWarning -bool true
killall Finder

Troubleshooting

Finder Not Restarting

# Force restart Finder
sudo pkill -f Finder
sleep 2
open /System/Library/CoreServices/Finder.app

Settings Not Applying

# Clear Finder cache and restart
sudo rm -rf ~/Library/Caches/com.apple.finder
killall Finder

Verify Settings Applied

# Check specific setting
defaults read com.apple.finder ShowStatusBar

# List all Finder settings
defaults read com.apple.finder

Security Considerations

  • Hidden files contain system data - modify with caution
  • File extensions help identify file types - consider security implications
  • Desktop items may clutter interface in shared environments
  • Test changes on individual devices before fleet deployment
  • Create backups before applying configuration changes

Important Notes

  • Changes require Finder restart to take effect
  • Some settings apply system-wide (NSGlobalDomain)
  • User-specific settings don't affect other accounts
  • Administrative privileges may be required for system-wide deployment
  • Backup current settings before making changes for easy restoration

Find My Mac Security Management and Compliance

Ensure enterprise security compliance by monitoring and managing Find My Mac status across your MacFleet devices. This tutorial covers security auditing, Apple ID verification, automated compliance reporting, and enterprise security policy enforcement.

Understanding Find My Mac Security

Find My Mac is Apple's built-in device location and security service that provides:

  • Device Location Tracking - Real-time location services for lost or stolen devices
  • Remote Lock and Wipe - Secure device data remotely
  • Activation Lock - Prevents unauthorized device reactivation
  • Security Integration - Works with Apple ID and iCloud services

Basic Find My Mac Status Check

Simple Status Verification

#!/bin/bash

# Basic Find My Mac status check
fmmToken=$(/usr/sbin/nvram -x -p | /usr/bin/grep fmm-mobileme-token-FMM)

if [ -z "$fmmToken" ]; then
    echo "Find My Mac is disabled"
else
    echo "Find My Mac is enabled"
fi

Enhanced Status Check with Details

#!/bin/bash

# Enhanced Find My Mac verification
check_find_my_mac_basic() {
    echo "=== Find My Mac Status Check ==="
    
    # Check for Find My Mac token
    local fmm_token
    fmm_token=$(/usr/sbin/nvram -x -p | /usr/bin/grep fmm-mobileme-token-FMM 2>/dev/null)
    
    if [ -z "$fmm_token" ]; then
        echo "āŒ Find My Mac: DISABLED"
        return 1
    else
        echo "āœ… Find My Mac: ENABLED"
        
        # Extract additional details if available
        echo "Token found in NVRAM"
        return 0
    fi
}

# Execute the check
check_find_my_mac_basic

Enterprise Security Management Script

#!/bin/bash

# MacFleet Find My Mac Security Management
# Comprehensive security auditing and compliance monitoring

# Configuration
LOG_FILE="/var/log/macfleet_security.log"
REPORT_DIR="/var/reports/security"
COMPLIANCE_DIR="/var/compliance"
TEMP_DIR="/tmp/macfleet_security"

# Security policies configuration
REQUIRE_FIND_MY_MAC=true
REQUIRE_APPLE_ID=true
REQUIRE_ACTIVATION_LOCK=true
MAX_OFFLINE_DAYS=30

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

# Create necessary directories
setup_directories() {
    for dir in "$REPORT_DIR" "$COMPLIANCE_DIR" "$TEMP_DIR"; do
        if [[ ! -d "$dir" ]]; then
            mkdir -p "$dir"
            log_action "Created directory: $dir"
        fi
    done
}

# Check Find My Mac status with detailed analysis
check_find_my_mac_status() {
    log_action "Checking Find My Mac status"
    
    local status_report="$TEMP_DIR/fmm_status.json"
    
    # Initialize status object
    cat > "$status_report" << EOF
{
    "timestamp": "$(date -Iseconds)",
    "hostname": "$(hostname)",
    "find_my_mac": {
        "enabled": false,
        "token_present": false,
        "activation_lock": false,
        "apple_id_signed_in": false
    },
    "compliance": {
        "status": "non_compliant",
        "issues": []
    }
}
EOF

    # Check for Find My Mac token in NVRAM
    local fmm_token
    fmm_token=$(/usr/sbin/nvram -x -p | /usr/bin/grep fmm-mobileme-token-FMM 2>/dev/null)
    
    if [[ -n "$fmm_token" ]]; then
        log_action "āœ… Find My Mac token found in NVRAM"
        
        # Update JSON status
        /usr/bin/python3 -c "
import json
with open('$status_report', 'r') as f:
    data = json.load(f)
data['find_my_mac']['enabled'] = True
data['find_my_mac']['token_present'] = True
with open('$status_report', 'w') as f:
    json.dump(data, f, indent=2)
"
        echo "enabled"
    else
        log_action "āŒ Find My Mac not enabled - no token found"
        
        # Add compliance issue
        /usr/bin/python3 -c "
import json
with open('$status_report', 'r') as f:
    data = json.load(f)
data['compliance']['issues'].append('Find My Mac not enabled')
with open('$status_report', 'w') as f:
    json.dump(data, f, indent=2)
"
        echo "disabled"
    fi
}

# Check Apple ID sign-in status
check_apple_id_status() {
    log_action "Checking Apple ID sign-in status"
    
    # Check if user is signed into iCloud
    local icloud_account
    icloud_account=$(defaults read MobileMeAccounts Accounts 2>/dev/null | grep -c AccountID || echo "0")
    
    if [[ "$icloud_account" -gt 0 ]]; then
        log_action "āœ… Apple ID signed in to iCloud"
        
        # Get Apple ID details (masked for privacy)
        local apple_id_info
        apple_id_info=$(defaults read MobileMeAccounts Accounts 2>/dev/null | grep AccountID | head -1 | sed 's/.*= "\(.*\)";/\1/' | sed 's/\(.*@\)\(.*\)/\1***/g')
        log_action "Apple ID: $apple_id_info"
        
        return 0
    else
        log_action "āŒ No Apple ID signed in"
        return 1
    fi
}

# Check system integrity and security settings
check_system_security() {
    log_action "Performing system security audit"
    
    local security_report="$TEMP_DIR/security_audit.json"
    
    cat > "$security_report" << EOF
{
    "timestamp": "$(date -Iseconds)",
    "hostname": "$(hostname)",
    "security_audit": {
        "sip_status": "unknown",
        "gatekeeper_status": "unknown",
        "filevault_status": "unknown",
        "firewall_status": "unknown",
        "secure_boot": "unknown"
    }
}
EOF

    # Check System Integrity Protection (SIP)
    local sip_status
    sip_status=$(csrutil status 2>/dev/null | grep -i enabled && echo "enabled" || echo "disabled")
    log_action "SIP Status: $sip_status"
    
    # Check Gatekeeper
    local gatekeeper_status
    gatekeeper_status=$(spctl --status 2>/dev/null | grep -i enabled && echo "enabled" || echo "disabled")
    log_action "Gatekeeper Status: $gatekeeper_status"
    
    # Check FileVault
    local filevault_status
    filevault_status=$(fdesetup status 2>/dev/null | grep -i "on" && echo "enabled" || echo "disabled")
    log_action "FileVault Status: $filevault_status"
    
    # Check Firewall
    local firewall_status
    firewall_status=$(/usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate 2>/dev/null | grep -i enabled && echo "enabled" || echo "disabled")
    log_action "Firewall Status: $firewall_status"
    
    # Update security report
    /usr/bin/python3 -c "
import json
with open('$security_report', 'r') as f:
    data = json.load(f)
data['security_audit']['sip_status'] = '$sip_status'
data['security_audit']['gatekeeper_status'] = '$gatekeeper_status'
data['security_audit']['filevault_status'] = '$filevault_status'
data['security_audit']['firewall_status'] = '$firewall_status'
with open('$security_report', 'w') as f:
    json.dump(data, f, indent=2)
"

    echo "$security_report"
}

# Check activation lock status
check_activation_lock() {
    log_action "Checking Activation Lock status"
    
    # Check if device has activation lock enabled
    # This requires checking with Apple's servers or MDM enrollment
    local activation_lock_status="unknown"
    
    # For enterprise devices, check MDM enrollment
    if profiles -P 2>/dev/null | grep -q "com.apple.mdm"; then
        log_action "āœ… Device is MDM enrolled"
        activation_lock_status="mdm_managed"
    else
        log_action "āš ļø  Device not MDM enrolled"
        activation_lock_status="not_managed"
    fi
    
    # Check for DEP/ABM enrollment
    if profiles -e 2>/dev/null | grep -q "DEP"; then
        log_action "āœ… Device is DEP/ABM enrolled"
        activation_lock_status="dep_enrolled"
    fi
    
    echo "$activation_lock_status"
}

# Generate comprehensive security report
generate_security_report() {
    local report_timestamp
    report_timestamp=$(date '+%Y%m%d_%H%M%S')
    local report_file="$REPORT_DIR/security_report_$report_timestamp.json"
    
    log_action "Generating comprehensive security report: $report_file"
    
    # Get system information
    local os_version
    local serial_number
    local hardware_uuid
    os_version=$(sw_vers -productVersion)
    serial_number=$(system_profiler SPHardwareDataType | grep "Serial Number" | awk '{print $4}')
    hardware_uuid=$(system_profiler SPHardwareDataType | grep "Hardware UUID" | awk '{print $3}')
    
    # Compile comprehensive report
    cat > "$report_file" << EOF
{
    "report_metadata": {
        "timestamp": "$(date -Iseconds)",
        "report_version": "1.0",
        "generator": "MacFleet Security Audit"
    },
    "device_info": {
        "hostname": "$(hostname)",
        "serial_number": "$serial_number",
        "hardware_uuid": "$hardware_uuid",
        "os_version": "$os_version",
        "model": "$(system_profiler SPHardwareDataType | grep "Model Name" | awk -F': ' '{print $2}')"
    },
    "security_status": {
        "find_my_mac": {
            "enabled": $(check_find_my_mac_status >/dev/null && echo "true" || echo "false"),
            "compliance": $([ "$REQUIRE_FIND_MY_MAC" = true ] && check_find_my_mac_status >/dev/null && echo "true" || echo "false")
        },
        "apple_id": {
            "signed_in": $(check_apple_id_status >/dev/null && echo "true" || echo "false"),
            "compliance": $([ "$REQUIRE_APPLE_ID" = true ] && check_apple_id_status >/dev/null && echo "true" || echo "false")
        },
        "activation_lock": {
            "status": "$(check_activation_lock)",
            "compliance": $([ "$REQUIRE_ACTIVATION_LOCK" = true ] && echo "true" || echo "false")
        }
    },
    "compliance_summary": {
        "overall_status": "$(calculate_compliance_status)",
        "required_actions": $(generate_required_actions),
        "risk_level": "$(calculate_risk_level)"
    }
}
EOF

    log_action "Security report generated: $report_file"
    echo "$report_file"
}

# Calculate overall compliance status
calculate_compliance_status() {
    local fmm_status
    local apple_id_status
    local issues=0
    
    fmm_status=$(check_find_my_mac_status)
    if [[ "$REQUIRE_FIND_MY_MAC" = true && "$fmm_status" != "enabled" ]]; then
        ((issues++))
    fi
    
    if ! check_apple_id_status >/dev/null 2>&1; then
        if [[ "$REQUIRE_APPLE_ID" = true ]]; then
            ((issues++))
        fi
    fi
    
    if [[ $issues -eq 0 ]]; then
        echo "compliant"
    elif [[ $issues -le 2 ]]; then
        echo "partially_compliant"
    else
        echo "non_compliant"
    fi
}

# Generate required actions for compliance
generate_required_actions() {
    local actions=()
    
    if [[ "$REQUIRE_FIND_MY_MAC" = true ]] && [[ "$(check_find_my_mac_status)" != "enabled" ]]; then
        actions+=("\"Enable Find My Mac in System Preferences\"")
    fi
    
    if [[ "$REQUIRE_APPLE_ID" = true ]] && ! check_apple_id_status >/dev/null 2>&1; then
        actions+=("\"Sign in with Apple ID in System Preferences\"")
    fi
    
    if [[ ${#actions[@]} -eq 0 ]]; then
        echo "[]"
    else
        printf "[%s]" "$(IFS=,; echo "${actions[*]}")"
    fi
}

# Calculate risk level based on security status
calculate_risk_level() {
    local risk_score=0
    
    # Find My Mac disabled adds risk
    if [[ "$(check_find_my_mac_status)" != "enabled" ]]; then
        ((risk_score += 3))
    fi
    
    # No Apple ID adds risk
    if ! check_apple_id_status >/dev/null 2>&1; then
        ((risk_score += 2))
    fi
    
    # System security issues add risk
    if [[ "$(csrutil status 2>/dev/null | grep -i disabled)" ]]; then
        ((risk_score += 2))
    fi
    
    if [[ $risk_score -le 1 ]]; then
        echo "low"
    elif [[ $risk_score -le 4 ]]; then
        echo "medium"
    else
        echo "high"
    fi
}

# Remediation actions for common issues
remediate_security_issues() {
    log_action "Starting automated remediation process"
    
    local remediation_report="$TEMP_DIR/remediation_$(date '+%Y%m%d_%H%M%S').json"
    
    cat > "$remediation_report" << EOF
{
    "timestamp": "$(date -Iseconds)",
    "hostname": "$(hostname)",
    "remediation_actions": []
}
EOF

    # Check if Find My Mac can be enabled programmatically
    if [[ "$(check_find_my_mac_status)" != "enabled" ]]; then
        log_action "āš ļø  Find My Mac is disabled - manual intervention required"
        log_action "   User must enable Find My Mac in System Preferences > Apple ID > Find My"
        
        # Add to remediation report
        /usr/bin/python3 -c "
import json
with open('$remediation_report', 'r') as f:
    data = json.load(f)
data['remediation_actions'].append({
    'issue': 'Find My Mac disabled',
    'action': 'manual_intervention_required',
    'instructions': 'Enable Find My Mac in System Preferences > Apple ID > Find My'
})
with open('$remediation_report', 'w') as f:
    json.dump(data, f, indent=2)
"
    fi
    
    # Generate user notification if needed
    if [[ "$(calculate_compliance_status)" != "compliant" ]]; then
        create_user_notification
    fi
    
    echo "$remediation_report"
}

# Create user notification for security compliance
create_user_notification() {
    log_action "Creating user notification for security compliance"
    
    local notification_title="MacFleet Security Compliance"
    local notification_message="Your device requires security configuration updates. Please contact IT support."
    
    # Use AppleScript to show notification
    osascript -e "display notification \"$notification_message\" with title \"$notification_title\""
    
    # Create persistent reminder file
    cat > "/tmp/macfleet_security_reminder.txt" << EOF
MacFleet Security Compliance Required

Your device needs the following security features enabled:
- Find My Mac
- Apple ID sign-in
- Activation Lock

Please contact IT support for assistance.
Generated: $(date)
EOF
}

# Monitor Find My Mac status over time
monitor_security_status() {
    log_action "Starting continuous security monitoring"
    
    local monitoring_interval=3600  # 1 hour
    local monitoring_log="$LOG_FILE.monitoring"
    
    while true; do
        {
            echo "=== Security Status Check - $(date) ==="
            echo "Find My Mac: $(check_find_my_mac_status)"
            echo "Apple ID: $(check_apple_id_status >/dev/null && echo "signed_in" || echo "not_signed_in")"
            echo "Compliance: $(calculate_compliance_status)"
            echo "Risk Level: $(calculate_risk_level)"
            echo "----------------------------------------"
        } >> "$monitoring_log"
        
        sleep "$monitoring_interval"
    done
}

# Fleet-wide security assessment
fleet_security_assessment() {
    log_action "Performing fleet-wide security assessment"
    
    local fleet_report="$REPORT_DIR/fleet_security_$(date '+%Y%m%d_%H%M%S').json"
    
    # This would typically integrate with MDM or configuration management
    # For demonstration, we'll show the current device assessment
    
    cat > "$fleet_report" << EOF
{
    "assessment_timestamp": "$(date -Iseconds)",
    "fleet_summary": {
        "total_devices": 1,
        "compliant_devices": $([ "$(calculate_compliance_status)" = "compliant" ] && echo "1" || echo "0"),
        "non_compliant_devices": $([ "$(calculate_compliance_status)" != "compliant" ] && echo "1" || echo "0")
    },
    "devices": [
        $(generate_security_report | tail -n +2 | head -n -1)
    ],
    "recommendations": [
        "Implement automated Find My Mac enablement via MDM",
        "Enforce Apple ID sign-in through device enrollment",
        "Regular security compliance auditing",
        "User education on security features"
    ]
}
EOF

    log_action "Fleet security assessment completed: $fleet_report"
    echo "$fleet_report"
}

# Main execution function
main() {
    local action="${1:-check}"
    
    log_action "=== MacFleet Security Management Started ==="
    log_action "Action: $action"
    log_action "Hostname: $(hostname)"
    log_action "User: $(whoami)"
    
    # Setup
    setup_directories
    
    case "$action" in
        "check")
            echo "=== Find My Mac Security Check ==="
            echo "Find My Mac Status: $(check_find_my_mac_status)"
            echo "Apple ID Status: $(check_apple_id_status >/dev/null && echo "signed_in" || echo "not_signed_in")"
            echo "Activation Lock: $(check_activation_lock)"
            echo "Compliance Status: $(calculate_compliance_status)"
            echo "Risk Level: $(calculate_risk_level)"
            ;;
        "audit")
            echo "Performing comprehensive security audit..."
            security_report=$(generate_security_report)
            echo "Security audit completed: $security_report"
            ;;
        "remediate")
            echo "Starting remediation process..."
            remediation_report=$(remediate_security_issues)
            echo "Remediation completed: $remediation_report"
            ;;
        "monitor")
            echo "Starting continuous monitoring..."
            monitor_security_status
            ;;
        "fleet")
            echo "Performing fleet-wide assessment..."
            fleet_report=$(fleet_security_assessment)
            echo "Fleet assessment completed: $fleet_report"
            ;;
        *)
            echo "Usage: $0 {check|audit|remediate|monitor|fleet}"
            echo "  check     - Quick security status check"
            echo "  audit     - Comprehensive security audit"
            echo "  remediate - Automated remediation actions"
            echo "  monitor   - Continuous security monitoring"
            echo "  fleet     - Fleet-wide security assessment"
            exit 1
            ;;
    esac
    
    # Cleanup
    rm -rf "$TEMP_DIR"
    
    log_action "=== Security management completed ==="
}

# Execute main function
main "$@"

Apple ID and iCloud Integration

Check Apple ID Sign-in Status

#!/bin/bash

# Comprehensive Apple ID verification
check_apple_id_comprehensive() {
    echo "=== Apple ID Status Check ==="
    
    # Check iCloud accounts
    local icloud_accounts
    icloud_accounts=$(defaults read MobileMeAccounts Accounts 2>/dev/null | grep -c AccountID || echo "0")
    
    if [[ "$icloud_accounts" -gt 0 ]]; then
        echo "āœ… Apple ID signed in ($icloud_accounts account(s))"
        
        # Get account details (privacy-safe)
        defaults read MobileMeAccounts Accounts 2>/dev/null | grep AccountID | while read -r line; do
            local account_id
            account_id=$(echo "$line" | sed 's/.*= "\(.*\)";/\1/' | sed 's/\(.*@\)\(.*\)/\1***/g')
            echo "   Account: $account_id"
        done
        
        # Check iCloud services
        echo "iCloud Services:"
        defaults read MobileMeAccounts Accounts 2>/dev/null | grep -E "(BookmarksSyncEnabled|ContactsSyncEnabled|MailSyncEnabled)" | while read -r service; do
            echo "   $service"
        done
        
        return 0
    else
        echo "āŒ No Apple ID signed in"
        return 1
    fi
}

Verify iCloud Services Status

#!/bin/bash

# Check specific iCloud services
check_icloud_services() {
    echo "=== iCloud Services Status ==="
    
    # Check Find My Mac specifically
    local fmf_token
    fmf_token=$(defaults read MobileMeAccounts Accounts 2>/dev/null | grep -i findmyfriends || echo "")
    
    if [[ -n "$fmf_token" ]]; then
        echo "āœ… Find My Friends/Family service active"
    else
        echo "āš ļø  Find My Friends/Family service not configured"
    fi
    
    # Check other critical services
    local services=(
        "BookmarksSyncEnabled:Safari Bookmarks"
        "ContactsSyncEnabled:Contacts"
        "CalendarSyncEnabled:Calendar"
        "KeychainSyncEnabled:Keychain"
    )
    
    for service in "${services[@]}"; do
        local key="${service%%:*}"
        local name="${service##*:}"
        local status
        status=$(defaults read MobileMeAccounts Accounts 2>/dev/null | grep "$key" | head -1 | grep -o "[01]" || echo "0")
        
        if [[ "$status" = "1" ]]; then
            echo "āœ… $name sync enabled"
        else
            echo "āŒ $name sync disabled"
        fi
    done
}

Enterprise Security Policies

Define Security Requirements

#!/bin/bash

# Enterprise security policy configuration
apply_security_policies() {
    echo "=== Applying Enterprise Security Policies ==="
    
    local policy_file="/etc/macfleet/security_policies.json"
    
    # Create security policy configuration
    mkdir -p "$(dirname "$policy_file")"
    cat > "$policy_file" << 'EOF'
{
    "security_policies": {
        "find_my_mac": {
            "required": true,
            "enforcement": "advisory",
            "grace_period_days": 7
        },
        "apple_id": {
            "required": true,
            "corporate_domain_only": false,
            "enforcement": "mandatory"
        },
        "activation_lock": {
            "required": true,
            "mdm_managed": true
        },
        "system_security": {
            "sip_required": true,
            "gatekeeper_required": true,
            "filevault_required": true,
            "firewall_required": true
        }
    },
    "compliance_reporting": {
        "frequency": "daily",
        "recipients": ["security@company.com"],
        "escalation_threshold": "medium"
    }
}
EOF

    echo "Security policies configured: $policy_file"
}

Compliance Monitoring

#!/bin/bash

# Automated compliance monitoring
setup_compliance_monitoring() {
    local monitoring_script="/usr/local/bin/macfleet_compliance_monitor.sh"
    local launchd_plist="/Library/LaunchDaemons/com.macfleet.security.compliance.plist"
    
    # Create monitoring script
    cat > "$monitoring_script" << 'EOF'
#!/bin/bash
LOG_FILE="/var/log/macfleet_compliance.log"
exec > >(tee -a "$LOG_FILE") 2>&1

echo "$(date): Starting security compliance check"

# Run security audit
/usr/local/bin/macfleet_security_manager.sh audit

# Check for non-compliance
COMPLIANCE_STATUS=$(calculate_compliance_status)
if [[ "$COMPLIANCE_STATUS" != "compliant" ]]; then
    echo "$(date): Non-compliance detected - $COMPLIANCE_STATUS"
    
    # Send alert (implement according to your notification system)
    echo "Device $(hostname) is non-compliant" | mail -s "Security Compliance Alert" security@company.com
fi

echo "$(date): Compliance check completed"
EOF

    chmod +x "$monitoring_script"
    
    # Create LaunchDaemon for scheduled compliance checks
    cat > "$launchd_plist" << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.macfleet.security.compliance</string>
    <key>ProgramArguments</key>
    <array>
        <string>$monitoring_script</string>
    </array>
    <key>StartCalendarInterval</key>
    <array>
        <dict>
            <key>Hour</key>
            <integer>9</integer>
            <key>Minute</key>
            <integer>0</integer>
        </dict>
        <dict>
            <key>Hour</key>
            <integer>17</integer>
            <key>Minute</key>
            <integer>0</integer>
        </dict>
    </array>
    <key>RunAtLoad</key>
    <false/>
</dict>
</plist>
EOF

    # Load the LaunchDaemon
    sudo launchctl load "$launchd_plist"
    
    echo "Compliance monitoring configured"
    echo "Script: $monitoring_script"
    echo "Schedule: Daily at 9:00 AM and 5:00 PM"
}

Security Status Indicators

Understanding NVRAM Tokens

The Find My Mac status is stored in NVRAM (Non-Volatile Random Access Memory) tokens:

TokenDescriptionIndicates
fmm-mobileme-token-FMMPrimary Find My Mac tokenService is active and configured
fmm-computer-nameDevice name for Find MyDevice identification in Find My network
fmm-mobileme-token-FMFFind My Friends tokenLocation sharing services

Interpreting Security States

StateFind My MacApple IDComplianceAction Required
Fully Compliantāœ… Enabledāœ… Signed Ināœ… CompliantNone
Partially Compliantāœ… EnabledāŒ Not Signed Ināš ļø PartialSign in to Apple ID
Non-CompliantāŒ DisabledāŒ Not Signed InāŒ Non-CompliantEnable Find My Mac and sign in
Unknown Stateā“ Cannot Detectā“ Cannot Detectā“ UnknownManual verification required

Troubleshooting Common Issues

Find My Mac Not Enabling

#!/bin/bash

# Troubleshoot Find My Mac issues
troubleshoot_find_my_mac() {
    echo "=== Find My Mac Troubleshooting ==="
    
    # Check prerequisites
    echo "Checking prerequisites..."
    
    # 1. Check internet connectivity
    if ping -c 1 apple.com >/dev/null 2>&1; then
        echo "āœ… Internet connectivity: OK"
    else
        echo "āŒ Internet connectivity: FAILED"
        echo "   - Check network connection"
        echo "   - Verify DNS settings"
    fi
    
    # 2. Check Apple ID sign-in
    if check_apple_id_status >/dev/null 2>&1; then
        echo "āœ… Apple ID sign-in: OK"
    else
        echo "āŒ Apple ID sign-in: REQUIRED"
        echo "   - Sign in to Apple ID in System Preferences"
        echo "   - Enable iCloud services"
    fi
    
    # 3. Check iCloud services
    local icloud_enabled
    icloud_enabled=$(defaults read MobileMeAccounts Accounts 2>/dev/null | grep -c "Enabled.*1" || echo "0")
    
    if [[ "$icloud_enabled" -gt 0 ]]; then
        echo "āœ… iCloud services: ENABLED"
    else
        echo "āŒ iCloud services: DISABLED"
        echo "   - Enable iCloud in System Preferences"
        echo "   - Ensure Find My Mac is checked"
    fi
    
    # 4. Check system requirements
    local os_version
    os_version=$(sw_vers -productVersion)
    
    if [[ "$(echo "$os_version" | cut -d. -f1)" -ge 10 ]] && [[ "$(echo "$os_version" | cut -d. -f2)" -ge 11 ]]; then
        echo "āœ… macOS version: SUPPORTED ($os_version)"
    else
        echo "āŒ macOS version: UNSUPPORTED ($os_version)"
        echo "   - Find My Mac requires macOS 10.11 or later"
    fi
}

Manual Remediation Steps

#!/bin/bash

# Generate manual remediation guide
generate_remediation_guide() {
    local guide_file="/tmp/macfleet_remediation_guide.txt"
    
    cat > "$guide_file" << EOF
MacFleet Security Remediation Guide
==================================

Device: $(hostname)
Date: $(date)

Required Actions:
EOF

    if [[ "$(check_find_my_mac_status)" != "enabled" ]]; then
        cat >> "$guide_file" << EOF

1. Enable Find My Mac:
   - Open System Preferences
   - Click on Apple ID (or iCloud on older systems)
   - Sign in with your Apple ID if not already signed in
   - Click on "Find My" in the sidebar
   - Check "Find My Mac"
   - Check "Enable offline finding" (if available)
   - Click "Allow" when prompted for location access

EOF
    fi
    
    if ! check_apple_id_status >/dev/null 2>&1; then
        cat >> "$guide_file" << EOF

2. Sign in to Apple ID:
   - Open System Preferences
   - Click on Apple ID at the top
   - Enter your Apple ID and password
   - Complete two-factor authentication if prompted
   - Enable iCloud services as needed

EOF
    fi
    
    cat >> "$guide_file" << EOF

For assistance, contact IT Support:
- Email: support@company.com
- Phone: +1-555-0123
- Ticket System: https://support.company.com

EOF

    echo "Remediation guide created: $guide_file"
    open "$guide_file"
}

Best Practices

šŸ” Security Guidelines

  • Enable Find My Mac on all enterprise devices
  • Require Apple ID sign-in for device accountability
  • Monitor compliance status regularly
  • Implement automated alerting for non-compliance

šŸ“‹ Management Recommendations

  • Use MDM enrollment for enterprise activation lock
  • Regular security audits across device fleet
  • User education on security feature importance
  • Automated compliance monitoring and reporting

šŸ” Monitoring Strategy

  • Daily compliance checks during business hours
  • Immediate alerts for security violations
  • Trend analysis of compliance metrics
  • Regular policy review and updates

Important Notes

  • Find My Mac requires macOS 10.11 or later for full functionality
  • Apple ID sign-in is mandatory for Find My Mac operation
  • Network connectivity required for initial setup and ongoing operation
  • Privacy considerations should be documented for enterprise use
  • Test remediation procedures before enterprise deployment

FileVault Encryption Management on macOS

Manage FileVault disk encryption across your MacFleet deployment with comprehensive monitoring, compliance reporting, and automated encryption management. This tutorial provides enterprise-grade solutions for maintaining data security through disk encryption.

Understanding FileVault Encryption

FileVault is Apple's full-disk encryption technology that protects data at rest on macOS devices:

  • Full Disk Encryption - Encrypts entire startup disk
  • XTS-AES-128 encryption algorithm with 256-bit key
  • Hardware acceleration on supported Mac devices
  • Recovery key management for enterprise deployment
  • Compliance requirements for data protection standards

Basic Encryption Status Monitoring

Check FileVault Status

#!/bin/bash

# Check current FileVault encryption status
sudo fdesetup status

echo "FileVault status check completed"

Verify Encryption State

#!/bin/bash

# Get detailed encryption information
echo "=== FileVault Status ==="
status=$(sudo fdesetup status)
echo "$status"

# Parse status for automation
if echo "$status" | grep -q "FileVault is On"; then
    echo "āœ… Encryption: ENABLED"
    exit 0
elif echo "$status" | grep -q "FileVault is Off"; then
    echo "āŒ Encryption: DISABLED"
    exit 1
else
    echo "āš ļø Encryption: UNKNOWN STATE"
    exit 2
fi

Encryption Progress Monitoring

macOS 10.11 and 10.12 (Core Storage)

#!/bin/bash

# Monitor encryption/decryption progress for older macOS versions
echo "=== Core Storage Encryption Progress ==="
progress=$(diskutil cs list | grep "Conversion Progress")

if [[ -n "$progress" ]]; then
    echo "Encryption in progress:"
    echo "$progress"
else
    echo "No encryption/decryption operation in progress"
fi

macOS 10.13+ (APFS)

#!/bin/bash

# Monitor encryption progress for APFS (macOS 10.13+)
echo "=== APFS Encryption Progress ==="

# Check encryption progress
enc_progress=$(diskutil apfs list | grep "Encryption Progress")
if [[ -n "$enc_progress" ]]; then
    echo "Encryption in progress:"
    echo "$enc_progress"
fi

# Check decryption progress
dec_progress=$(diskutil apfs list | grep "Decryption Progress")
if [[ -n "$dec_progress" ]]; then
    echo "Decryption in progress:"
    echo "$dec_progress"
fi

if [[ -z "$enc_progress" && -z "$dec_progress" ]]; then
    echo "No encryption/decryption operation in progress"
fi

Universal Progress Monitor

#!/bin/bash

# Universal encryption progress monitor
check_encryption_progress() {
    local macos_version
    macos_version=$(sw_vers -productVersion | cut -d. -f1-2)
    
    echo "=== Encryption Progress Monitor ==="
    echo "macOS Version: $macos_version"
    
    case "$macos_version" in
        "10.11"|"10.12")
            echo "Using Core Storage monitoring..."
            diskutil cs list | grep "Conversion Progress" || echo "No progress detected"
            ;;
        *)
            echo "Using APFS monitoring..."
            local enc_progress dec_progress
            enc_progress=$(diskutil apfs list | grep "Encryption Progress")
            dec_progress=$(diskutil apfs list | grep "Decryption Progress")
            
            if [[ -n "$enc_progress" ]]; then
                echo "Encryption: $enc_progress"
            elif [[ -n "$dec_progress" ]]; then
                echo "Decryption: $dec_progress"
            else
                echo "No encryption/decryption operation in progress"
            fi
            ;;
    esac
}

check_encryption_progress

Advanced Enterprise Management

Comprehensive Encryption Audit

#!/bin/bash

# MacFleet FileVault Enterprise Audit Tool
# Comprehensive encryption status and compliance checking

# Configuration
LOG_FILE="/var/log/macfleet_encryption.log"
REPORT_DIR="/var/log/macfleet_reports"
CONFIG_FILE="/etc/macfleet/encryption_policy.conf"

# Create directories if they don't exist
mkdir -p "$(dirname "$LOG_FILE")" "$REPORT_DIR" "$(dirname "$CONFIG_FILE")"

# Default configuration
cat > "$CONFIG_FILE" 2>/dev/null << 'EOF' || true
# MacFleet Encryption Policy Configuration
REQUIRE_FILEVAULT=true
ALERT_ON_DISABLED=true
MONITOR_PROGRESS=true
COMPLIANCE_REPORTING=true
AUTO_REMEDIATION=false
NOTIFICATION_EMAIL=""
EOF

# Source configuration
source "$CONFIG_FILE" 2>/dev/null || true

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

# Get system information
get_system_info() {
    echo "=== System Information ==="
    echo "Hostname: $(hostname)"
    echo "macOS Version: $(sw_vers -productVersion)"
    echo "Build: $(sw_vers -buildVersion)"
    echo "Hardware: $(system_profiler SPHardwareDataType | grep "Model Name" | awk -F: '{print $2}' | xargs)"
    echo "Serial: $(system_profiler SPHardwareDataType | grep "Serial Number" | awk -F: '{print $2}' | xargs)"
    echo "Audit Date: $(date)"
    echo ""
}

# Check FileVault status
check_filevault_status() {
    echo "=== FileVault Status Analysis ==="
    
    local status
    status=$(sudo fdesetup status 2>/dev/null)
    
    if echo "$status" | grep -q "FileVault is On"; then
        echo "āœ… FileVault Status: ENABLED"
        log_action "FileVault encryption is properly enabled"
        
        # Get enabled users
        local enabled_users
        enabled_users=$(sudo fdesetup list 2>/dev/null)
        if [[ -n "$enabled_users" ]]; then
            echo "Enabled Users:"
            echo "$enabled_users"
        fi
        
        return 0
    elif echo "$status" | grep -q "FileVault is Off"; then
        echo "āŒ FileVault Status: DISABLED"
        log_action "SECURITY ALERT: FileVault encryption is disabled"
        
        if [[ "$ALERT_ON_DISABLED" == "true" ]]; then
            echo "āš ļø  COMPLIANCE VIOLATION: Encryption required by policy"
        fi
        
        return 1
    else
        echo "āš ļø  FileVault Status: UNKNOWN"
        log_action "WARNING: Cannot determine FileVault status"
        return 2
    fi
}

# Check encryption progress
check_encryption_progress() {
    echo "=== Encryption Progress ==="
    
    local macos_version
    macos_version=$(sw_vers -productVersion | cut -d. -f1-2)
    
    case "$macos_version" in
        "10.11"|"10.12")
            local cs_progress
            cs_progress=$(diskutil cs list | grep "Conversion Progress")
            if [[ -n "$cs_progress" ]]; then
                echo "Core Storage Progress: $cs_progress"
                log_action "Encryption/Decryption in progress: $cs_progress"
            else
                echo "No Core Storage conversion in progress"
            fi
            ;;
        *)
            local enc_progress dec_progress
            enc_progress=$(diskutil apfs list | grep "Encryption Progress")
            dec_progress=$(diskutil apfs list | grep "Decryption Progress")
            
            if [[ -n "$enc_progress" ]]; then
                echo "APFS Encryption Progress: $enc_progress"
                log_action "APFS encryption in progress: $enc_progress"
            elif [[ -n "$dec_progress" ]]; then
                echo "APFS Decryption Progress: $dec_progress"
                log_action "APFS decryption in progress: $dec_progress"
            else
                echo "No APFS encryption/decryption in progress"
            fi
            ;;
    esac
}

# Check disk information
check_disk_info() {
    echo "=== Disk Information ==="
    
    # Boot disk info
    local boot_disk
    boot_disk=$(diskutil info / | grep "Device Node" | awk '{print $3}')
    echo "Boot Disk: $boot_disk"
    
    # Disk size and usage
    echo "Disk Usage:"
    df -h /
    
    # APFS information (macOS 10.13+)
    if command -v diskutil >/dev/null && diskutil apfs list >/dev/null 2>&1; then
        echo -e "\nAPFS Container Info:"
        diskutil apfs list | grep -E "(Container|Volume|Encryption)"
    fi
}

# Generate compliance report
generate_compliance_report() {
    local report_file="$REPORT_DIR/encryption_compliance_$(date +%Y%m%d_%H%M%S).json"
    
    echo "=== Generating Compliance Report ==="
    
    # Get FileVault status
    local filevault_enabled=false
    local status_detail=""
    
    if sudo fdesetup status 2>/dev/null | grep -q "FileVault is On"; then
        filevault_enabled=true
        status_detail="enabled"
    else
        status_detail="disabled"
    fi
    
    # Create JSON report
    cat > "$report_file" << EOF
{
  "report_type": "encryption_compliance",
  "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
  "hostname": "$(hostname)",
  "serial_number": "$(system_profiler SPHardwareDataType | grep "Serial Number" | awk -F: '{print $2}' | xargs)",
  "macos_version": "$(sw_vers -productVersion)",
  "encryption": {
    "filevault_enabled": $filevault_enabled,
    "status_detail": "$status_detail",
    "compliance_status": "$([ "$filevault_enabled" == "true" ] && echo "compliant" || echo "non_compliant")",
    "policy_required": $REQUIRE_FILEVAULT
  },
  "disk_info": {
    "boot_disk": "$(diskutil info / | grep "Device Node" | awk '{print $3}')",
    "file_system": "$(diskutil info / | grep "File System" | awk -F: '{print $2}' | xargs)"
  },
  "audit_details": {
    "audit_date": "$(date)",
    "policy_version": "1.0",
    "remediation_required": $([ "$filevault_enabled" != "true" ] && echo "true" || echo "false")
  }
}
EOF
    
    echo "Compliance report saved to: $report_file"
    log_action "Compliance report generated: $report_file"
}

# Remediation actions
perform_remediation() {
    echo "=== Automated Remediation ==="
    
    if [[ "$AUTO_REMEDIATION" != "true" ]]; then
        echo "Auto-remediation disabled in policy"
        return 0
    fi
    
    # Check if FileVault is disabled
    if ! sudo fdesetup status 2>/dev/null | grep -q "FileVault is On"; then
        echo "āš ļø  FileVault is disabled - remediation required"
        log_action "REMEDIATION: FileVault encryption is disabled"
        
        echo "Manual remediation steps:"
        echo "1. Open System Preferences > Security & Privacy"
        echo "2. Click the FileVault tab"
        echo "3. Click Turn On FileVault"
        echo "4. Follow the setup wizard"
        echo ""
        echo "Or use MDM to enforce FileVault encryption policy"
        
        # Create remediation ticket (placeholder)
        echo "Creating remediation ticket for device: $(hostname)"
    fi
}

# Main audit function
main() {
    log_action "=== MacFleet FileVault Audit Started ==="
    
    get_system_info
    check_filevault_status
    local filevault_status=$?
    
    echo ""
    check_encryption_progress
    echo ""
    check_disk_info
    echo ""
    
    if [[ "$COMPLIANCE_REPORTING" == "true" ]]; then
        generate_compliance_report
        echo ""
    fi
    
    if [[ $filevault_status -ne 0 ]]; then
        perform_remediation
    fi
    
    log_action "=== FileVault audit completed with status: $filevault_status ==="
    return $filevault_status
}

# Execute main function
main "$@"

Enterprise Policy Management

Policy Configuration Template

#!/bin/bash

# Create comprehensive encryption policy
cat > /etc/macfleet/encryption_policy.conf << 'EOF'
# MacFleet Enterprise Encryption Policy
# Version: 2.0

# Core Requirements
REQUIRE_FILEVAULT=true
ENFORCE_IMMEDIATE_ENCRYPTION=true
ALLOW_PERSONAL_RECOVERY_KEY=false
REQUIRE_INSTITUTIONAL_RECOVERY_KEY=true

# Monitoring Configuration
ALERT_ON_DISABLED=true
MONITOR_PROGRESS=true
PROGRESS_CHECK_INTERVAL=3600  # seconds
COMPLIANCE_REPORTING=true
AUDIT_FREQUENCY=86400  # daily

# Remediation Settings
AUTO_REMEDIATION=false
ESCALATION_THRESHOLD=72  # hours
NOTIFICATION_EMAIL="security@company.com"
HELP_DESK_CONTACT="+1-555-0123"

# Security Policies
MIN_RECOVERY_KEY_LENGTH=24
RECOVERY_KEY_ROTATION_DAYS=90
ENCRYPTION_ALGORITHM="XTS-AES-128"

# Compliance Standards
COMPLIANCE_FRAMEWORKS="SOC2,HIPAA,PCI-DSS"
DATA_CLASSIFICATION_REQUIRED=true
AUDIT_TRAIL_RETENTION_DAYS=2555  # 7 years
EOF

echo "Enterprise encryption policy configured"

Recovery Key Management

#!/bin/bash

# Enterprise recovery key management
manage_recovery_keys() {
    echo "=== Recovery Key Management ==="
    
    # Check if institutional recovery key is set
    local has_institutional_key=false
    if sudo fdesetup list 2>/dev/null | grep -q "institutional"; then
        has_institutional_key=true
        echo "āœ… Institutional recovery key configured"
    else
        echo "āŒ No institutional recovery key found"
    fi
    
    # Validate recovery key
    if [[ "$has_institutional_key" == "true" ]]; then
        echo "Recovery key validation:"
        sudo fdesetup validaterecovery 2>/dev/null && echo "āœ… Recovery key valid" || echo "āŒ Recovery key invalid"
    fi
    
    # Escrow recovery key (MDM integration)
    echo "Recovery key escrow status:"
    if system_profiler SPConfigurationProfileDataType | grep -q "FDERecoveryKeyEscrow"; then
        echo "āœ… Recovery key escrowed to MDM"
    else
        echo "āš ļø  Recovery key not escrowed"
    fi
}

manage_recovery_keys

Monitoring and Alerting

Continuous Monitoring Script

#!/bin/bash

# Continuous FileVault monitoring daemon
DAEMON_NAME="macfleet-encryption-monitor"
PID_FILE="/var/run/${DAEMON_NAME}.pid"
CHECK_INTERVAL=300  # 5 minutes

# Daemon functions
start_monitoring() {
    if [[ -f "$PID_FILE" ]]; then
        echo "Monitoring daemon already running (PID: $(cat "$PID_FILE"))"
        return 1
    fi
    
    echo "Starting FileVault monitoring daemon..."
    
    # Background monitoring loop
    (
        while true; do
            # Quick status check
            if ! sudo fdesetup status 2>/dev/null | grep -q "FileVault is On"; then
                logger -t "$DAEMON_NAME" "ALERT: FileVault encryption disabled on $(hostname)"
                
                # Send notification (customize for your environment)
                osascript -e 'display notification "FileVault encryption is disabled!" with title "MacFleet Security Alert"' 2>/dev/null || true
            fi
            
            sleep "$CHECK_INTERVAL"
        done
    ) &
    
    echo $! > "$PID_FILE"
    echo "Monitoring daemon started (PID: $!)"
}

stop_monitoring() {
    if [[ -f "$PID_FILE" ]]; then
        local pid
        pid=$(cat "$PID_FILE")
        kill "$pid" 2>/dev/null
        rm -f "$PID_FILE"
        echo "Monitoring daemon stopped"
    else
        echo "Monitoring daemon not running"
    fi
}

# Execute based on argument
case "${1:-start}" in
    start)
        start_monitoring
        ;;
    stop)
        stop_monitoring
        ;;
    restart)
        stop_monitoring
        sleep 2
        start_monitoring
        ;;
    status)
        if [[ -f "$PID_FILE" ]]; then
            echo "Monitoring daemon running (PID: $(cat "$PID_FILE"))"
        else
            echo "Monitoring daemon not running"
        fi
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|status}"
        exit 1
        ;;
esac

Important Security Notes

FileVault Best Practices

  • Enable before deployment - Encrypt devices before user deployment
  • Escrow recovery keys - Use MDM for centralized key management
  • Regular key rotation - Rotate institutional recovery keys periodically
  • Monitor compliance - Continuous monitoring for policy violations
  • Test recovery procedures - Regularly test key recovery processes

Enterprise Considerations

  • Performance impact - Minimal on modern Mac hardware with T2/Apple Silicon
  • Initial encryption time - Can take several hours for large drives
  • Recovery planning - Ensure recovery key availability for support
  • User training - Educate users on encryption benefits and recovery
  • Compliance reporting - Regular audits for regulatory requirements

Apple Silicon Considerations

  • Hardware acceleration - Optimized encryption performance
  • Secure Enclave - Enhanced key protection
  • Progress monitoring limitations - Some monitoring tools may not work
  • Boot security - Additional security features beyond FileVault

Remember to test these scripts thoroughly in your environment before deploying to production devices.

File Size and Storage Analysis on macOS

Master file size analysis and storage management on your MacFleet devices using powerful disk usage tools. This tutorial covers basic size queries, storage analysis, disk usage monitoring, and advanced storage optimization techniques for effective fleet storage management.

Understanding macOS Storage Analysis

macOS provides several command-line tools for storage analysis:

  • du - Disk usage analysis for files and directories
  • df - File system disk space usage
  • ls - File listing with size information
  • find - Search files by size criteria
  • stat - Detailed file information including size

Basic File and Folder Size Operations

Find Single File Size

#!/bin/bash

# Get size of a specific file
FILE_PATH="/Users/stefan/Desktop/Document.txt"

echo "File size for: $FILE_PATH"
du -h "$FILE_PATH"

echo "File size analysis completed"

Find Folder Size

#!/bin/bash

# Get size of a folder
FOLDER_PATH="/Users/stefan/Desktop/Wallpapers"

echo "Folder size for: $FOLDER_PATH"
du -h "$FOLDER_PATH"

echo "Folder size analysis completed"

Detailed Size Information

#!/bin/bash

# Get detailed size information with options
analyze_size() {
    local target_path="$1"
    
    if [[ ! -e "$target_path" ]]; then
        echo "Error: Path not found: $target_path"
        return 1
    fi
    
    echo "=== Size Analysis for: $target_path ==="
    
    # Basic size
    echo "Total size:"
    du -h "$target_path"
    
    # Size with all files listed
    echo -e "\nDetailed breakdown:"
    du -ah "$target_path" | head -20
    
    # Grand total with summary
    echo -e "\nSummary with total:"
    du -ch "$target_path"
}

# Usage
analyze_size "/Users/stefan/Desktop/Document.txt"

Advanced Storage Analysis

Directory Size Breakdown

#!/bin/bash

# Analyze directory sizes with sorting
directory_analysis() {
    local base_path="$1"
    local max_depth="${2:-1}"
    
    echo "=== Directory Size Analysis: $base_path ==="
    
    # Top-level directory sizes, sorted by size
    echo "Largest directories:"
    du -h -d "$max_depth" "$base_path" 2>/dev/null | sort -hr | head -20
    
    # Count of items
    echo -e "\nItem counts:"
    echo "Files: $(find "$base_path" -type f 2>/dev/null | wc -l)"
    echo "Directories: $(find "$base_path" -type d 2>/dev/null | wc -l)"
    
    # File type analysis
    echo -e "\nFile type distribution:"
    find "$base_path" -type f 2>/dev/null | grep '\.' | rev | cut -d. -f1 | rev | sort | uniq -c | sort -nr | head -10
}

# Usage
directory_analysis "/Users" 2

Large File Detection

#!/bin/bash

# Find large files in directory
find_large_files() {
    local search_path="$1"
    local min_size="${2:-100M}"
    
    echo "=== Large Files Analysis (>$min_size) in: $search_path ==="
    
    # Find large files
    echo "Large files found:"
    find "$search_path" -type f -size +"$min_size" -exec ls -lh {} \; 2>/dev/null | sort -k5 -hr
    
    # Count and total size
    local large_files_count=$(find "$search_path" -type f -size +"$min_size" 2>/dev/null | wc -l)
    echo -e "\nTotal large files: $large_files_count"
    
    if [[ $large_files_count -gt 0 ]]; then
        echo "Total size of large files:"
        find "$search_path" -type f -size +"$min_size" -exec du -ch {} + 2>/dev/null | tail -1
    fi
}

# Usage
find_large_files "/Users" "50M"

Storage Usage by File Type

#!/bin/bash

# Analyze storage usage by file extension
storage_by_type() {
    local search_path="$1"
    
    echo "=== Storage Usage by File Type: $search_path ==="
    
    # Create temporary file for analysis
    local temp_file="/tmp/file_analysis_$$"
    
    # Get all files with extensions and their sizes
    find "$search_path" -type f -name "*.*" -exec sh -c '
        for file; do
            ext=$(echo "$file" | rev | cut -d. -f1 | rev | tr "[:upper:]" "[:lower:]")
            size=$(stat -f%z "$file" 2>/dev/null || echo 0)
            echo "$ext $size"
        done
    ' _ {} + > "$temp_file"
    
    # Summarize by extension
    echo "Top file types by total size:"
    awk '{
        ext_size[$1] += $2
        ext_count[$1]++
    } END {
        for (ext in ext_size) {
            printf "%-10s %15s %10d files\n", ext, ext_size[ext], ext_count[ext]
        }
    }' "$temp_file" | sort -k2 -nr | head -15 | \
    while read ext size count; do
        # Convert bytes to human readable
        if [[ $size -gt 1073741824 ]]; then
            printf "%-10s %10.2f GB %10d files\n" "$ext" $(echo "scale=2; $size/1073741824" | bc) "$count"
        elif [[ $size -gt 1048576 ]]; then
            printf "%-10s %10.2f MB %10d files\n" "$ext" $(echo "scale=2; $size/1048576" | bc) "$count"
        else
            printf "%-10s %10.2f KB %10d files\n" "$ext" $(echo "scale=2; $size/1024" | bc) "$count"
        fi
    done
    
    # Cleanup
    rm -f "$temp_file"
}

# Usage
storage_by_type "/Users"

Disk Space Monitoring

System Disk Usage

#!/bin/bash

# Comprehensive disk usage report
system_disk_report() {
    echo "=== System Disk Usage Report ==="
    
    # File system usage
    echo "File System Usage:"
    df -h
    
    echo -e "\nDisk usage by mount point:"
    df -h | awk 'NR>1 {print $5 " " $1}' | while read output; do
        usage=$(echo $output | awk '{print $1}' | cut -d'%' -f1)
        partition=$(echo $output | awk '{print $2}')
        if [[ $usage -ge 80 ]]; then
            echo "āš ļø  $partition: ${usage}% (WARNING)"
        elif [[ $usage -ge 90 ]]; then
            echo "🚨 $partition: ${usage}% (CRITICAL)"
        else
            echo "āœ… $partition: ${usage}%"
        fi
    done
    
    # Top directories by size
    echo -e "\nTop directories by size:"
    du -h / 2>/dev/null | sort -hr | head -10
}

# Run system report
system_disk_report

Storage Trend Analysis

#!/bin/bash

# Monitor storage trends over time
storage_trend_monitor() {
    local target_path="$1"
    local log_file="/var/log/macfleet_storage_trends.log"
    
    echo "=== Storage Trend Monitoring: $target_path ==="
    
    # Current timestamp and size
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    local current_size=$(du -sk "$target_path" 2>/dev/null | cut -f1)
    
    # Log current measurement
    echo "$timestamp,$target_path,$current_size" >> "$log_file"
    
    # Show recent trends if log exists
    if [[ -f "$log_file" ]]; then
        echo "Recent storage trends (last 10 measurements):"
        echo "Timestamp                | Path              | Size (KB)    | Change"
        echo "-------------------------|-------------------|--------------|--------"
        
        tail -10 "$log_file" | while IFS=',' read -r time path size; do
            # Calculate change from previous measurement
            printf "%-24s | %-17s | %12s | \n" "$time" "$(basename "$path")" "$size"
        done
        
        # Calculate growth rate
        local first_size=$(head -1 "$log_file" | cut -d',' -f3)
        local growth=$((current_size - first_size))
        local growth_percent=$(echo "scale=2; ($growth * 100) / $first_size" | bc 2>/dev/null || echo "0")
        
        echo -e "\nGrowth since first measurement: ${growth} KB (${growth_percent}%)"
    fi
}

# Usage
storage_trend_monitor "/Users"

Enterprise Storage Management System

#!/bin/bash

# MacFleet Storage Management Tool
# Comprehensive storage analysis and optimization for fleet devices

# Configuration
SCRIPT_VERSION="1.0.0"
LOG_FILE="/var/log/macfleet_storage.log"
REPORT_DIR="/etc/macfleet/reports/storage"
CONFIG_DIR="/etc/macfleet/storage"
ALERT_DIR="$CONFIG_DIR/alerts"

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

# Storage categories for analysis
declare -A STORAGE_CATEGORIES=(
    ["system_critical"]="/System,/Library,/usr,/bin,/sbin"
    ["user_data"]="/Users,/home"
    ["applications"]="/Applications"
    ["caches"]="/Library/Caches,/Users/*/Library/Caches"
    ["logs"]="/var/log,/Library/Logs,/Users/*/Library/Logs"
    ["downloads"]="/Users/*/Downloads"
    ["documents"]="/Users/*/Documents,/Users/*/Desktop"
    ["media"]="/Users/*/Movies,/Users/*/Music,/Users/*/Pictures"
    ["temporary"]="/tmp,/var/tmp,/Users/*/Library/Application Support/*/Cache"
    ["development"]="/usr/local,/opt,/Users/*/Development"
)

# Storage thresholds and policies
declare -A STORAGE_POLICIES=(
    ["space_warning"]="80,85,90,95"
    ["large_file_threshold"]="100M,500M,1G,5G"
    ["old_file_threshold"]="30,90,180,365"
    ["cache_cleanup_age"]="7,14,30,60"
    ["temp_cleanup_age"]="1,3,7,14"
    ["log_retention_days"]="30,60,90,180"
)

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

# Advanced storage analysis engine
analyze_storage_comprehensive() {
    local target_path="$1"
    local analysis_level="${2:-standard}"
    local category="${3:-general}"
    
    log_action "Starting comprehensive storage analysis: $target_path (Level: $analysis_level)"
    
    if [[ ! -e "$target_path" ]]; then
        log_action "ERROR: Target path does not exist: $target_path"
        return 1
    fi
    
    local report_file="$REPORT_DIR/storage_analysis_$(echo "$target_path" | tr '/' '_')_$(date +%Y%m%d_%H%M%S).json"
    
    # Initialize report
    cat > "$report_file" << EOF
{
    "analysis_info": {
        "target_path": "$target_path",
        "analysis_level": "$analysis_level",
        "category": "$category",
        "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
        "hostname": "$(hostname)",
        "script_version": "$SCRIPT_VERSION"
    },
    "storage_metrics": {},
    "file_analysis": {},
    "recommendations": [],
    "alerts": []
}
EOF
    
    # Basic storage metrics
    local total_size_kb=$(du -sk "$target_path" 2>/dev/null | cut -f1)
    local total_files=$(find "$target_path" -type f 2>/dev/null | wc -l)
    local total_dirs=$(find "$target_path" -type d 2>/dev/null | wc -l)
    local largest_file_size=$(find "$target_path" -type f -exec stat -f%z {} \; 2>/dev/null | sort -nr | head -1)
    
    # Update report with basic metrics
    jq --argjson total_size_kb "$total_size_kb" \
       --argjson total_files "$total_files" \
       --argjson total_dirs "$((total_dirs - 1))" \
       --argjson largest_file "$largest_file_size" \
       '.storage_metrics = {
           "total_size_kb": $total_size_kb,
           "total_size_mb": ($total_size_kb / 1024),
           "total_size_gb": ($total_size_kb / 1048576),
           "total_files": $total_files,
           "total_directories": $total_dirs,
           "largest_file_bytes": $largest_file,
           "average_file_size": (if $total_files > 0 then ($total_size_kb * 1024 / $total_files) else 0 end)
       }' "$report_file" > "${report_file}.tmp" && mv "${report_file}.tmp" "$report_file"
    
    # Perform analysis based on level
    case "$analysis_level" in
        "quick")
            perform_quick_storage_analysis "$target_path" "$report_file"
            ;;
        "standard")
            perform_standard_storage_analysis "$target_path" "$report_file"
            ;;
        "comprehensive")
            perform_comprehensive_storage_analysis "$target_path" "$report_file"
            ;;
        "optimization")
            perform_optimization_analysis "$target_path" "$report_file"
            ;;
        "security")
            perform_security_storage_analysis "$target_path" "$report_file"
            ;;
    esac
    
    log_action "Storage analysis completed: $report_file"
    echo "$report_file"
}

# Quick storage analysis
perform_quick_storage_analysis() {
    local target_path="$1"
    local report_file="$2"
    
    echo "Performing quick storage analysis..."
    
    # Top-level directory sizes
    local dir_sizes=$(du -h -d 1 "$target_path" 2>/dev/null | sort -hr | head -10)
    
    # Large files (>100MB)
    local large_files=$(find "$target_path" -type f -size +100M 2>/dev/null | head -10)
    
    # Update report
    jq --arg dir_sizes "$dir_sizes" \
       --arg large_files "$large_files" \
       '.file_analysis.quick = {
           "directory_sizes": $dir_sizes,
           "large_files_100mb": $large_files
       }' "$report_file" > "${report_file}.tmp" && mv "${report_file}.tmp" "$report_file"
}

# Standard storage analysis
perform_standard_storage_analysis() {
    local target_path="$1"
    local report_file="$2"
    
    echo "Performing standard storage analysis..."
    
    # File age analysis
    local recent_files=$(find "$target_path" -type f -mtime -7 2>/dev/null | wc -l)
    local old_files=$(find "$target_path" -type f -mtime +365 2>/dev/null | wc -l)
    
    # File size distribution
    local small_files=$(find "$target_path" -type f -size -1k 2>/dev/null | wc -l)
    local medium_files=$(find "$target_path" -type f -size +1k -size -1M 2>/dev/null | wc -l)
    local large_files=$(find "$target_path" -type f -size +1M -size -100M 2>/dev/null | wc -l)
    local huge_files=$(find "$target_path" -type f -size +100M 2>/dev/null | wc -l)
    
    # Empty files and directories
    local empty_files=$(find "$target_path" -type f -empty 2>/dev/null | wc -l)
    local empty_dirs=$(find "$target_path" -type d -empty 2>/dev/null | wc -l)
    
    # Update report
    jq --argjson recent_files "$recent_files" \
       --argjson old_files "$old_files" \
       --argjson small_files "$small_files" \
       --argjson medium_files "$medium_files" \
       --argjson large_files "$large_files" \
       --argjson huge_files "$huge_files" \
       --argjson empty_files "$empty_files" \
       --argjson empty_dirs "$empty_dirs" \
       '.file_analysis.standard = {
           "file_age": {
               "recent_files": $recent_files,
               "old_files": $old_files
           },
           "file_sizes": {
               "small_1kb": $small_files,
               "medium_1kb_1mb": $medium_files,
               "large_1mb_100mb": $large_files,
               "huge_100mb_plus": $huge_files
           },
           "empty_items": {
               "empty_files": $empty_files,
               "empty_directories": $empty_dirs
           }
       }' "$report_file" > "${report_file}.tmp" && mv "${report_file}.tmp" "$report_file"
}

# Comprehensive storage analysis
perform_comprehensive_storage_analysis() {
    local target_path="$1"
    local report_file="$2"
    
    echo "Performing comprehensive storage analysis..."
    
    # Duplicate file detection
    local duplicates_temp="/tmp/duplicates_$$"
    find "$target_path" -type f -exec md5 {} \; 2>/dev/null | sort | uniq -d -w 32 > "$duplicates_temp"
    local duplicate_count=$(wc -l < "$duplicates_temp")
    
    # File extension analysis
    local extensions_temp="/tmp/extensions_$$"
    find "$target_path" -type f -name "*.*" 2>/dev/null | rev | cut -d. -f1 | rev | sort | uniq -c | sort -nr > "$extensions_temp"
    
    # Access pattern analysis
    local never_accessed=$(find "$target_path" -type f -atime +365 2>/dev/null | wc -l)
    local recently_accessed=$(find "$target_path" -type f -atime -1 2>/dev/null | wc -l)
    
    # Directory depth analysis
    local max_depth=$(find "$target_path" -type d 2>/dev/null | awk -F/ '{print NF}' | sort -n | tail -1)
    local current_depth=$(echo "$target_path" | tr -cd '/' | wc -c)
    local relative_depth=$((max_depth - current_depth))
    
    # Update report
    jq --argjson duplicate_count "$duplicate_count" \
       --argjson never_accessed "$never_accessed" \
       --argjson recently_accessed "$recently_accessed" \
       --argjson max_depth "$relative_depth" \
       '.file_analysis.comprehensive = {
           "duplicates": {
               "duplicate_file_sets": $duplicate_count
           },
           "access_patterns": {
               "never_accessed": $never_accessed,
               "recently_accessed": $recently_accessed
           },
           "structure": {
               "maximum_depth": $max_depth
           }
       }' "$report_file" > "${report_file}.tmp" && mv "${report_file}.tmp" "$report_file"
    
    # Cleanup temp files
    rm -f "$duplicates_temp" "$extensions_temp"
}

# Optimization analysis
perform_optimization_analysis() {
    local target_path="$1"
    local report_file="$2"
    
    echo "Performing optimization analysis..."
    
    # Cache files
    local cache_files=$(find "$target_path" -path "*/Cache*" -o -name "*cache*" 2>/dev/null | wc -l)
    local cache_size=$(find "$target_path" -path "*/Cache*" -o -name "*cache*" -exec du -sk {} + 2>/dev/null | awk '{sum+=$1} END {print sum+0}')
    
    # Log files
    local log_files=$(find "$target_path" -name "*.log" 2>/dev/null | wc -l)
    local log_size=$(find "$target_path" -name "*.log" -exec du -sk {} + 2>/dev/null | awk '{sum+=$1} END {print sum+0}')
    
    # Temporary files
    local temp_files=$(find "$target_path" -name "*.tmp" -o -name "*.temp" -o -path "*/tmp/*" 2>/dev/null | wc -l)
    local temp_size=$(find "$target_path" -name "*.tmp" -o -name "*.temp" -o -path "*/tmp/*" -exec du -sk {} + 2>/dev/null | awk '{sum+=$1} END {print sum+0}')
    
    # Backup files
    local backup_files=$(find "$target_path" -name "*.bak" -o -name "*~" -o -name "*.backup" 2>/dev/null | wc -l)
    local backup_size=$(find "$target_path" -name "*.bak" -o -name "*~" -o -name "*.backup" -exec du -sk {} + 2>/dev/null | awk '{sum+=$1} END {print sum+0}')
    
    # Potential savings calculation
    local total_cleanup_kb=$((cache_size + log_size + temp_size + backup_size))
    local total_cleanup_mb=$((total_cleanup_kb / 1024))
    
    # Generate recommendations
    local recommendations=()
    [[ $cache_size -gt 102400 ]] && recommendations+=("Consider cleaning cache files (${cache_size} KB)")
    [[ $log_size -gt 51200 ]] && recommendations+=("Archive or clean old log files (${log_size} KB)")
    [[ $temp_size -gt 10240 ]] && recommendations+=("Remove temporary files (${temp_size} KB)")
    [[ $backup_size -gt 102400 ]] && recommendations+=("Review backup file retention (${backup_size} KB)")
    
    # Update report
    jq --argjson cache_files "$cache_files" \
       --argjson cache_size "$cache_size" \
       --argjson log_files "$log_files" \
       --argjson log_size "$log_size" \
       --argjson temp_files "$temp_files" \
       --argjson temp_size "$temp_size" \
       --argjson backup_files "$backup_files" \
       --argjson backup_size "$backup_size" \
       --argjson total_cleanup "$total_cleanup_kb" \
       --argjson recommendations "$(printf '%s\n' "${recommendations[@]}" | jq -R . | jq -s .)" \
       '.file_analysis.optimization = {
           "cache_files": {"count": $cache_files, "size_kb": $cache_size},
           "log_files": {"count": $log_files, "size_kb": $log_size},
           "temp_files": {"count": $temp_files, "size_kb": $temp_size},
           "backup_files": {"count": $backup_files, "size_kb": $backup_size},
           "potential_savings_kb": $total_cleanup,
           "potential_savings_mb": ($total_cleanup / 1024)
       } | .recommendations = $recommendations' "$report_file" > "${report_file}.tmp" && mv "${report_file}.tmp" "$report_file"
}

# Fleet storage management
manage_fleet_storage() {
    local action="$1"
    local target_pattern="$2"
    local threshold="$3"
    
    log_action "Fleet storage management: $action"
    
    case "$action" in
        "audit")
            audit_fleet_storage "$target_pattern"
            ;;
        "cleanup")
            cleanup_fleet_storage "$target_pattern" "$threshold"
            ;;
        "monitor")
            monitor_fleet_storage
            ;;
        "report")
            generate_fleet_storage_report
            ;;
    esac
}

# Generate fleet storage report
generate_fleet_storage_report() {
    local fleet_report="$REPORT_DIR/fleet_storage_report_$(date +%Y%m%d_%H%M%S).json"
    
    echo "Generating fleet storage report..."
    
    # System overview
    local total_disk_space=$(df -k / | awk 'NR==2 {print $2}')
    local used_disk_space=$(df -k / | awk 'NR==2 {print $3}')
    local available_disk_space=$(df -k / | awk 'NR==2 {print $4}')
    local disk_usage_percent=$(df / | awk 'NR==2 {print $5}' | sed 's/%//')
    
    cat > "$fleet_report" << EOF
{
    "fleet_storage_report": {
        "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
        "hostname": "$(hostname)",
        "system_overview": {
            "total_disk_kb": $total_disk_space,
            "used_disk_kb": $used_disk_space,
            "available_disk_kb": $available_disk_space,
            "usage_percent": $disk_usage_percent
        },
        "category_analysis": {},
        "alerts": [],
        "recommendations": []
    }
}
EOF
    
    # Analyze each storage category
    for category in "${!STORAGE_CATEGORIES[@]}"; do
        echo "Analyzing category: $category"
        IFS=',' read -ra PATHS <<< "${STORAGE_CATEGORIES[$category]}"
        local category_size=0
        local category_files=0
        
        for path in "${PATHS[@]}"; do
            if [[ -d "$path" ]]; then
                local path_size=$(du -sk "$path" 2>/dev/null | cut -f1)
                local path_files=$(find "$path" -type f 2>/dev/null | wc -l)
                category_size=$((category_size + path_size))
                category_files=$((category_files + path_files))
            fi
        done
        
        # Update report with category data
        jq --arg category "$category" \
           --argjson size "$category_size" \
           --argjson files "$category_files" \
           '.fleet_storage_report.category_analysis[$category] = {
               "size_kb": $size,
               "file_count": $files,
               "size_mb": ($size / 1024),
               "size_gb": ($size / 1048576)
           }' "$fleet_report" > "${fleet_report}.tmp" && mv "${fleet_report}.tmp" "$fleet_report"
    done
    
    # Generate alerts based on thresholds
    local alerts=()
    if [[ $disk_usage_percent -gt 90 ]]; then
        alerts+=("CRITICAL: Disk usage above 90% ($disk_usage_percent%)")
    elif [[ $disk_usage_percent -gt 80 ]]; then
        alerts+=("WARNING: Disk usage above 80% ($disk_usage_percent%)")
    fi
    
    # Add alerts to report
    if [[ ${#alerts[@]} -gt 0 ]]; then
        jq --argjson alerts "$(printf '%s\n' "${alerts[@]}" | jq -R . | jq -s .)" \
           '.fleet_storage_report.alerts = $alerts' "$fleet_report" > "${fleet_report}.tmp" && mv "${fleet_report}.tmp" "$fleet_report"
    fi
    
    log_action "Fleet storage report generated: $fleet_report"
    echo "$fleet_report"
}

# Main execution function
main() {
    local action="${1:-analyze}"
    local target="${2:-/Users}"
    local level="${3:-standard}"
    local options="${4:-}"
    
    log_action "=== MacFleet Storage Management Started ==="
    log_action "Action: $action, Target: $target, Level: $level"
    
    case "$action" in
        "analyze")
            analyze_storage_comprehensive "$target" "$level"
            ;;
        "size")
            echo "File/Folder size:"
            du -h "$target"
            ;;
        "fleet")
            manage_fleet_storage "$level" "$target" "$options"
            ;;
        "report")
            generate_fleet_storage_report
            ;;
        "help")
            echo "Usage: $0 [action] [target] [level] [options]"
            echo "Actions:"
            echo "  analyze <path> [level] - Comprehensive storage analysis"
            echo "  size <path> - Simple size check"
            echo "  fleet <action> [pattern] [threshold] - Fleet management"
            echo "  report - Generate fleet storage report"
            echo "  help - Show this help"
            echo ""
            echo "Analysis levels: quick, standard, comprehensive, optimization, security"
            echo "Fleet actions: audit, cleanup, monitor, report"
            ;;
        *)
            log_action "ERROR: Unknown action: $action"
            exit 1
            ;;
    esac
    
    log_action "=== Storage management completed ==="
}

# Execute main function
main "$@"

Common Storage Analysis Tasks

Directory Comparison

#!/bin/bash

# Compare sizes of multiple directories
compare_directories() {
    local directories=("$@")
    
    echo "=== Directory Size Comparison ==="
    printf "%-40s %15s %15s\n" "Directory" "Size" "Files"
    echo "--------------------------------------------------------------------------------"
    
    for dir in "${directories[@]}"; do
        if [[ -d "$dir" ]]; then
            local size=$(du -sh "$dir" 2>/dev/null | cut -f1)
            local files=$(find "$dir" -type f 2>/dev/null | wc -l)
            printf "%-40s %15s %15d\n" "$dir" "$size" "$files"
        else
            printf "%-40s %15s %15s\n" "$dir" "N/A" "N/A"
        fi
    done
}

# Usage
compare_directories "/Users/stefan/Documents" "/Users/stefan/Downloads" "/Users/stefan/Desktop"

Storage Growth Tracking

#!/bin/bash

# Track storage growth over time
track_storage_growth() {
    local target_path="$1"
    local log_file="/var/log/storage_growth.csv"
    
    # Create header if file doesn't exist
    if [[ ! -f "$log_file" ]]; then
        echo "timestamp,path,size_kb,files,directories" > "$log_file"
    fi
    
    # Get current metrics
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    local size_kb=$(du -sk "$target_path" 2>/dev/null | cut -f1)
    local files=$(find "$target_path" -type f 2>/dev/null | wc -l)
    local dirs=$(find "$target_path" -type d 2>/dev/null | wc -l)
    
    # Log current measurement
    echo "$timestamp,$target_path,$size_kb,$files,$dirs" >> "$log_file"
    
    echo "Storage growth logged for: $target_path"
    echo "Current size: $(echo "scale=2; $size_kb/1024" | bc) MB"
    echo "Files: $files, Directories: $dirs"
}

# Usage
track_storage_growth "/Users/stefan"

Cleanup Recommendations

#!/bin/bash

# Generate cleanup recommendations
generate_cleanup_recommendations() {
    local target_path="$1"
    
    echo "=== Cleanup Recommendations for: $target_path ==="
    
    # Old downloads
    local old_downloads=$(find "$target_path" -path "*/Downloads/*" -type f -mtime +30 2>/dev/null | wc -l)
    if [[ $old_downloads -gt 0 ]]; then
        echo "šŸ“ Found $old_downloads files in Downloads older than 30 days"
    fi
    
    # Large cache files
    local cache_size=$(find "$target_path" -path "*/Cache*" -type f -size +10M 2>/dev/null | wc -l)
    if [[ $cache_size -gt 0 ]]; then
        echo "šŸ—‚ļø  Found $cache_size large cache files (>10MB)"
    fi
    
    # Duplicate files
    local duplicates=$(find "$target_path" -type f -exec md5 {} \; 2>/dev/null | sort | uniq -d -w 32 | wc -l)
    if [[ $duplicates -gt 0 ]]; then
        echo "šŸ“„ Found approximately $duplicates duplicate files"
    fi
    
    # Empty directories
    local empty_dirs=$(find "$target_path" -type d -empty 2>/dev/null | wc -l)
    if [[ $empty_dirs -gt 0 ]]; then
        echo "šŸ“‚ Found $empty_dirs empty directories"
    fi
    
    # Log files
    local large_logs=$(find "$target_path" -name "*.log" -size +50M 2>/dev/null | wc -l)
    if [[ $large_logs -gt 0 ]]; then
        echo "šŸ“‹ Found $large_logs large log files (>50MB)"
    fi
    
    echo -e "\nšŸ’” Consider running cleanup operations for these items"
}

# Usage
generate_cleanup_recommendations "/Users"

Important Notes

  • File paths with spaces - Use quotes or escape characters: du -h "/path/with spaces"
  • Permission requirements - Some directories require admin access
  • Performance impact - Large directory scans can be resource-intensive
  • Regular monitoring - Set up automated storage monitoring for fleet management
  • Backup before cleanup - Always backup important data before cleanup operations
  • Test scripts on sample directories before fleet-wide deployment