Tutorial

Novas atualizações e melhorias para a Macfleet.

Aviso importante

Os exemplos de código e scripts fornecidos nestes tutoriais são apenas para fins educacionais. A Macfleet não é responsável por quaisquer problemas, danos ou vulnerabilidades de segurança que possam surgir do uso, modificação ou implementação destes exemplos. Sempre revise e teste o código em um ambiente seguro antes de usá-lo em sistemas de produção.

App Store Auto Updates Management on macOS

Control and manage App Store automatic updates on your MacFleet devices to optimize bandwidth usage, manage security updates, and maintain system stability. This tutorial covers update policies, enterprise configuration, and comprehensive update management strategies.

Understanding macOS App Store Auto Updates

App Store auto updates on macOS automatically download and install application updates from the Mac App Store. This feature affects:

  • Application Updates - Automatic installation of app updates
  • System Storage - Downloaded updates consume disk space
  • Network Bandwidth - Updates download in the background
  • System Stability - New updates may introduce bugs or compatibility issues

Enterprise Considerations

Managing auto updates is crucial for enterprise environments:

  • Bandwidth Control - Prevent unexpected network usage
  • Security Management - Control when security updates are applied
  • System Stability - Test updates before deployment
  • Storage Management - Prevent storage issues on limited-space devices
  • Compliance Requirements - Some industries require controlled update deployment

Basic App Store Update Control

Disable Auto Updates

#!/bin/bash

# Disable App Store auto updates
sudo defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool FALSE

echo "App Store auto updates disabled"
exit 0

Enable Auto Updates

#!/bin/bash

# Enable App Store auto updates
sudo defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool TRUE

echo "App Store auto updates enabled"
exit 0

Check Current Auto Update Status

#!/bin/bash

# Check current auto update setting
auto_update_status=$(defaults read /Library/Preferences/com.apple.commerce.plist AutoUpdate 2>/dev/null || echo "Not Set")

if [[ "$auto_update_status" == "1" ]]; then
    echo "App Store Auto Updates: ENABLED"
elif [[ "$auto_update_status" == "0" ]]; then
    echo "App Store Auto Updates: DISABLED"
else
    echo "App Store Auto Updates: DEFAULT (typically enabled)"
fi

Advanced Update Management

Comprehensive Update Policy Configuration

#!/bin/bash

# Advanced App Store update management with validation
configure_app_store_updates() {
    local policy="$1"
    local schedule="$2"
    local dry_run="${3:-false}"
    
    # Validate admin privileges
    if [[ $EUID -ne 0 ]]; then
        echo "Error: This script requires administrator privileges"
        echo "Please run with sudo: sudo $0"
        exit 1
    fi
    
    echo "=== Configuring App Store Update Policy: $policy ==="
    
    if [[ "$dry_run" == "true" ]]; then
        echo "DRY RUN MODE - No changes will be applied"
        return 0
    fi
    
    case "$policy" in
        "enterprise_controlled")
            echo "Applying enterprise controlled update policy..."
            
            # Disable auto updates for controlled environment
            defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool FALSE
            
            # Disable automatic download of updates
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload -bool FALSE
            
            # Disable critical updates installation
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist CriticalUpdateInstall -bool FALSE
            
            echo "✓ Enterprise controlled policy applied"
            ;;
        "security_only")
            echo "Applying security-only update policy..."
            
            # Disable general app updates
            defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool FALSE
            
            # Enable critical security updates only
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist CriticalUpdateInstall -bool TRUE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload -bool TRUE
            
            echo "✓ Security-only update policy applied"
            ;;
        "scheduled_updates")
            echo "Applying scheduled update policy..."
            
            # Disable immediate updates
            defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool FALSE
            
            # Configure scheduled update checking
            setup_scheduled_updates "$schedule"
            
            echo "✓ Scheduled update policy applied"
            ;;
        "bandwidth_conscious")
            echo "Applying bandwidth-conscious update policy..."
            
            # Disable automatic downloads
            defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool FALSE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload -bool FALSE
            
            # Enable update checking but not automatic installation
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticCheckEnabled -bool TRUE
            
            echo "✓ Bandwidth-conscious policy applied"
            ;;
        "full_auto")
            echo "Applying full automatic update policy..."
            
            # Enable all automatic updates
            defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool TRUE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload -bool TRUE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticCheckEnabled -bool TRUE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist CriticalUpdateInstall -bool TRUE
            
            echo "✓ Full automatic update policy applied"
            ;;
        "disabled")
            echo "Disabling all automatic updates..."
            
            # Disable all automatic update features
            defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool FALSE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload -bool FALSE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticCheckEnabled -bool FALSE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist CriticalUpdateInstall -bool FALSE
            
            echo "✓ All automatic updates disabled"
            ;;
        *)
            echo "Error: Unknown policy '$policy'"
            echo "Available policies: enterprise_controlled, security_only, scheduled_updates, bandwidth_conscious, full_auto, disabled"
            return 1
            ;;
    esac
    
    # Verify configuration
    verify_update_settings
}

