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.

Time Machine Backup Management on macOS

Manage and automate Time Machine backups across your MacFleet with enterprise-grade backup policies and disaster recovery capabilities. This tutorial covers advanced backup management, fleet-wide deployment, compliance monitoring, and automated recovery systems.

Understanding Enterprise Time Machine Management

Enterprise backup management requires:

  • 🔄 Automated backup policies - Consistent backup schedules across all devices
  • 🛡️ Disaster recovery planning - Fast recovery from data loss incidents
  • 📊 Compliance monitoring - Audit trails and regulatory compliance
  • ⚡ Fleet-wide management - Centralized backup control and reporting
  • 🔐 Security and encryption - Protected backup data with access controls

Basic Time Machine Operations

Set Backup Destination

#!/bin/bash

# Set Time Machine backup destination
BACKUP_DESTINATION="/Volumes/BackupDrive"

if [[ -d "$BACKUP_DESTINATION" ]]; then
    sudo tmutil setdestination "$BACKUP_DESTINATION"
    echo "✅ Backup destination set to: $BACKUP_DESTINATION"
else
    echo "❌ Backup destination not found: $BACKUP_DESTINATION"
    exit 1
fi

Enable and Start Backup

#!/bin/bash

# Enable Time Machine and start backup
sudo tmutil enable
sudo tmutil startbackup

echo "✅ Time Machine enabled and backup started"

Check Backup Status

#!/bin/bash

# Check current backup status
tmutil status

echo "📊 Current backup status displayed"

List Available Backups

#!/bin/bash

# List all available backups
tmutil listbackups

echo "📋 Available backups listed"

Advanced Backup Management

Intelligent Backup Destination Setup

#!/bin/bash

# Intelligent backup destination with validation
setup_backup_destination() {
    local destination="$1"
    local min_space_gb="${2:-100}"  # Minimum 100GB by default
    
    echo "🔍 Validating backup destination: $destination"
    
    # Check if destination exists
    if [[ ! -d "$destination" ]]; then
        echo "❌ Destination directory does not exist: $destination"
        return 1
    fi
    
    # Check available space
    local available_space=$(df -BG "$destination" | tail -1 | awk '{print $4}' | sed 's/G//')
    
    if [[ $available_space -lt $min_space_gb ]]; then
        echo "❌ Insufficient space: ${available_space}GB available, ${min_space_gb}GB required"
        return 1
    fi
    
    # Check write permissions
    if [[ ! -w "$destination" ]]; then
        echo "❌ No write permission to destination: $destination"
        return 1
    fi
    
    # Set the destination
    sudo tmutil setdestination "$destination"
    
    if [[ $? -eq 0 ]]; then
        echo "✅ Backup destination successfully set: $destination"
        echo "📊 Available space: ${available_space}GB"
        return 0
    else
        echo "❌ Failed to set backup destination"
        return 1
    fi
}

# Usage example
setup_backup_destination "/Volumes/Enterprise_Backup" 500

Advanced Exclusion Management

#!/bin/bash

# Enterprise backup exclusion management
manage_backup_exclusions() {
    local action="$1"  # add, remove, list
    local path="$2"
    
    case "$action" in
        "add")
            if [[ -n "$path" ]]; then
                sudo tmutil addexclusion "$path"
                echo "✅ Added exclusion: $path"
                log_exclusion_change "added" "$path"
            else
                echo "❌ Path required for add operation"
                return 1
            fi
            ;;
        "remove")
            if [[ -n "$path" ]]; then
                sudo tmutil removeexclusion "$path"
                echo "✅ Removed exclusion: $path"
                log_exclusion_change "removed" "$path"
            else
                echo "❌ Path required for remove operation"
                return 1
            fi
            ;;
        "list")
            echo "📋 Current exclusions:"
            tmutil listbackups | while read -r backup; do
                if [[ -d "$backup" ]]; then
                    echo "Checking exclusions for: $backup"
                    # List exclusions would require parsing backup metadata
                fi
            done
            ;;
        "enterprise_defaults")
            apply_enterprise_exclusions
            ;;
        *)
            echo "❌ Invalid action: $action"
            echo "Available actions: add, remove, list, enterprise_defaults"
            return 1
            ;;
    esac
}

