Tutorial

Nuevas actualizaciones y mejoras para Macfleet.

Aviso importante

Los ejemplos de código y scripts proporcionados en estos tutoriales son solo para propósitos educativos. Macfleet no es responsable de ningún problema, daño o vulnerabilidad de seguridad que pueda surgir del uso, modificación o implementación de estos ejemplos. Siempre revisa y prueba el código en un entorno seguro antes de usarlo en sistemas de producción.

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

Nuevas actualizaciones y mejoras para Macfleet.

Configurando un Runner de GitHub Actions en un Mac Mini (Apple Silicon)

Runner de GitHub Actions

GitHub Actions es una plataforma poderosa de CI/CD que te permite automatizar tus flujos de trabajo de desarrollo de software. Aunque GitHub ofrece runners hospedados, los runners auto-hospedados proporcionan mayor control y personalización para tu configuración de CI/CD. Este tutorial te guía a través de la configuración y conexión de un runner auto-hospedado en un Mac mini para ejecutar pipelines de macOS.

Prerrequisitos

Antes de comenzar, asegúrate de tener:

  • Un Mac mini (regístrate en Macfleet)
  • Un repositorio de GitHub con derechos de administrador
  • Un gestor de paquetes instalado (preferiblemente Homebrew)
  • Git instalado en tu sistema

Paso 1: Crear una Cuenta de Usuario Dedicada

Primero, crea una cuenta de usuario dedicada para el runner de GitHub Actions:

# Crear la cuenta de usuario '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

# Establecer la contraseña para el usuario
sudo dscl . -passwd /Users/gh-runner tu_contraseña

# Agregar 'gh-runner' al grupo 'admin'
sudo dscl . -append /Groups/admin GroupMembership gh-runner

Cambia a la nueva cuenta de usuario:

su gh-runner

Paso 2: Instalar Software Requerido

Instala Git y Rosetta 2 (si usas Apple Silicon):

# Instalar Git si no está ya instalado
brew install git

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

Paso 3: Configurar el Runner de GitHub Actions

  1. Ve a tu repositorio de GitHub
  2. Navega a Configuración > Actions > Runners

Runner de GitHub Actions

  1. Haz clic en "New self-hosted runner" (https://github.com/<username>/<repository>/settings/actions/runners/new)
  2. Selecciona macOS como imagen del runner y ARM64 como arquitectura
  3. Sigue los comandos proporcionados para descargar y configurar el runner

Runner de GitHub Actions

Crea un archivo .env en el directorio _work del runner:

# archivo _work/.env
ImageOS=macos15
XCODE_15_DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer
  1. Ejecuta el script run.sh en tu directorio del runner para completar la configuración.
  2. Verifica que el runner esté activo y escuchando trabajos en la terminal y revisa la configuración del repositorio de GitHub para la asociación del runner y el estado Idle.

Runner de GitHub Actions

Paso 4: Configurar Sudoers (Opcional)

Si tus acciones requieren privilegios de root, configura el archivo sudoers:

sudo visudo

Agrega la siguiente línea:

gh-runner ALL=(ALL) NOPASSWD: ALL

Paso 5: Usar el Runner en Flujos de Trabajo

Configura tu flujo de trabajo de GitHub Actions para usar el runner auto-hospedado:

name: Flujo de trabajo de muestra

on:
  workflow_dispatch:

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

El runner está autenticado en tu repositorio y etiquetado con self-hosted, macOS, y ARM64. Úsalo en tus flujos de trabajo especificando estas etiquetas en el campo runs-on:

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

Mejores Prácticas

  • Mantén tu software del runner actualizado
  • Monitorea regularmente los logs del runner para problemas
  • Usa etiquetas específicas para diferentes tipos de runners
  • Implementa medidas de seguridad apropiadas
  • Considera usar múltiples runners para balanceo de carga

Solución de Problemas

Problemas comunes y soluciones:

  1. Runner no conectando:

    • Verifica conectividad de red
    • Verifica validez del token de GitHub
    • Asegúrate de permisos apropiados
  2. Fallas de construcción:

    • Verifica instalación de Xcode
    • Verifica dependencias requeridas
    • Revisa logs del flujo de trabajo
  3. Problemas de permisos:

    • Verifica permisos de usuario
    • Verifica configuración de sudoers
    • Revisa permisos del sistema de archivos

Conclusión

Ahora tienes un runner auto-hospedado de GitHub Actions configurado en tu Mac mini. Esta configuración te proporciona más control sobre tu entorno de CI/CD y te permite ejecutar flujos de trabajo específicos de macOS de manera eficiente.

Recuerda mantener regularmente tu runner y mantenerlo actualizado con los últimos parches de seguridad y versiones de software.

Aplicación Nativa

Aplicación nativa de Macfleet

Guía de Instalación de Macfleet

Macfleet es una solución poderosa de gestión de flota diseñada específicamente para entornos de Mac Mini alojados en la nube. Como proveedor de hosting en la nube de Mac Mini, puedes usar Macfleet para monitorear, gestionar y optimizar toda tu flota de instancias Mac virtualizadas.

Esta guía de instalación te llevará a través de la configuración del monitoreo de Macfleet en sistemas macOS, Windows y Linux para asegurar una supervisión integral de tu infraestructura en la nube.

🍎 macOS

  • Descarga el archivo .dmg para Mac aquí
  • Haz doble clic en el archivo .dmg descargado
  • Arrastra la aplicación Macfleet a la carpeta Aplicaciones
  • Expulsa el archivo .dmg
  • Abre Preferencias del Sistema > Seguridad y Privacidad
    • Pestaña Privacidad > Accesibilidad
    • Marca Macfleet para permitir el monitoreo
  • Inicia Macfleet desde Aplicaciones
  • El seguimiento comienza automáticamente

🪟 Windows

  • Descarga el archivo .exe para Windows aquí
  • Haz clic derecho en el archivo .exe > "Ejecutar como administrador"
  • Sigue el asistente de instalación
  • Acepta los términos y condiciones
  • Permite en Windows Defender si se solicita
  • Concede permisos de monitoreo de aplicaciones
  • Inicia Macfleet desde el Menú Inicio
  • La aplicación comienza el seguimiento automáticamente

🐧 Linux

  • Descarga el paquete .deb (Ubuntu/Debian) o .rpm (CentOS/RHEL) aquí
  • Instala usando tu gestor de paquetes
    • Ubuntu/Debian: sudo dpkg -i Macfleet-linux.deb
    • CentOS/RHEL: sudo rpm -ivh Macfleet-linux.rpm
  • Permite permisos de acceso X11 si se solicita
  • Agrega el usuario a los grupos apropiados si es necesario
  • Inicia Macfleet desde el menú de Aplicaciones
  • La aplicación comienza el seguimiento automáticamente

Nota: Después de la instalación en todos los sistemas, inicia sesión con tus credenciales de Macfleet para sincronizar datos con tu panel de control.