# Setup scheduled updates
setup_scheduled_updates() {
    local schedule="$1"
    
    case "$schedule" in
        "weekly")
            # Create weekly update check
            create_update_schedule "weekly" "0 2 * * 1"
            ;;
        "monthly")
            # Create monthly update check
            create_update_schedule "monthly" "0 2 1 * *"
            ;;
        "daily_check")
            # Daily check, manual install
            create_update_schedule "daily_check" "0 8 * * *"
            ;;
        *)
            echo "Default schedule: weekly"
            create_update_schedule "weekly" "0 2 * * 1"
            ;;
    esac
}

# Create scheduled update tasks
create_update_schedule() {
    local schedule_name="$1"
    local cron_schedule="$2"
    
    local plist_path="/Library/LaunchDaemons/com.macfleet.updatecheck.plist"
    
    cat > "$plist_path" << 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.updatecheck</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/bin/python3</string>
        <string>/usr/local/bin/macfleet_update_checker.py</string>
    </array>
    <key>StartCalendarInterval</key>
    <dict>
        <key>Hour</key>
        <integer>2</integer>
        <key>Minute</key>
        <integer>0</integer>
        <key>Weekday</key>
        <integer>1</integer>
    </dict>
    <key>RunAtLoad</key>
    <false/>
</dict>
</plist>
EOF
    
    # Set proper permissions
    chown root:wheel "$plist_path"
    chmod 644 "$plist_path"
    
    echo "✓ Scheduled update check created: $schedule_name"
}

# Verify current update settings
verify_update_settings() {
    echo ""
    echo "=== Current Update Configuration ==="
    
    # Check App Store auto updates
    local app_store_auto=$(defaults read /Library/Preferences/com.apple.commerce.plist AutoUpdate 2>/dev/null || echo "Default")
    echo "App Store Auto Updates: $([ "$app_store_auto" == "1" ] && echo "Enabled" || [ "$app_store_auto" == "0" ] && echo "Disabled" || echo "Default (Enabled)")"
    
    # Check Software Update settings
    local auto_download=$(defaults read /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload 2>/dev/null || echo "Default")
    echo "Automatic Download: $([ "$auto_download" == "1" ] && echo "Enabled" || [ "$auto_download" == "0" ] && echo "Disabled" || echo "Default")"
    
    local auto_check=$(defaults read /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticCheckEnabled 2>/dev/null || echo "Default")
    echo "Automatic Check: $([ "$auto_check" == "1" ] && echo "Enabled" || [ "$auto_check" == "0" ] && echo "Disabled" || echo "Default")"
    
    local critical_updates=$(defaults read /Library/Preferences/com.apple.SoftwareUpdate.plist CriticalUpdateInstall 2>/dev/null || echo "Default")
    echo "Critical Updates: $([ "$critical_updates" == "1" ] && echo "Enabled" || [ "$critical_updates" == "0" ] && echo "Disabled" || echo "Default")"
}

# Usage examples
configure_app_store_updates "enterprise_controlled" "weekly"

Update Monitoring and Reporting

#!/bin/bash

# Monitor and report on update status
monitor_update_status() {
    local detailed="${1:-false}"
    
    echo "=== App Store Update Status Monitor ==="
    
    # Check for available updates
    echo "Checking for available updates..."
    local available_updates
    available_updates=$(softwareupdate -l 2>/dev/null | grep -c "recommended" || echo "0")
    
    echo "Available Updates: $available_updates"
    
    # Check last update check time
    local last_check
    last_check=$(defaults read /Library/Preferences/com.apple.SoftwareUpdate.plist LastSuccessfulDate 2>/dev/null || echo "Unknown")
    echo "Last Update Check: $last_check"
    
    # Check update history
    if [[ "$detailed" == "true" ]]; then
        echo ""
        echo "=== Detailed Update Information ==="
        
        # List available updates
        echo "Available Updates:"
        softwareupdate -l 2>/dev/null | grep -A 3 "recommended" || echo "No updates available"
        
        # Check update download cache
        local cache_size
        cache_size=$(du -sh /Library/Updates 2>/dev/null | cut -f1 || echo "0B")
        echo "Update Cache Size: $cache_size"
        
        # Check system version
        echo "Current System Version: $(sw_vers -productVersion)"
        echo "Build Version: $(sw_vers -buildVersion)"
    fi
}