# Apply standard enterprise exclusions
apply_enterprise_exclusions() {
    echo "🏢 Applying enterprise backup exclusions..."
    
    local exclusions=(
        "/System/Library/Caches"
        "/Library/Caches"
        "~/Library/Caches"
        "/private/var/vm"
        "/cores"
        "/tmp"
        "/private/tmp"
        "~/.Trash"
        "/Applications/Xcode.app/Contents/Developer/Platforms"  # Large dev files
        "/usr/local/var/log"  # Log files
        "~/Downloads"  # Temporary downloads
    )
    
    for exclusion in "${exclusions[@]}"; do
        sudo tmutil addexclusion "$exclusion" 2>/dev/null
        echo "Added exclusion: $exclusion"
    done
    
    echo "✅ Enterprise exclusions applied"
}

# Log exclusion changes for audit
log_exclusion_change() {
    local action="$1"
    local path="$2"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    local log_entry="[$timestamp] Exclusion $action: $path"
    
    echo "$log_entry" >> "/var/log/macfleet_backup_exclusions.log"
}

Backup Health Monitoring

#!/bin/bash

# Comprehensive backup health assessment
assess_backup_health() {
    echo "🏥 Assessing Time Machine backup health..."
    
    local health_score=100
    local issues=()
    local warnings=()
    
    # Check if Time Machine is enabled
    local tm_enabled=$(tmutil status | grep "Running" | wc -l)
    if [[ $tm_enabled -eq 0 ]]; then
        health_score=$((health_score - 30))
        issues+=("Time Machine is not running")
    fi
    
    # Check backup destination accessibility
    local destinations=$(tmutil destinationinfo | grep "URL" | wc -l)
    if [[ $destinations -eq 0 ]]; then
        health_score=$((health_score - 25))
        issues+=("No backup destinations configured")
    else
        # Check if destinations are accessible
        tmutil destinationinfo | grep "URL" | while read -r line; do
            local dest_path=$(echo "$line" | sed 's/.*URL : //')
            if [[ ! -d "$dest_path" ]]; then
                health_score=$((health_score - 15))
                issues+=("Backup destination inaccessible: $dest_path")
            fi
        done
    fi
    
    # Check last backup time
    local last_backup=$(tmutil latestbackup 2>/dev/null)
    if [[ -n "$last_backup" ]]; then
        local last_backup_timestamp=$(stat -f %m "$last_backup" 2>/dev/null)
        local current_timestamp=$(date +%s)
        local hours_since_backup=$(( (current_timestamp - last_backup_timestamp) / 3600 ))
        
        if [[ $hours_since_backup -gt 48 ]]; then
            health_score=$((health_score - 20))
            issues+=("Last backup was $hours_since_backup hours ago")
        elif [[ $hours_since_backup -gt 24 ]]; then
            health_score=$((health_score - 10))
            warnings+=("Last backup was $hours_since_backup hours ago")
        fi
    else
        health_score=$((health_score - 25))
        issues+=("No previous backups found")
    fi
    
    # Check available disk space on backup destination
    local backup_dest=$(tmutil destinationinfo | grep "URL" | head -1 | sed 's/.*URL : //')
    if [[ -n "$backup_dest" ]] && [[ -d "$backup_dest" ]]; then
        local available_space=$(df -BG "$backup_dest" | tail -1 | awk '{print $4}' | sed 's/G//')
        if [[ $available_space -lt 10 ]]; then
            health_score=$((health_score - 15))
            issues+=("Low disk space on backup destination: ${available_space}GB")
        elif [[ $available_space -lt 50 ]]; then
            warnings+=("Backup destination space getting low: ${available_space}GB")
        fi
    fi
    
    # Generate health report
    echo "📊 Backup Health Score: $health_score/100"
    
    if [[ ${#issues[@]} -gt 0 ]]; then
        echo "🔴 Critical Issues:"
        printf '   - %s\n' "${issues[@]}"
    fi
    
    if [[ ${#warnings[@]} -gt 0 ]]; then
        echo "⚠️ Warnings:"
        printf '   - %s\n' "${warnings[@]}"
    fi
    
    if [[ $health_score -ge 90 ]]; then
        echo "✅ Backup system is healthy"
    elif [[ $health_score -ge 70 ]]; then
        echo "⚠️ Backup system has minor issues"
    else
        echo "🔴 Backup system requires immediate attention"
    fi
    
    return $health_score
}

Enterprise Backup Policies

Production Environment Policy

#!/bin/bash

# High-frequency production backup policy
apply_production_backup_policy() {
    echo "🏭 Applying production backup policy..."
    
    # Enable Time Machine
    sudo tmutil enable
    
    # Set aggressive backup schedule (every 30 minutes)
    configure_backup_intervals 1800 900 600 60
    
    # Apply minimal exclusions (keep most data)
    local minimal_exclusions=(
        "/System/Library/Caches"
        "/private/var/vm"
        "/cores"
    )
    
    for exclusion in "${minimal_exclusions[@]}"; do
        sudo tmutil addexclusion "$exclusion" 2>/dev/null
    done
    
    # Enable backup verification
    enable_backup_verification
    
    echo "✅ Production backup policy applied"
    log_policy_application "production"
}

Development Environment Policy

#!/bin/bash

# Development-optimized backup policy
apply_development_backup_policy() {
    echo "💻 Applying development backup policy..."
    
    # Enable Time Machine
    sudo tmutil enable
    
    # Set moderate backup schedule (every 2 hours)
    configure_backup_intervals 7200 3600 1800 300
    
    # Exclude development artifacts
    local dev_exclusions=(
        "/System/Library/Caches"
        "/Library/Caches"
        "~/Library/Caches"
        "/private/var/vm"
        "/cores"
        "~/Library/Developer/Xcode/DerivedData"
        "~/Library/Developer/CoreSimulator"
        "*/node_modules"
        "*/.git/objects"
        "*/target"
        "*/build"
        "*/.gradle"
        "*/.npm"
    )
    
    for exclusion in "${dev_exclusions[@]}"; do
        sudo tmutil addexclusion "$exclusion" 2>/dev/null
    done
    
    echo "✅ Development backup policy applied"
    log_policy_application "development"
}

Executive/Minimal Policy

#!/bin/bash

# Lightweight backup policy for executives
apply_executive_backup_policy() {
    echo "🏢 Applying executive backup policy..."
    
    # Enable Time Machine
    sudo tmutil enable
    
    # Set standard backup schedule (every 4 hours)
    configure_backup_intervals 14400 7200 3600 600
    
    # Exclude non-essential files
    local executive_exclusions=(
        "/System/Library/Caches"
        "/Library/Caches"
        "~/Library/Caches"
        "/private/var/vm"
        "/cores"
        "~/Downloads"
        "~/Movies"
        "/Applications/Games"
        "~/Library/Application Support/Steam"
    )
    
    for exclusion in "${executive_exclusions[@]}"; do
        sudo tmutil addexclusion "$exclusion" 2>/dev/null
    done
    
    echo "✅ Executive backup policy applied"
    log_policy_application "executive"
}

Enterprise Backup Management System

#!/bin/bash

# MacFleet Enterprise Time Machine Management System
# Comprehensive backup management with fleet deployment and compliance

# Configuration
SCRIPT_NAME="MacFleet Backup Manager"
VERSION="4.0.0"
LOG_FILE="/var/log/macfleet_backup.log"
CONFIG_DIR="/etc/macfleet/backup"
POLICY_DIR="/etc/macfleet/backup/policies"
AUDIT_DIR="/etc/macfleet/backup/audit"
RECOVERY_DIR="/etc/macfleet/backup/recovery"

# Create necessary directories
mkdir -p "$CONFIG_DIR" "$POLICY_DIR" "$AUDIT_DIR" "$RECOVERY_DIR"

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

# Policy application logging
log_policy_application() {
    local policy_type="$1"
    local user=$(whoami)
    local hostname=$(hostname)
    
    local audit_entry="{
        \"timestamp\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\",
        \"hostname\": \"$hostname\",
        \"user\": \"$user\",
        \"policy_type\": \"$policy_type\",
        \"action\": \"policy_applied\",
        \"script_version\": \"$VERSION\"
    }"
    
    echo "$audit_entry" >> "$AUDIT_DIR/policy_audit.json"
    log_action "Backup policy applied: $policy_type"
}

# Configure backup intervals (requires SIP disabled - safer alternative provided)
configure_backup_intervals() {
    local interval="$1"        # Time between backups (seconds)
    local delay="$2"          # Delay after wake (seconds)
    local grace_period="$3"   # Grace period after restart (seconds)
    local start_interval="$4" # Delay after power connect (seconds)
    
    echo "⚙️ Configuring backup intervals..."
    echo "Interval: $interval seconds, Delay: $delay seconds"
    echo "Grace Period: $grace_period seconds, Start Interval: $start_interval seconds"
    
    # Create a configuration record for enterprise tracking
    local config_record="{
        \"timestamp\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\",
        \"interval\": $interval,
        \"delay\": $delay,
        \"grace_period\": $grace_period,
        \"start_interval\": $start_interval
    }"
    
    echo "$config_record" > "$CONFIG_DIR/backup_intervals.json"
    
    # Note: Actual modification requires SIP disabled
    echo "⚠️ Interval configuration saved. Apply manually if SIP modifications are required."
    log_action "Backup intervals configured: interval=$interval, delay=$delay"
}

# Backup verification system
enable_backup_verification() {
    echo "🔍 Enabling backup verification..."
    
    # Create verification script
    cat > "$CONFIG_DIR/verify_backup.sh" << 'EOF'
#!/bin/bash
# Backup verification script

verify_latest_backup() {
    local latest_backup=$(tmutil latestbackup)
    
    if [[ -z "$latest_backup" ]]; then
        echo "❌ No backup found to verify"
        return 1
    fi
    
    echo "🔍 Verifying backup: $latest_backup"
    
    # Check backup completeness
    if tmutil compare / "$latest_backup" >/dev/null 2>&1; then
        echo "✅ Backup verification successful"
        return 0
    else
        echo "❌ Backup verification failed"
        return 1
    fi
}

verify_latest_backup
EOF
    
    chmod +x "$CONFIG_DIR/verify_backup.sh"
    echo "✅ Backup verification enabled"
}

# Disaster recovery preparation
prepare_disaster_recovery() {
    echo "🆘 Preparing disaster recovery system..."
    
    # Create recovery information
    local recovery_info="{
        \"timestamp\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\",
        \"hostname\": \"$(hostname)\",
        \"system_version\": \"$(sw_vers -productVersion)\",
        \"backup_destinations\": $(tmutil destinationinfo | grep "URL" | sed 's/.*URL : //' | jq -R . | jq -s .),
        \"latest_backup\": \"$(tmutil latestbackup)\",
        \"user_accounts\": $(dscl . list /Users | grep -v '^_' | jq -R . | jq -s .)
    }"
    
    echo "$recovery_info" > "$RECOVERY_DIR/system_recovery_info.json"
    
    # Create recovery documentation
    cat > "$RECOVERY_DIR/recovery_guide.md" << EOF
# MacFleet Disaster Recovery Guide

## System Information
- Hostname: $(hostname)
- macOS Version: $(sw_vers -productVersion)
- Last Backup: $(tmutil latestbackup)

## Recovery Steps
1. Boot from macOS Recovery (Cmd+R during startup)
2. Open Disk Utility and restore from Time Machine
3. Select latest backup from: $(tmutil latestbackup)
4. Follow Migration Assistant prompts
5. Verify system functionality
6. Run backup health check

## Critical Files Location
- User data: /Users/
- Applications: /Applications/
- System preferences: /Library/Preferences/

## Emergency Contacts
- IT Support: [Configure in enterprise setup]
- MacFleet Admin: [Configure in enterprise setup]
EOF
    
    echo "✅ Disaster recovery preparation completed"
    log_action "Disaster recovery system prepared"
}

# Fleet backup status monitoring
monitor_fleet_backup_status() {
    local fleet_hosts_file="$CONFIG_DIR/fleet_hosts.txt"
    
    if [[ ! -f "$fleet_hosts_file" ]]; then
        echo "❌ Fleet hosts file not found: $fleet_hosts_file"
        return 1
    fi
    
    echo "📊 Monitoring fleet backup status..."
    
    local total_hosts=0
    local healthy_backups=0
    local failed_backups=0
    
    while IFS= read -r host; do
        [[ "$host" =~ ^#.*$ ]] && continue
        [[ -z "$host" ]] && continue
        
        ((total_hosts++))
        echo "Checking: $host"
        
        # Check backup status via SSH
        if ssh "$host" "tmutil status | grep -q 'Running = 1'" 2>/dev/null; then
            echo "✅ $host: Backup running"
            ((healthy_backups++))
        elif ssh "$host" "tmutil latestbackup" >/dev/null 2>&1; then
            echo "⚠️ $host: Backup exists but not running"
            ((healthy_backups++))
        else
            echo "❌ $host: No backup or unreachable"
            ((failed_backups++))
        fi
        
    done < "$fleet_hosts_file"
    
    # Generate fleet status report
    local fleet_report="{
        \"timestamp\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\",
        \"total_hosts\": $total_hosts,
        \"healthy_backups\": $healthy_backups,
        \"failed_backups\": $failed_backups,
        \"success_rate\": $(echo "scale=2; $healthy_backups * 100 / $total_hosts" | bc -l)
    }"
    
    echo "$fleet_report" > "$AUDIT_DIR/fleet_status_$(date +%Y%m%d_%H%M%S).json"
    
    echo "📈 Fleet Status: $healthy_backups/$total_hosts devices with healthy backups"
    log_action "Fleet backup monitoring completed: $healthy_backups/$total_hosts healthy"
}

# Backup compliance reporting
generate_compliance_report() {
    local report_file="$AUDIT_DIR/backup_compliance_$(date +%Y%m%d_%H%M%S).json"
    
    echo "📋 Generating backup compliance report..."
    
    # Gather backup information
    local latest_backup=$(tmutil latestbackup)
    local backup_count=$(tmutil listbackups | wc -l)
    local tm_enabled=$(tmutil status | grep -c "Running")
    local destinations=$(tmutil destinationinfo | grep -c "URL")
    
    # Calculate compliance score
    local compliance_score=0
    [[ $tm_enabled -gt 0 ]] && compliance_score=$((compliance_score + 25))
    [[ $destinations -gt 0 ]] && compliance_score=$((compliance_score + 25))
    [[ -n "$latest_backup" ]] && compliance_score=$((compliance_score + 25))
    [[ $backup_count -gt 0 ]] && compliance_score=$((compliance_score + 25))
    
    # Generate comprehensive report
    local report="{
        \"report_metadata\": {
            \"generated_at\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\",
            \"hostname\": \"$(hostname)\",
            \"script_version\": \"$VERSION\",
            \"compliance_frameworks\": [\"GDPR\", \"HIPAA\", \"SOX\", \"ISO 27001\"]
        },
        \"backup_status\": {
            \"time_machine_enabled\": $([ $tm_enabled -gt 0 ] && echo "true" || echo "false"),
            \"destinations_configured\": $destinations,
            \"latest_backup\": \"$latest_backup\",
            \"total_backups\": $backup_count,
            \"backup_health_score\": $(assess_backup_health >/dev/null 2>&1; echo $?)
        },
        \"compliance_assessment\": {
            \"overall_score\": $compliance_score,
            \"data_protection_compliance\": $([ $compliance_score -ge 75 ] && echo "\"compliant\"" || echo "\"non_compliant\""),
            \"last_backup_within_24h\": $(check_backup_freshness),
            \"encryption_enabled\": $(check_backup_encryption)
        }
    }"
    
    echo "$report" > "$report_file"
    echo "📊 Compliance report saved: $report_file"
    log_action "Compliance report generated: compliance_score=$compliance_score"
}