# Generate update compliance report
generate_update_report() {
    local report_type="${1:-standard}"
    local output_file="${2:-/tmp/update_report_$(date +%Y%m%d_%H%M%S).json}"
    
    echo "=== Generating Update Report: $report_type ==="
    
    # Collect update information
    local hostname=$(hostname)
    local system_version=$(sw_vers -productVersion)
    local build_version=$(sw_vers -buildVersion)
    local app_store_auto=$(defaults read /Library/Preferences/com.apple.commerce.plist AutoUpdate 2>/dev/null || echo "default")
    local auto_download=$(defaults read /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload 2>/dev/null || echo "default")
    local last_check=$(defaults read /Library/Preferences/com.apple.SoftwareUpdate.plist LastSuccessfulDate 2>/dev/null || echo "unknown")
    
    # Get available updates list
    local available_updates
    available_updates=$(softwareupdate -l 2>/dev/null | grep "recommended" | wc -l | tr -d ' ')
    
    cat > "$output_file" << EOF
{
    "update_report": {
        "report_type": "$report_type",
        "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
        "hostname": "$hostname",
        "system_info": {
            "system_version": "$system_version",
            "build_version": "$build_version"
        },
        "update_settings": {
            "app_store_auto_update": "$app_store_auto",
            "automatic_download": "$auto_download",
            "last_update_check": "$last_check"
        },
        "update_status": {
            "available_updates": $available_updates,
            "pending_restarts": false
        }
    }
}
EOF
    
    echo "✓ Update report generated: $output_file"
    echo "$output_file"
}

# Usage
monitor_update_status "true"
generate_update_report "compliance"

Enterprise App Store Update Management System

#!/bin/bash

# MacFleet App Store Update Management Tool
# Comprehensive update policy management and monitoring for fleet devices

# Configuration
SCRIPT_VERSION="1.0.0"
LOG_FILE="/var/log/macfleet_appstore_updates.log"
REPORT_DIR="/etc/macfleet/reports/updates"
CONFIG_DIR="/etc/macfleet/updates"
POLICY_DIR="/etc/macfleet/policies/updates"

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

# Update policy templates
declare -A UPDATE_POLICIES=(
    ["enterprise_strict"]="app_updates_disabled,system_updates_manual,security_updates_auto,bandwidth_priority_high"
    ["enterprise_balanced"]="app_updates_scheduled,system_updates_auto,security_updates_immediate,bandwidth_priority_medium"
    ["enterprise_liberal"]="app_updates_auto,system_updates_auto,security_updates_immediate,bandwidth_priority_low"
    ["kiosk_mode"]="app_updates_disabled,system_updates_disabled,security_updates_manual,bandwidth_priority_high"
    ["development"]="app_updates_auto,system_updates_prompt,security_updates_auto,bandwidth_priority_low"
    ["education"]="app_updates_scheduled,system_updates_scheduled,security_updates_auto,bandwidth_priority_medium"
    ["healthcare"]="app_updates_manual,system_updates_manual,security_updates_immediate,bandwidth_priority_high"
    ["financial"]="app_updates_disabled,system_updates_manual,security_updates_immediate,bandwidth_priority_high"
    ["retail"]="app_updates_scheduled,system_updates_auto,security_updates_auto,bandwidth_priority_medium"
    ["remote_work"]="app_updates_auto,system_updates_prompt,security_updates_auto,bandwidth_priority_medium"
)

# Update schedules for different scenarios
declare -A UPDATE_SCHEDULES=(
    ["business_hours"]="weekdays_evening,09:00-17:00_block"
    ["maintenance_window"]="weekend_only,saturday_2am"
    ["off_peak"]="overnight,02:00-05:00"
    ["immediate"]="real_time,no_delay"
    ["weekly_batch"]="sunday_night,sunday_23:00"
    ["monthly_patch"]="first_sunday,monthly_02:00"
)

# Bandwidth management profiles
declare -A BANDWIDTH_PROFILES=(
    ["conservative"]="max_5mbps,off_peak_only,cellular_disabled"
    ["balanced"]="max_20mbps,business_hours_limited,cellular_security_only"
    ["unlimited"]="no_throttle,anytime,cellular_enabled"
    ["emergency_only"]="max_1mbps,security_updates_only,cellular_emergency"
)

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

# Advanced update policy enforcement
enforce_update_policy() {
    local policy_name="$1"
    local environment_type="${2:-enterprise}"
    local bandwidth_profile="${3:-balanced}"
    local dry_run="${4:-false}"
    
    log_action "Enforcing update policy: $policy_name (environment: $environment_type, bandwidth: $bandwidth_profile, dry_run: $dry_run)"
    
    if [[ -z "${UPDATE_POLICIES[$policy_name]}" ]]; then
        log_action "ERROR: Unknown policy '$policy_name'"
        echo "Available policies: ${!UPDATE_POLICIES[*]}"
        return 1
    fi
    
    # Parse policy configuration
    IFS=',' read -ra POLICY_PARTS <<< "${UPDATE_POLICIES[$policy_name]}"
    local app_updates="${POLICY_PARTS[0]}"
    local system_updates="${POLICY_PARTS[1]}"
    local security_updates="${POLICY_PARTS[2]}"
    local bandwidth_priority="${POLICY_PARTS[3]}"
    
    echo "=== Enforcing Update Policy: $policy_name ==="
    echo "App Updates: $app_updates"
    echo "System Updates: $system_updates"
    echo "Security Updates: $security_updates"
    echo "Bandwidth Priority: $bandwidth_priority"
    echo "Environment: $environment_type"
    
    if [[ "$dry_run" == "true" ]]; then
        echo "DRY RUN MODE - No changes will be applied"
        return 0
    fi
    
    # Apply app update settings
    apply_app_update_policy "$app_updates"
    
    # Apply system update settings
    apply_system_update_policy "$system_updates"
    
    # Apply security update settings
    apply_security_update_policy "$security_updates"
    
    # Apply bandwidth management
    apply_bandwidth_management "$bandwidth_profile"
    
    # Configure environment-specific settings
    configure_environment_settings "$environment_type"
    
    # Generate policy compliance report
    local report_file="$REPORT_DIR/policy_enforcement_${policy_name}_$(date +%Y%m%d_%H%M%S).json"
    generate_comprehensive_report "$policy_name" "$report_file"
    
    log_action "Update policy enforcement completed: $report_file"
    echo "$report_file"
}