# Check backup freshness
check_backup_freshness() {
    local latest_backup=$(tmutil latestbackup)
    
    if [[ -n "$latest_backup" ]]; then
        local last_backup_timestamp=$(stat -f %m "$latest_backup" 2>/dev/null)
        local current_timestamp=$(date +%s)
        local hours_since_backup=$(( (current_timestamp - last_backup_timestamp) / 3600 ))
        
        if [[ $hours_since_backup -le 24 ]]; then
            echo "true"
        else
            echo "false"
        fi
    else
        echo "false"
    fi
}

# Check backup encryption
check_backup_encryption() {
    # Check if FileVault is enabled (indicates system encryption)
    if fdesetup status | grep -q "FileVault is On"; then
        echo "true"
    else
        echo "false"
    fi
}

# Emergency backup initiation
emergency_backup() {
    echo "🚨 EMERGENCY BACKUP INITIATED"
    
    # Ensure Time Machine is enabled
    sudo tmutil enable
    
    # Start immediate backup
    sudo tmutil startbackup --block
    
    local backup_status=$?
    
    if [[ $backup_status -eq 0 ]]; then
        echo "✅ Emergency backup completed successfully"
        log_action "Emergency backup completed successfully"
    else
        echo "❌ Emergency backup failed"
        log_action "Emergency backup failed with status: $backup_status"
    fi
    
    # Generate emergency backup report
    emergency_backup_report
}

# Emergency backup reporting
emergency_backup_report() {
    local report_file="$AUDIT_DIR/emergency_backup_$(date +%Y%m%d_%H%M%S).json"
    
    local report="{
        \"timestamp\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\",
        \"hostname\": \"$(hostname)\",
        \"emergency_backup_status\": \"completed\",
        \"latest_backup\": \"$(tmutil latestbackup)\",
        \"backup_size\": \"$(du -sh "$(tmutil latestbackup)" 2>/dev/null | cut -f1)\",
        \"system_health\": $(assess_backup_health >/dev/null 2>&1; echo $?)
    }"
    
    echo "$report" > "$report_file"
    echo "📋 Emergency backup report saved: $report_file"
}

# Fleet deployment function
deploy_backup_policy() {
    local policy_type="$1"
    local fleet_hosts_file="$CONFIG_DIR/fleet_hosts.txt"
    
    if [[ ! -f "$fleet_hosts_file" ]]; then
        echo "❌ Fleet hosts file not found: $fleet_hosts_file"
        return 1
    fi
    
    echo "🚀 Deploying backup policy '$policy_type' to fleet..."
    
    local success_count=0
    local total_count=0
    
    while IFS= read -r host; do
        [[ "$host" =~ ^#.*$ ]] && continue
        [[ -z "$host" ]] && continue
        
        ((total_count++))
        echo "Deploying to: $host"
        
        # Deploy script and execute policy
        if scp "$0" "$host:/tmp/macfleet_backup.sh" >/dev/null 2>&1 && \
           ssh "$host" "chmod +x /tmp/macfleet_backup.sh && sudo /tmp/macfleet_backup.sh --policy '$policy_type'" >/dev/null 2>&1; then
            echo "✅ Successfully deployed to $host"
            ((success_count++))
        else
            echo "❌ Failed to deploy to $host"
        fi
        
    done < "$fleet_hosts_file"
    
    echo "📊 Fleet deployment completed: $success_count/$total_count successful"
    log_action "Fleet deployment: $success_count/$total_count hosts successful"
}

# Display current backup status
show_backup_status() {
    echo "=== MacFleet Time Machine Status ==="
    
    # Time Machine status
    local tm_status=$(tmutil status)
    echo "🔄 Time Machine Status:"
    echo "$tm_status"
    echo ""
    
    # Latest backup
    local latest_backup=$(tmutil latestbackup)
    if [[ -n "$latest_backup" ]]; then
        echo "📅 Latest Backup: $latest_backup"
        echo "📊 Backup Size: $(du -sh "$latest_backup" 2>/dev/null | cut -f1)"
    else
        echo "❌ No backups found"
    fi
    echo ""
    
    # Backup destinations
    echo "💾 Backup Destinations:"
    tmutil destinationinfo
    echo ""
    
    # Health assessment
    assess_backup_health
}

# Display usage information
show_usage() {
    cat << EOF
$SCRIPT_NAME v$VERSION

Usage: $0 [OPTION]

BACKUP MANAGEMENT:
    --policy TYPE               Apply backup policy (production|development|executive)
    --emergency                 Start emergency backup
    --status                    Show current backup status
    --health                    Perform backup health assessment

FLEET MANAGEMENT:
    --deploy-fleet POLICY       Deploy backup policy to entire fleet
    --monitor-fleet             Monitor fleet backup status
    --generate-report           Generate compliance report

CONFIGURATION:
    --set-destination PATH      Set backup destination with validation
    --exclude PATH              Add path to backup exclusions
    --include PATH              Remove path from backup exclusions
    --prepare-recovery          Prepare disaster recovery information

EXAMPLES:
    $0 --policy production
    $0 --emergency
    $0 --deploy-fleet development
    $0 --set-destination /Volumes/Backup
    $0 --health

Configuration files:
    $CONFIG_DIR/fleet_hosts.txt     - Fleet deployment hosts
    $POLICY_DIR/                    - Backup policy definitions
    
Log files:
    $LOG_FILE                       - Main log file
    $AUDIT_DIR/                     - Audit and compliance logs
EOF
}

# Main function
main() {
    case "$1" in
        --policy)
            [[ -z "$2" ]] && { echo "❌ Policy type required"; exit 1; }
            case "$2" in
                "production")
                    apply_production_backup_policy
                    ;;
                "development")
                    apply_development_backup_policy
                    ;;
                "executive")
                    apply_executive_backup_policy
                    ;;
                *)
                    echo "❌ Invalid policy type: $2"
                    echo "Available policies: production, development, executive"
                    exit 1
                    ;;
            esac
            ;;
        --emergency)
            emergency_backup
            ;;
        --status)
            show_backup_status
            ;;
        --health)
            assess_backup_health
            ;;
        --deploy-fleet)
            [[ -z "$2" ]] && { echo "❌ Policy type required for fleet deployment"; exit 1; }
            deploy_backup_policy "$2"
            ;;
        --monitor-fleet)
            monitor_fleet_backup_status
            ;;
        --generate-report)
            generate_compliance_report
            ;;
        --set-destination)
            [[ -z "$2" ]] && { echo "❌ Destination path required"; exit 1; }
            setup_backup_destination "$2"
            ;;
        --exclude)
            [[ -z "$2" ]] && { echo "❌ Path required for exclusion"; exit 1; }
            manage_backup_exclusions "add" "$2"
            ;;
        --include)
            [[ -z "$2" ]] && { echo "❌ Path required for inclusion"; exit 1; }
            manage_backup_exclusions "remove" "$2"
            ;;
        --prepare-recovery)
            prepare_disaster_recovery
            ;;
        --help|"")
            show_usage
            ;;
        *)
            echo "❌ Invalid option: $1"
            show_usage
            exit 1
            ;;
    esac
}