# Apply app update policy settings
apply_app_update_policy() {
    local policy="$1"
    
    case "$policy" in
        "app_updates_disabled")
            defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool FALSE
            echo "✓ App Store auto updates disabled"
            ;;
        "app_updates_auto")
            defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool TRUE
            echo "✓ App Store auto updates enabled"
            ;;
        "app_updates_scheduled")
            defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool FALSE
            setup_scheduled_app_updates "weekly"
            echo "✓ App Store updates scheduled for weekly maintenance window"
            ;;
        "app_updates_manual")
            defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool FALSE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticCheckEnabled -bool TRUE
            echo "✓ App Store updates set to manual with automatic checking"
            ;;
    esac
}

# Apply system update policy settings
apply_system_update_policy() {
    local policy="$1"
    
    case "$policy" in
        "system_updates_disabled")
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticCheckEnabled -bool FALSE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload -bool FALSE
            echo "✓ System updates completely disabled"
            ;;
        "system_updates_auto")
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticCheckEnabled -bool TRUE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload -bool TRUE
            echo "✓ System updates fully automated"
            ;;
        "system_updates_manual")
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticCheckEnabled -bool TRUE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload -bool FALSE
            echo "✓ System updates set to manual installation"
            ;;
        "system_updates_prompt")
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticCheckEnabled -bool TRUE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload -bool TRUE
            # Configure user prompts for installation
            echo "✓ System updates set to prompt user for installation"
            ;;
        "system_updates_scheduled")
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticCheckEnabled -bool TRUE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload -bool TRUE
            setup_scheduled_system_updates "monthly"
            echo "✓ System updates scheduled for monthly maintenance"
            ;;
    esac
}

# Apply security update policy settings
apply_security_update_policy() {
    local policy="$1"
    
    case "$policy" in
        "security_updates_immediate")
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist CriticalUpdateInstall -bool TRUE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticCheckEnabled -bool TRUE
            echo "✓ Security updates set to immediate installation"
            ;;
        "security_updates_auto")
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist CriticalUpdateInstall -bool TRUE
            echo "✓ Security updates enabled for automatic installation"
            ;;
        "security_updates_manual")
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist CriticalUpdateInstall -bool FALSE
            echo "✓ Security updates set to manual installation"
            ;;
    esac
}

# Apply bandwidth management settings
apply_bandwidth_management() {
    local profile="$1"
    
    if [[ -z "${BANDWIDTH_PROFILES[$profile]}" ]]; then
        echo "Warning: Unknown bandwidth profile '$profile', using default"
        profile="balanced"
    fi
    
    # Parse bandwidth configuration
    IFS=',' read -ra BANDWIDTH_PARTS <<< "${BANDWIDTH_PROFILES[$profile]}"
    local max_bandwidth="${BANDWIDTH_PARTS[0]}"
    local time_restrictions="${BANDWIDTH_PARTS[1]}"
    local cellular_policy="${BANDWIDTH_PARTS[2]}"
    
    echo "✓ Bandwidth management applied: $profile"
    echo "  Max Bandwidth: $max_bandwidth"
    echo "  Time Restrictions: $time_restrictions"
    echo "  Cellular Policy: $cellular_policy"
    
    # Configure bandwidth throttling (implementation would depend on network tools)
    configure_bandwidth_throttling "$max_bandwidth" "$time_restrictions"
}

# Configure environment-specific settings
configure_environment_settings() {
    local environment="$1"
    
    case "$environment" in
        "healthcare")
            # HIPAA compliance settings
            configure_hipaa_update_compliance
            echo "✓ Healthcare/HIPAA update compliance configured"
            ;;
        "financial")
            # Financial services compliance
            configure_financial_update_compliance
            echo "✓ Financial services update compliance configured"
            ;;
        "education")
            # Educational institution settings
            configure_education_update_settings
            echo "✓ Educational environment update settings configured"
            ;;
        "kiosk")
            # Kiosk-specific restrictions
            configure_kiosk_update_restrictions
            echo "✓ Kiosk update restrictions configured"
            ;;
        "enterprise")
            # Standard enterprise settings
            configure_enterprise_update_settings
            echo "✓ Enterprise update settings configured"
            ;;
    esac
}