# Execute main function
main "$@"

Usage Examples

Apply Enterprise Backup Policies

# Production environment with aggressive backup schedule
sudo ./macfleet_backup.sh --policy production

# Development environment with optimized exclusions
sudo ./macfleet_backup.sh --policy development

# Executive environment with minimal backup footprint
sudo ./macfleet_backup.sh --policy executive

Fleet Management

# Deploy production backup policy across entire fleet
sudo ./macfleet_backup.sh --deploy-fleet production

# Monitor backup status across all devices
sudo ./macfleet_backup.sh --monitor-fleet

# Generate enterprise compliance report
sudo ./macfleet_backup.sh --generate-report

Emergency Operations

# Initiate emergency backup
sudo ./macfleet_backup.sh --emergency

# Check backup system health
sudo ./macfleet_backup.sh --health

# Prepare disaster recovery information
sudo ./macfleet_backup.sh --prepare-recovery

Configuration Management

# Set backup destination with validation
sudo ./macfleet_backup.sh --set-destination /Volumes/Enterprise_Backup

# Add exclusions for large files
sudo ./macfleet_backup.sh --exclude ~/Downloads
sudo ./macfleet_backup.sh --exclude ~/Movies

# Check current status
sudo ./macfleet_backup.sh --status

Compliance and Regulatory Framework

GDPR Compliance

  • 📋 Data Protection: Automated backup of personal data with encryption
  • 🔐 Right to Erasure: Managed exclusions for data removal requests
  • 📊 Data Processing Records: Comprehensive audit trails
  • 🛡️ Security Measures: Encrypted backup destinations and access controls

HIPAA Technical Safeguards

  • 🏥 Data Backup: Regular automated backups of health information
  • 🔐 Encryption: FileVault integration for data protection
  • 📝 Audit Controls: Complete logging of backup activities
  • 🚨 Emergency Access: Emergency backup capabilities for business continuity

SOX Compliance

  • 📋 Financial Data Protection: Automated backup of financial records
  • 🔍 Audit Trails: Comprehensive logging of all backup operations
  • 📊 Retention Policies: Configurable backup retention periods
  • 🛡️ Access Controls: Secure backup destination management

ISO 27001 Controls

  • A.12.3.1: Information backup procedures and testing
  • A.17.1.2: Business continuity planning implementation
  • A.18.1.3: Records management and retention

Advanced Features

Backup Encryption and Security

# Check backup encryption status
check_backup_encryption() {
    if fdesetup status | grep -q "FileVault is On"; then
        echo "✅ System encryption enabled (FileVault)"
        return 0
    else
        echo "⚠️ System encryption not enabled"
        return 1
    fi
}