# Setup scheduled app updates
setup_scheduled_app_updates() {
    local frequency="$1"
    
    local script_path="/usr/local/bin/macfleet_scheduled_app_updates.sh"
    
    cat > "$script_path" << 'EOF'
#!/bin/bash
# MacFleet Scheduled App Updates
LOG_FILE="/var/log/macfleet_scheduled_updates.log"

echo "$(date): Starting scheduled app update check" >> "$LOG_FILE"

# Check for app updates
available_updates=$(softwareupdate -l 2>/dev/null | grep -c "recommended" || echo "0")

if [[ "$available_updates" -gt 0 ]]; then
    echo "$(date): Found $available_updates available updates" >> "$LOG_FILE"
    
    # Download updates but don't install (for approval process)
    softwareupdate -d -a >> "$LOG_FILE" 2>&1
    
    # Notify administrators
    echo "$(date): Updates downloaded, awaiting approval" >> "$LOG_FILE"
else
    echo "$(date): No updates available" >> "$LOG_FILE"
fi
EOF
    
    chmod +x "$script_path"
    
    # Create launchd job based on frequency
    create_update_launchd_job "$frequency" "$script_path"
}

# Generate comprehensive update report
generate_comprehensive_report() {
    local policy_name="$1"
    local report_file="$2"
    
    # Collect comprehensive update information
    local hostname=$(hostname)
    local system_version=$(sw_vers -productVersion)
    local build_version=$(sw_vers -buildVersion)
    local uptime=$(uptime | awk '{print $3,$4}' | sed 's/,//')
    
    # Get current settings
    local app_store_auto=$(defaults read /Library/Preferences/com.apple.commerce.plist AutoUpdate 2>/dev/null || echo "default")
    local auto_download=$(defaults read /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload 2>/dev/null || echo "default")
    local auto_check=$(defaults read /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticCheckEnabled 2>/dev/null || echo "default")
    local critical_updates=$(defaults read /Library/Preferences/com.apple.SoftwareUpdate.plist CriticalUpdateInstall 2>/dev/null || echo "default")
    
    # Get update status
    local available_updates=$(softwareupdate -l 2>/dev/null | grep -c "recommended" || echo "0")
    local last_check=$(defaults read /Library/Preferences/com.apple.SoftwareUpdate.plist LastSuccessfulDate 2>/dev/null || echo "unknown")
    local cache_size=$(du -sh /Library/Updates 2>/dev/null | cut -f1 || echo "0B")
    
    cat > "$report_file" << EOF
{
    "comprehensive_update_report": {
        "policy_name": "$policy_name",
        "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
        "hostname": "$hostname",
        "script_version": "$SCRIPT_VERSION",
        "system_info": {
            "system_version": "$system_version",
            "build_version": "$build_version",
            "uptime": "$uptime"
        },
        "update_settings": {
            "app_store_auto_update": "$app_store_auto",
            "automatic_download": "$auto_download",
            "automatic_check": "$auto_check",
            "critical_updates": "$critical_updates"
        },
        "update_status": {
            "available_updates": $available_updates,
            "last_check": "$last_check",
            "cache_size": "$cache_size"
        },
        "compliance_status": "compliant",
        "policy_enforcement_date": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
    }
}
EOF
    
    log_action "Comprehensive update report generated: $report_file"
}

# Monitor update compliance across fleet
monitor_fleet_update_compliance() {
    local compliance_type="${1:-standard}"
    
    echo "=== Fleet Update Compliance Monitor ==="
    
    # Check overall compliance status
    local policy_violations=0
    local total_checks=0
    
    # Verify App Store settings
    local app_store_setting=$(defaults read /Library/Preferences/com.apple.commerce.plist AutoUpdate 2>/dev/null || echo "default")
    ((total_checks++))
    
    # Check for pending updates that violate policy
    local pending_updates=$(softwareupdate -l 2>/dev/null | grep -c "recommended" || echo "0")
    
    if [[ "$pending_updates" -gt 0 && "$compliance_type" == "strict" ]]; then
        ((policy_violations++))
        echo "⚠️ Policy Violation: Pending updates found in strict compliance mode"
    fi
    
    # Calculate compliance score
    local compliance_score=$((100 - (policy_violations * 100 / total_checks)))
    
    echo "Compliance Score: $compliance_score%"
    echo "Policy Violations: $policy_violations"
    echo "Total Checks: $total_checks"
    echo "Pending Updates: $pending_updates"
    
    # Generate compliance summary
    local compliance_file="$REPORT_DIR/fleet_compliance_$(date +%Y%m%d_%H%M%S).json"
    cat > "$compliance_file" << EOF
{
    "fleet_compliance": {
        "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
        "compliance_type": "$compliance_type",
        "compliance_score": $compliance_score,
        "policy_violations": $policy_violations,
        "total_checks": $total_checks,
        "pending_updates": $pending_updates,
        "hostname": "$(hostname)"
    }
}
EOF
    
    echo "✓ Fleet compliance report: $compliance_file"
}

# Main execution function
main() {
    local action="${1:-status}"
    local param1="${2:-}"
    local param2="${3:-}"
    local param3="${4:-}"
    local param4="${5:-}"
    
    log_action "=== MacFleet App Store Update Management Started ==="
    log_action "Action: $action"
    
    # Ensure required privileges for configuration changes
    if [[ "$action" != "status" && "$action" != "help" && "$action" != "report" && $EUID -ne 0 ]]; then
        echo "Error: This action requires administrator privileges"
        echo "Please run with sudo: sudo $0 $*"
        exit 1
    fi
    
    case "$action" in
        "policy")
            if [[ -z "$param1" ]]; then
                echo "Available policies: ${!UPDATE_POLICIES[*]}"
                exit 1
            fi
            enforce_update_policy "$param1" "$param2" "$param3" "$param4"
            ;;
        "enable")
            defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool TRUE
            echo "✓ App Store auto updates enabled"
            ;;
        "disable")
            defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool FALSE
            echo "✓ App Store auto updates disabled"
            ;;
        "check")
            echo "Checking for available updates..."
            softwareupdate -l
            ;;
        "install")
            if [[ -n "$param1" ]]; then
                echo "Installing specific update: $param1"
                softwareupdate -i "$param1"
            else
                echo "Installing all available updates..."
                softwareupdate -i -a
            fi
            ;;
        "status")
            verify_update_settings
            if [[ "$param1" == "detailed" ]]; then
                monitor_update_status "true"
            fi
            ;;
        "report")
            generate_comprehensive_report "${param1:-current}" "${param2:-/tmp/update_report_$(date +%Y%m%d_%H%M%S).json}"
            ;;
        "compliance")
            monitor_fleet_update_compliance "$param1"
            ;;
        "reset")
            echo "Resetting App Store update settings to defaults..."
            defaults delete /Library/Preferences/com.apple.commerce.plist AutoUpdate 2>/dev/null || true
            defaults delete /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload 2>/dev/null || true
            defaults delete /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticCheckEnabled 2>/dev/null || true
            defaults delete /Library/Preferences/com.apple.SoftwareUpdate.plist CriticalUpdateInstall 2>/dev/null || true
            echo "✓ Update settings reset to system defaults"
            ;;
        "help")
            echo "Usage: $0 [action] [options...]"
            echo "Actions:"
            echo "  policy <policy_name> [environment] [bandwidth] [dry_run] - Apply update policy"
            echo "  enable - Enable App Store auto updates"
            echo "  disable - Disable App Store auto updates"
            echo "  check - Check for available updates"
            echo "  install [update_name] - Install updates (all or specific)"
            echo "  status [detailed] - Show current update configuration"
            echo "  report [policy_name] [output_file] - Generate update report"
            echo "  compliance [type] - Check fleet compliance"
            echo "  reset - Reset to system defaults"
            echo "  help - Show this help"
            echo ""
            echo "Policies: ${!UPDATE_POLICIES[*]}"
            echo "Schedules: ${!UPDATE_SCHEDULES[*]}"
            echo "Bandwidth Profiles: ${!BANDWIDTH_PROFILES[*]}"
            ;;
        *)
            log_action "ERROR: Unknown action: $action"
            echo "Use '$0 help' for usage information"
            exit 1
            ;;
    esac
    
    log_action "=== App Store update management completed ==="
}

# Execute main function
main "$@"

Update Security and Compliance

Healthcare/HIPAA Compliance

#!/bin/bash

# Configure HIPAA-compliant update management
configure_hipaa_update_compliance() {
    echo "=== Configuring HIPAA Update Compliance ==="
    
    # Disable automatic updates for compliance control
    defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool FALSE
    defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload -bool FALSE
    
    # Enable security updates only
    defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist CriticalUpdateInstall -bool TRUE
    
    # Configure audit logging
    setup_update_audit_logging "hipaa"
    
    echo "✓ HIPAA update compliance configured"
}

# Setup audit logging for compliance
setup_update_audit_logging() {
    local compliance_type="$1"
    local audit_file="/var/log/macfleet_update_audit.log"
    
    # Create audit script
    cat > "/usr/local/bin/macfleet_update_audit.sh" << 'EOF'
#!/bin/bash
AUDIT_LOG="/var/log/macfleet_update_audit.log"

log_update_event() {
    local event_type="$1"
    local details="$2"
    echo "$(date -u +%Y-%m-%dT%H:%M:%SZ) | $event_type | $(whoami) | $details" >> "$AUDIT_LOG"
}

# Monitor for update events
log_update_event "AUDIT_START" "Update audit monitoring started"
EOF
    
    chmod +x "/usr/local/bin/macfleet_update_audit.sh"
    echo "✓ Update audit logging configured for $compliance_type"
}

configure_hipaa_update_compliance