Storage Optimization

# Optimize backup storage usage
optimize_backup_storage() {
    echo "🗂️ Optimizing backup storage..."
    
    # Remove old snapshots beyond retention policy
    local retention_days=30
    tmutil listbackups | head -n -$retention_days | while read -r old_backup; do
        if [[ -n "$old_backup" ]]; then
            sudo tmutil delete "$old_backup"
            echo "Removed old backup: $old_backup"
        fi
    done
    
    echo "✅ Storage optimization completed"
}

Business Continuity Testing

# Test backup integrity and recovery procedures
test_backup_integrity() {
    echo "🧪 Testing backup integrity..."
    
    local latest_backup=$(tmutil latestbackup)
    
    if [[ -n "$latest_backup" ]]; then
        # Verify backup can be read
        if ls "$latest_backup" >/dev/null 2>&1; then
            echo "✅ Backup is accessible"
            
            # Test random file restoration (non-destructive)
            local test_file=$(find "$latest_backup" -name "*.txt" | head -1)
            if [[ -n "$test_file" ]]; then
                echo "✅ Test file found in backup: $test_file"
            fi
        else
            echo "❌ Backup is not accessible"
            return 1
        fi
    else
        echo "❌ No backup available for testing"
        return 1
    fi
}

Important Security Notes

  • 🔐 Administrative privileges required for Time Machine management
  • 📝 All backup operations are logged for audit and compliance
  • 💾 Backup destinations should be on encrypted volumes
  • 🔄 Regular testing of backup integrity and recovery procedures recommended
  • ⚠️ SIP modifications require careful consideration of security implications
  • 🚨 Emergency procedures should be tested periodically

Troubleshooting

Common Issues

# Check Time Machine daemon status
sudo launchctl list | grep backupd

# Reset Time Machine if stuck
sudo tmutil disable
sudo tmutil enable

# Clear Time Machine cache
sudo rm -rf /Library/Preferences/com.apple.TimeMachine.plist

# Check backup destination permissions
ls -la /Volumes/BackupDrive

Recovery Procedures

# Boot into Recovery Mode: Cmd+R during startup
# Use Migration Assistant or Time Machine restore
# Follow guided recovery process

# Manual file restoration
sudo tmutil restore /path/to/source /path/to/destination

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.