Financial Services Compliance

#!/bin/bash

# Configure financial services update compliance
configure_financial_update_compliance() {
    echo "=== Configuring Financial Services Update Compliance ==="
    
    # Strict update control for financial compliance
    defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool FALSE
    defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload -bool FALSE
    defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticCheckEnabled -bool TRUE
    
    # Security updates only with manual approval
    defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist CriticalUpdateInstall -bool FALSE
    
    # Configure change management integration
    setup_change_management_integration "financial"
    
    echo "✓ Financial services update compliance configured"
}

configure_financial_update_compliance

Troubleshooting and Maintenance

Update System Health Check

#!/bin/bash

# Comprehensive update system health check
perform_update_health_check() {
    echo "=== Update System Health Check ==="
    
    # Check update service status
    local update_service_status
    update_service_status=$(launchctl list | grep -c "com.apple.softwareupdated" || echo "0")
    echo "Software Update Service: $([ "$update_service_status" -gt 0 ] && echo "Running" || echo "Not Running")"
    
    # Check update cache
    local cache_path="/Library/Updates"
    if [[ -d "$cache_path" ]]; then
        local cache_size=$(du -sh "$cache_path" | cut -f1)
        local cache_files=$(find "$cache_path" -type f | wc -l | tr -d ' ')
        echo "Update Cache: $cache_size ($cache_files files)"
    else
        echo "Update Cache: Not present"
    fi
    
    # Check for corrupted preferences
    local commerce_plist="/Library/Preferences/com.apple.commerce.plist"
    local softwareupdate_plist="/Library/Preferences/com.apple.SoftwareUpdate.plist"
    
    if plutil -lint "$commerce_plist" &>/dev/null; then
        echo "Commerce Preferences: Valid"
    else
        echo "⚠️ Commerce Preferences: Corrupted or missing"
    fi
    
    if plutil -lint "$softwareupdate_plist" &>/dev/null; then
        echo "Software Update Preferences: Valid"
    else
        echo "⚠️ Software Update Preferences: Corrupted or missing"
    fi
    
    # Check network connectivity for updates
    if curl -s --connect-timeout 5 "https://swscan.apple.com/" &>/dev/null; then
        echo "Apple Update Servers: Accessible"
    else
        echo "⚠️ Apple Update Servers: Not accessible"
    fi
}

perform_update_health_check

Important Notes

  • Administrator privileges required for update configuration changes
  • Restart requirements - Some settings take effect after restart
  • Network impact - Consider bandwidth usage for automatic updates
  • Security implications - Balance automation with security control
  • Compliance requirements - Some industries require manual update approval
  • Storage considerations - Downloaded updates consume disk space
  • Testing recommendations - Test update policies on staging devices first
  • Monitoring importance - Regular compliance checking prevents policy drift

Tutorial

Novas atualizações e melhorias para a Macfleet.

Configurando um Runner do GitHub Actions em um Mac Mini (Apple Silicon)

Runner do GitHub Actions

GitHub Actions é uma plataforma poderosa de CI/CD que permite automatizar seus fluxos de trabalho de desenvolvimento de software. Embora o GitHub ofereça runners hospedados, runners auto-hospedados fornecem maior controle e personalização para sua configuração de CI/CD. Este tutorial o guia através da configuração e conexão de um runner auto-hospedado em um Mac mini para executar pipelines do macOS.

Pré-requisitos

Antes de começar, certifique-se de ter:

  • Um Mac mini (registre-se no Macfleet)
  • Um repositório GitHub com direitos de administrador
  • Um gerenciador de pacotes instalado (preferencialmente Homebrew)
  • Git instalado em seu sistema

Passo 1: Criar uma Conta de Usuário Dedicada

Primeiro, crie uma conta de usuário dedicada para o runner do GitHub Actions:

# Criar a conta de usuário 'gh-runner'
sudo dscl . -create /Users/gh-runner
sudo dscl . -create /Users/gh-runner UserShell /bin/bash
sudo dscl . -create /Users/gh-runner RealName "GitHub runner"
sudo dscl . -create /Users/gh-runner UniqueID "1001"
sudo dscl . -create /Users/gh-runner PrimaryGroupID 20
sudo dscl . -create /Users/gh-runner NFSHomeDirectory /Users/gh-runner

# Definir a senha para o usuário
sudo dscl . -passwd /Users/gh-runner sua_senha

# Adicionar 'gh-runner' ao grupo 'admin'
sudo dscl . -append /Groups/admin GroupMembership gh-runner

Mude para a nova conta de usuário:

su gh-runner

Passo 2: Instalar Software Necessário

Instale Git e Rosetta 2 (se estiver usando Apple Silicon):

# Instalar Git se ainda não estiver instalado
brew install git

# Instalar Rosetta 2 para Macs Apple Silicon
softwareupdate --install-rosetta

Passo 3: Configurar o Runner do GitHub Actions

  1. Vá para seu repositório GitHub
  2. Navegue para Configurações > Actions > Runners

Runner do GitHub Actions

  1. Clique em "New self-hosted runner" (https://github.com/<username>/<repository>/settings/actions/runners/new)
  2. Selecione macOS como imagem do runner e ARM64 como arquitetura
  3. Siga os comandos fornecidos para baixar e configurar o runner

Runner do GitHub Actions

Crie um arquivo .env no diretório _work do runner:

# arquivo _work/.env
ImageOS=macos15
XCODE_15_DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer
  1. Execute o script run.sh em seu diretório do runner para completar a configuração.
  2. Verifique se o runner está ativo e ouvindo por trabalhos no terminal e verifique as configurações do repositório GitHub para a associação do runner e status Idle.

Runner do GitHub Actions

Passo 4: Configurar Sudoers (Opcional)

Se suas ações requerem privilégios de root, configure o arquivo sudoers:

sudo visudo

Adicione a seguinte linha:

gh-runner ALL=(ALL) NOPASSWD: ALL

Passo 5: Usar o Runner em Fluxos de Trabalho

Configure seu fluxo de trabalho do GitHub Actions para usar o runner auto-hospedado:

name: Fluxo de trabalho de exemplo

on:
  workflow_dispatch:

jobs:
  build:
    runs-on: [self-hosted, macOS, ARM64]
    steps:
      - name: Instalar NodeJS
        run: brew install node

O runner está autenticado em seu repositório e rotulado com self-hosted, macOS, e ARM64. Use-o em seus fluxos de trabalho especificando estes rótulos no campo runs-on:

runs-on: [self-hosted, macOS, ARM64]

Melhores Práticas

  • Mantenha seu software do runner atualizado
  • Monitore regularmente os logs do runner para problemas
  • Use rótulos específicos para diferentes tipos de runners
  • Implemente medidas de segurança adequadas
  • Considere usar múltiplos runners para balanceamento de carga

Solução de Problemas

Problemas comuns e soluções:

  1. Runner não conectando:

    • Verifique conectividade de rede
    • Verifique validade do token GitHub
    • Certifique-se de permissões adequadas
  2. Falhas de build:

    • Verifique instalação do Xcode
    • Verifique dependências necessárias
    • Revise logs do fluxo de trabalho
  3. Problemas de permissão:

    • Verifique permissões do usuário
    • Verifique configuração sudoers
    • Revise permissões do sistema de arquivos

Conclusão

Agora você tem um runner auto-hospedado do GitHub Actions configurado em seu Mac mini. Esta configuração fornece mais controle sobre seu ambiente CI/CD e permite executar fluxos de trabalho específicos do macOS de forma eficiente.

Lembre-se de manter regularmente seu runner e mantê-lo atualizado com os patches de segurança e versões de software mais recentes.

Aplicativo Nativo

Aplicativo nativo do Macfleet

Guia de Instalação do Macfleet

Macfleet é uma solução poderosa de gerenciamento de frota projetada especificamente para ambientes Mac Mini hospedados na nuvem. Como provedor de hospedagem na nuvem Mac Mini, você pode usar o Macfleet para monitorar, gerenciar e otimizar toda sua frota de instâncias Mac virtualizadas.

Este guia de instalação o conduzirá através da configuração do monitoramento do Macfleet em sistemas macOS, Windows e Linux para garantir supervisão abrangente de sua infraestrutura na nuvem.

🍎 macOS

  • Baixe o arquivo .dmg para Mac aqui
  • Clique duas vezes no arquivo .dmg baixado
  • Arraste o aplicativo Macfleet para a pasta Aplicativos
  • Ejete o arquivo .dmg
  • Abra Preferências do Sistema > Segurança e Privacidade
    • Aba Privacidade > Acessibilidade
    • Marque Macfleet para permitir monitoramento
  • Inicie o Macfleet a partir de Aplicativos
  • O rastreamento inicia automaticamente

🪟 Windows

  • Baixe o arquivo .exe para Windows aqui
  • Clique com o botão direito no arquivo .exe > "Executar como administrador"
  • Siga o assistente de instalação
  • Aceite os termos e condições
  • Permita no Windows Defender se solicitado
  • Conceda permissões de monitoramento de aplicativo
  • Inicie o Macfleet a partir do Menu Iniciar
  • O aplicativo começa o rastreamento automaticamente

🐧 Linux

  • Baixe o pacote .deb (Ubuntu/Debian) ou .rpm (CentOS/RHEL) aqui
  • Instale usando seu gerenciador de pacotes
    • Ubuntu/Debian: sudo dpkg -i Macfleet-linux.deb
    • CentOS/RHEL: sudo rpm -ivh Macfleet-linux.rpm
  • Permita permissões de acesso X11 se solicitado
  • Adicione o usuário aos grupos apropriados se necessário
  • Inicie o Macfleet a partir do menu Aplicativos
  • O aplicativo começa o rastreamento automaticamente

Nota: Após a instalação em todos os sistemas, faça login com suas credenciais do Macfleet para sincronizar dados com seu painel de controle.