Tutorial

New updates and improvements to Roundfleet.

Disk Utility Management on macOS

Manage storage and disk operations across your Roundfleet devices using advanced diskutil commands and enterprise storage management tools. This tutorial covers disk management, storage security, compliance monitoring, and enterprise storage lifecycle management.

Understanding macOS Disk Management

macOS provides several command-line tools for disk and storage management:

  • diskutil - Primary disk utility for volume and partition management
  • df - Display filesystem disk space usage
  • du - Display directory space usage
  • fsck - Filesystem check and repair utility
  • APFS - Apple File System with advanced features

Basic Disk Operations

List All Disks

#!/bin/bash

# Basic disk listing
diskutil list

echo "Disk inventory completed successfully"

Enhanced Disk Information

#!/bin/bash

# Enhanced disk information with detailed analysis
get_comprehensive_disk_info() {
    echo "=== Comprehensive Disk Analysis ==="
    
    # Basic disk list
    echo "Disk Inventory:"
    diskutil list
    
    echo -e "\nDisk Usage Summary:"
    df -h
    
    echo -e "\nAPFS Container Information:"
    diskutil apfs list
    
    echo -e "\nPhysical Disk Information:"
    system_profiler SPStorageDataType
    
    echo -e "\nSMART Status:"
    for disk in $(diskutil list | grep "^/dev/disk[0-9]" | awk '{print $1}'); do
        echo "SMART status for $disk:"
        smartctl -H "$disk" 2>/dev/null || echo "  SMART data not available"
    done
}

# Execute comprehensive analysis
get_comprehensive_disk_info

Storage Management Categories

Storage Type Classifications

#!/bin/bash

# Enterprise storage categories for management and policy enforcement
declare -A STORAGE_CATEGORIES=(
    ["system_critical"]="System volumes, boot partitions, recovery partitions"
    ["user_data"]="User home directories, personal documents, application data"
    ["application_storage"]="Application binaries, frameworks, system libraries"
    ["development_workspace"]="Development environments, source code, build artifacts"
    ["media_content"]="Videos, images, audio files, creative assets"
    ["backup_archives"]="Time Machine, system backups, archive storage"
    ["temporary_cache"]="Cache files, temporary data, system logs"
    ["security_volumes"]="Encrypted volumes, secure containers, key storage"
    ["network_storage"]="Mounted network drives, cloud storage, remote volumes"
    ["external_devices"]="USB drives, external HDDs, removable storage"
)

# Storage risk levels
declare -A RISK_LEVELS=(
    ["system_critical"]="critical"
    ["user_data"]="high"
    ["application_storage"]="medium"
    ["development_workspace"]="medium"
    ["media_content"]="low"
    ["backup_archives"]="high"
    ["temporary_cache"]="low"
    ["security_volumes"]="critical"
    ["network_storage"]="medium"
    ["external_devices"]="high"
)

# Management priorities
declare -A MANAGEMENT_PRIORITIES=(
    ["system_critical"]="highest_protection"
    ["user_data"]="high_protection"
    ["application_storage"]="standard_protection"
    ["development_workspace"]="standard_protection"
    ["media_content"]="basic_protection"
    ["backup_archives"]="highest_protection"
    ["temporary_cache"]="cleanup_priority"
    ["security_volumes"]="highest_protection"
    ["network_storage"]="monitoring_priority"
    ["external_devices"]="security_screening"
)

print_storage_categories() {
    echo "=== Storage Management Categories ==="
    for category in "${!STORAGE_CATEGORIES[@]}"; do
        echo "Category: $category"
        echo "  Description: ${STORAGE_CATEGORIES[$category]}"
        echo "  Risk Level: ${RISK_LEVELS[$category]}"
        echo "  Management Priority: ${MANAGEMENT_PRIORITIES[$category]}"
        echo ""
    done
}

# Display available categories
print_storage_categories

Disk Management Policies

Storage Policy Engine

#!/bin/bash

# Storage management policies for different organizational requirements
declare -A STORAGE_POLICIES=(
    ["enterprise_standard"]="Standard enterprise storage with backup and monitoring"
    ["high_security_financial"]="High-security storage for financial and sensitive data"
    ["creative_workflow"]="Optimized for creative teams with large media files"
    ["development_environment"]="Development-focused with version control and build optimization"
    ["compliance_strict"]="Strict compliance with data retention and audit requirements"
    ["performance_optimized"]="Performance-focused with SSD optimization and caching"
    ["cost_efficient"]="Cost-efficient storage with intelligent tiering and cleanup"
)

# Policy configurations
get_storage_policy() {
    local policy_type="$1"
    
    case "$policy_type" in
        "enterprise_standard")
            cat << EOF
{
    "encryption_required": true,
    "backup_frequency": "daily",
    "retention_period": "90_days",
    "compression_enabled": true,
    "deduplication": true,
    "monitoring_level": "standard",
    "security_scanning": true,
    "automatic_cleanup": false,
    "performance_optimization": "balanced",
    "compliance_frameworks": ["iso27001"],
    "disk_health_monitoring": true,
    "storage_quotas": {
        "user_data": "100GB",
        "application_storage": "50GB",
        "temporary_cache": "10GB"
    }
}
EOF
            ;;
        "high_security_financial")
            cat << EOF
{
    "encryption_required": true,
    "encryption_level": "aes256",
    "backup_frequency": "continuous",
    "retention_period": "2555_days",
    "compression_enabled": false,
    "deduplication": false,
    "monitoring_level": "comprehensive",
    "security_scanning": true,
    "automatic_cleanup": false,
    "performance_optimization": "security_first",
    "compliance_frameworks": ["sox", "pci_dss", "nist"],
    "disk_health_monitoring": true,
    "immutable_backups": true,
    "access_logging": "detailed",
    "integrity_verification": "continuous",
    "storage_quotas": {
        "user_data": "50GB",
        "application_storage": "25GB",
        "temporary_cache": "5GB",
        "audit_logs": "unlimited"
    }
}
EOF
            ;;
        "creative_workflow")
            cat << EOF
{
    "encryption_required": false,
    "backup_frequency": "project_based",
    "retention_period": "365_days",
    "compression_enabled": false,
    "deduplication": false,
    "monitoring_level": "performance",
    "security_scanning": false,
    "automatic_cleanup": true,
    "performance_optimization": "speed_first",
    "compliance_frameworks": ["client_confidentiality"],
    "disk_health_monitoring": true,
    "large_file_optimization": true,
    "cache_acceleration": true,
    "storage_quotas": {
        "user_data": "500GB",
        "media_content": "2TB",
        "project_archives": "1TB",
        "temporary_cache": "100GB"
    }
}
EOF
            ;;
        *)
            echo "Unknown storage policy: $policy_type"
            return 1
            ;;
    esac
}

# Apply storage policy
apply_storage_policy() {
    local policy="$1"
    local config_file="/tmp/storage_policy.json"
    
    echo "Applying storage policy: $policy"
    
    get_storage_policy "$policy" > "$config_file"
    
    if [[ ! -f "$config_file" ]]; then
        echo "❌ Failed to generate policy configuration"
        return 1
    fi
    
    echo "✅ Storage policy applied successfully"
    echo "Configuration: $config_file"
    
    # Display key policy settings
    echo "=== Policy Summary ==="
    echo "Encryption Required: $(jq -r '.encryption_required' "$config_file")"
    echo "Backup Frequency: $(jq -r '.backup_frequency' "$config_file")"
    echo "Retention Period: $(jq -r '.retention_period' "$config_file")"
    echo "Monitoring Level: $(jq -r '.monitoring_level' "$config_file")"
    echo "Performance Optimization: $(jq -r '.performance_optimization' "$config_file")"
    
    return 0
}

Advanced Disk Operations

Secure Disk Erasure

#!/bin/bash

# Enhanced secure disk erasure with verification
secure_erase_volume() {
    local identifier="$1"
    local security_level="$2"
    local new_name="$3"
    local filesystem_type="${4:-APFS}"
    
    echo "=== Secure Volume Erasure ==="
    echo "Target: $identifier"
    echo "Security Level: $security_level"
    echo "New Name: $new_name"
    echo "Filesystem: $filesystem_type"
    
    # Verify disk exists
    if ! diskutil info "$identifier" &>/dev/null; then
        echo "❌ Error: Disk identifier '$identifier' not found"
        return 1
    fi
    
    # Get disk information before erasure
    local disk_info
    disk_info=$(diskutil info "$identifier")
    echo "Disk Information:"
    echo "$disk_info"
    
    # Confirmation prompt
    echo ""
    echo "âš ī¸  WARNING: This will permanently erase all data on $identifier"
    echo "Current volume: $(echo "$disk_info" | grep "Volume Name:" | awk -F': ' '{print $2}')"
    echo "Size: $(echo "$disk_info" | grep "Disk Size:" | awk -F': ' '{print $2}')"
    
    read -p "Type 'CONFIRM' to proceed with erasure: " confirmation
    if [[ "$confirmation" != "CONFIRM" ]]; then
        echo "❌ Operation cancelled by user"
        return 1
    fi
    
    # Perform secure erasure based on security level
    case "$security_level" in
        "basic")
            echo "Performing basic erasure..."
            diskutil eraseVolume "$filesystem_type" "$new_name" "$identifier"
            ;;
        "secure")
            echo "Performing secure erasure (DoD 5220.22-M)..."
            diskutil secureErase freespace 3 "$identifier"
            diskutil eraseVolume "$filesystem_type" "$new_name" "$identifier"
            ;;
        "military")
            echo "Performing military-grade erasure (7-pass)..."
            diskutil secureErase freespace 4 "$identifier"
            diskutil eraseVolume "$filesystem_type" "$new_name" "$identifier"
            ;;
        *)
            echo "❌ Unknown security level: $security_level"
            return 1
            ;;
    esac
    
    # Verify erasure completion
    if diskutil info "$identifier" | grep -q "Volume Name.*$new_name"; then
        echo "✅ Secure erasure completed successfully"
        echo "New volume: $new_name"
        echo "Filesystem: $filesystem_type"
        
        # Log the operation
        audit_log "Secure erasure completed: $identifier -> $new_name (Security: $security_level)"
        
        return 0
    else
        echo "❌ Erasure verification failed"
        return 1
    fi
}

# Usage example
# secure_erase_volume "disk2s1" "secure" "CleanVolume" "APFS"

Volume Health Monitoring

#!/bin/bash

# Comprehensive volume health monitoring and assessment
monitor_volume_health() {
    local identifier="$1"
    local health_report="/tmp/volume_health_$(date +%Y%m%d_%H%M%S).json"
    
    echo "=== Volume Health Monitoring ==="
    echo "Target Volume: $identifier"
    
    # Initialize health report
    cat > "$health_report" << EOF
{
    "volume_identifier": "$identifier",
    "scan_timestamp": "$(date -Iseconds)",
    "hostname": "$(hostname)",
    "health_checks": {}
}
EOF
    
    # Volume verification
    echo "Running volume verification..."
    local verify_output
    verify_output=$(diskutil verifyVolume "$identifier" 2>&1)
    local verify_status=$?
    
    # Parse verification results
    local verification_passed=false
    if [[ $verify_status -eq 0 ]] && echo "$verify_output" | grep -q "appears to be OK"; then
        verification_passed=true
    fi
    
    # SMART status check (if supported)
    echo "Checking SMART status..."
    local smart_status="unknown"
    local physical_disk
    physical_disk=$(diskutil info "$identifier" | grep "Part of Whole" | awk '{print $4}')
    
    if [[ -n "$physical_disk" ]]; then
        if smartctl -H "$physical_disk" 2>/dev/null | grep -q "PASSED"; then
            smart_status="passed"
        elif smartctl -H "$physical_disk" 2>/dev/null | grep -q "FAILED"; then
            smart_status="failed"
        fi
    fi
    
    # Disk usage analysis
    echo "Analyzing disk usage..."
    local disk_usage
    disk_usage=$(df -h "$identifier" 2>/dev/null | tail -1)
    local usage_percent
    usage_percent=$(echo "$disk_usage" | awk '{print $5}' | tr -d '%')
    
    # Performance test
    echo "Running performance test..."
    local write_speed read_speed
    local test_file="/Volumes/$(diskutil info "$identifier" | grep "Mount Point" | awk -F': ' '{print $2}' | xargs)/speed_test_$$"
    
    if [[ -w "$(dirname "$test_file")" ]]; then
        # Write test (10MB)
        write_speed=$(dd if=/dev/zero of="$test_file" bs=1m count=10 2>&1 | grep "bytes/sec" | awk '{print $(NF-1)}')
        
        # Read test
        read_speed=$(dd if="$test_file" of=/dev/null bs=1m 2>&1 | grep "bytes/sec" | awk '{print $(NF-1)}')
        
        # Cleanup
        rm -f "$test_file"
    else
        write_speed="not_available"
        read_speed="not_available"
    fi
    
    # Update health report
    jq --argjson verification "$verification_passed" \
       --arg smart_status "$smart_status" \
       --argjson usage_percent "${usage_percent:-0}" \
       --arg write_speed "$write_speed" \
       --arg read_speed "$read_speed" \
       '.health_checks = {
          "filesystem_verification": $verification,
          "smart_status": $smart_status,
          "disk_usage_percent": $usage_percent,
          "write_speed_mbps": $write_speed,
          "read_speed_mbps": $read_speed
        }' "$health_report" > "${health_report}.tmp" && mv "${health_report}.tmp" "$health_report"
    
    # Health assessment
    local health_score=100
    local issues=()
    
    if [[ "$verification_passed" != "true" ]]; then
        ((health_score -= 30))
        issues+=("filesystem_corruption")
    fi
    
    if [[ "$smart_status" == "failed" ]]; then
        ((health_score -= 50))
        issues+=("smart_failure")
    fi
    
    if [[ ${usage_percent:-0} -gt 90 ]]; then
        ((health_score -= 20))
        issues+=("disk_space_critical")
    elif [[ ${usage_percent:-0} -gt 80 ]]; then
        ((health_score -= 10))
        issues+=("disk_space_warning")
    fi
    
    # Add health score and issues to report
    jq --argjson health_score "$health_score" \
       --argjson issues "$(printf '%s\n' "${issues[@]}" | jq -R . | jq -s .)" \
       '.health_assessment = {
          "overall_score": $health_score,
          "issues_detected": $issues,
          "recommendations": []
        }' "$health_report" > "${health_report}.tmp" && mv "${health_report}.tmp" "$health_report"
    
    # Display results
    echo ""
    echo "Health Assessment Results:"
    echo "  Overall Health Score: $health_score/100"
    echo "  Filesystem Verification: $([ "$verification_passed" = "true" ] && echo "✅ PASSED" || echo "❌ FAILED")"
    echo "  SMART Status: $smart_status"
    echo "  Disk Usage: ${usage_percent:-0}%"
    echo "  Write Speed: $write_speed"
    echo "  Read Speed: $read_speed"
    
    if [[ ${#issues[@]} -gt 0 ]]; then
        echo "  Issues Detected:"
        for issue in "${issues[@]}"; do
            echo "    - $issue"
        done
    else
        echo "  ✅ No issues detected"
    fi
    
    echo "  Health Report: $health_report"
    
    # Log health check
    audit_log "Volume health check completed: $identifier (Score: $health_score/100)"
    
    return 0
}

Enterprise Storage Management System

#!/bin/bash

# Roundfleet Enterprise Storage Management System
# Comprehensive disk and storage management

# Configuration
CONFIG_DIR="/etc/roundfleet/storage"
LOG_FILE="/var/log/roundfleet_storage_management.log"
DATA_DIR="/var/data/roundfleet/storage"
REPORTS_DIR="/var/reports/roundfleet/storage"
AUDIT_LOG="/var/log/roundfleet_storage_audit.log"
BACKUP_DIR="/var/backups/roundfleet/storage"

# Create required directories
create_directories() {
    local directories=("$CONFIG_DIR" "$DATA_DIR" "$REPORTS_DIR" "$BACKUP_DIR")
    
    for dir in "${directories[@]}"; do
        if [[ ! -d "$dir" ]]; then
            sudo mkdir -p "$dir"
            sudo chmod 755 "$dir"
        fi
    done
}

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

log_error() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') [ERROR] $1" | tee -a "$LOG_FILE" >&2
}

audit_log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') [AUDIT] $1" | tee -a "$AUDIT_LOG"
}

# Storage inventory management
initialize_storage_database() {
    local db_file="$DATA_DIR/storage_inventory.json"
    
    if [[ ! -f "$db_file" ]]; then
        cat > "$db_file" << EOF
{
    "version": "1.0",
    "created": "$(date -Iseconds)",
    "storage_devices": {},
    "volume_configurations": {},
    "health_monitoring": {},
    "performance_metrics": {},
    "security_assessments": {}
}
EOF
        log_action "Storage database initialized: $db_file"
    fi
}

# Comprehensive storage discovery
discover_storage_infrastructure() {
    local discovery_file="$DATA_DIR/storage_discovery_$(date +%Y%m%d_%H%M%S).json"
    
    log_action "Starting comprehensive storage discovery"
    
    echo "=== Storage Infrastructure Discovery ==="
    
    # Physical storage devices
    echo "Discovering physical storage devices..."
    local physical_devices
    physical_devices=$(system_profiler SPStorageDataType -json)
    
    # Logical volumes and partitions
    echo "Analyzing logical volumes..."
    local logical_volumes
    logical_volumes=$(diskutil list -plist | plutil -convert json -o -)
    
    # APFS containers and volumes
    echo "Examining APFS containers..."
    local apfs_containers
    apfs_containers=$(diskutil apfs list -plist | plutil -convert json -o -)
    
    # Network mounted volumes
    echo "Checking network volumes..."
    local network_volumes
    network_volumes=$(mount | grep -E "(nfs|smb|afp)" | jq -R . | jq -s .)
    
    # External devices
    echo "Detecting external devices..."
    local external_devices
    external_devices=$(diskutil list external -plist | plutil -convert json -o -)
    
    # Encryption status
    echo "Assessing encryption status..."
    local encryption_status=()
    while IFS= read -r volume; do
        if [[ -n "$volume" ]]; then
            local encrypted="false"
            if diskutil info "$volume" | grep -q "FileVault.*Yes"; then
                encrypted="true"
            fi
            encryption_status+=("{\"volume\": \"$volume\", \"encrypted\": $encrypted}")
        fi
    done <<< "$(diskutil list | grep -E "^\s+[0-9]+:" | awk '{print $NF}')"
    
    # Generate comprehensive discovery report
    cat > "$discovery_file" << EOF
{
    "discovery_timestamp": "$(date -Iseconds)",
    "hostname": "$(hostname)",
    "physical_storage": $physical_devices,
    "logical_volumes": $logical_volumes,
    "apfs_containers": $apfs_containers,
    "network_volumes": $network_volumes,
    "external_devices": $external_devices,
    "encryption_status": [$(IFS=,; echo "${encryption_status[*]}")],
    "system_info": {
        "os_version": "$(sw_vers -productVersion)",
        "total_storage": "$(df -h / | tail -1 | awk '{print $2}')",
        "available_storage": "$(df -h / | tail -1 | awk '{print $4}')"
    }
}
EOF
    
    log_action "Storage discovery completed: $discovery_file"
    
    # Display summary
    echo ""
    echo "Discovery Summary:"
    echo "  Physical Devices: $(echo "$physical_devices" | jq '.SPStorageDataType | length' 2>/dev/null || echo "0")"
    echo "  Logical Volumes: $(echo "$logical_volumes" | jq '.AllDisks | length' 2>/dev/null || echo "0")"
    echo "  APFS Containers: $(echo "$apfs_containers" | jq '.Containers | length' 2>/dev/null || echo "0")"
    echo "  Network Volumes: $(echo "$network_volumes" | jq '. | length' 2>/dev/null || echo "0")"
    echo "  External Devices: $(echo "$external_devices" | jq '.AllDisks | length' 2>/dev/null || echo "0")"
    echo "  Discovery Report: $discovery_file"
    
    return 0
}

# Automated storage optimization
optimize_storage_performance() {
    local optimization_profile="$1"
    local optimization_report="$REPORTS_DIR/storage_optimization_$(date +%Y%m%d_%H%M%S).json"
    
    log_action "Starting storage optimization (Profile: $optimization_profile)"
    
    echo "=== Storage Performance Optimization ==="
    echo "Optimization Profile: $optimization_profile"
    
    # Initialize optimization report
    cat > "$optimization_report" << EOF
{
    "optimization_profile": "$optimization_profile",
    "start_timestamp": "$(date -Iseconds)",
    "hostname": "$(hostname)",
    "optimizations_performed": [],
    "performance_improvements": {},
    "recommendations": []
}
EOF
    
    local optimizations_performed=()
    
    case "$optimization_profile" in
        "performance")
            echo "Applying performance optimizations..."
            
            # Enable TRIM for SSDs
            if sudo trimforce enable 2>/dev/null; then
                optimizations_performed+=("trim_enabled")
                echo "  ✅ TRIM enabled for SSD optimization"
            fi
            
            # Optimize APFS
            for container in $(diskutil apfs list | grep "Container" | awk '{print $2}'); do
                if diskutil apfs defragment "$container" 2>/dev/null; then
                    optimizations_performed+=("apfs_defragment_$container")
                    echo "  ✅ APFS container $container defragmented"
                fi
            done
            
            # Clear system caches
            sudo purge
            optimizations_performed+=("system_cache_cleared")
            echo "  ✅ System caches cleared"
            ;;
            
        "security")
            echo "Applying security optimizations..."
            
            # Enable FileVault if not already enabled
            if ! fdesetup status | grep -q "FileVault is On"; then
                echo "  âš ī¸  FileVault not enabled - recommend enabling for security"
                optimizations_performed+=("filevault_recommendation")
            else
                echo "  ✅ FileVault already enabled"
            fi
            
            # Secure delete free space
            for volume in $(df | grep "^/dev" | awk '{print $1}'); do
                if diskutil secureErase freespace 1 "$volume" 2>/dev/null; then
                    optimizations_performed+=("secure_delete_$volume")
                    echo "  ✅ Secure delete performed on $volume"
                fi
            done
            ;;
            
        "storage_cleanup")
            echo "Performing storage cleanup..."
            
            # Clean system logs
            local log_space_before
            log_space_before=$(du -sh /var/log 2>/dev/null | awk '{print $1}')
            
            sudo log erase --all 2>/dev/null
            optimizations_performed+=("system_logs_cleaned")
            
            # Clean user caches
            local cache_space_before
            cache_space_before=$(du -sh ~/Library/Caches 2>/dev/null | awk '{print $1}')
            
            find ~/Library/Caches -type f -atime +30 -delete 2>/dev/null
            optimizations_performed+=("user_caches_cleaned")
            
            # Clean downloads folder
            find ~/Downloads -type f -atime +90 -delete 2>/dev/null
            optimizations_performed+=("downloads_cleaned")
            
            echo "  ✅ System cleanup completed"
            ;;
            
        *)
            echo "❌ Unknown optimization profile: $optimization_profile"
            return 1
            ;;
    esac
    
    # Update optimization report
    jq --argjson optimizations "$(printf '%s\n' "${optimizations_performed[@]}" | jq -R . | jq -s .)" \
       '.optimizations_performed = $optimizations | .end_timestamp = "'"$(date -Iseconds)"'"' \
       "$optimization_report" > "${optimization_report}.tmp" && mv "${optimization_report}.tmp" "$optimization_report"
    
    echo ""
    echo "Optimization Results:"
    echo "  Profile: $optimization_profile"
    echo "  Optimizations Performed: ${#optimizations_performed[@]}"
    echo "  Report: $optimization_report"
    
    audit_log "Storage optimization completed: $optimization_profile (${#optimizations_performed[@]} optimizations)"
    
    return 0
}

# Bulk volume operations
bulk_volume_operations() {
    local operation="$1"
    local volume_list="$2"
    local operation_report="$REPORTS_DIR/bulk_operations_$(date +%Y%m%d_%H%M%S).json"
    
    log_action "Starting bulk volume operations: $operation"
    
    if [[ ! -f "$volume_list" ]]; then
        log_error "Volume list file not found: $volume_list"
        return 1
    fi
    
    echo "=== Bulk Volume Operations ==="
    echo "Operation: $operation"
    echo "Volume List: $volume_list"
    
    # Initialize operation report
    cat > "$operation_report" << EOF
{
    "operation_type": "$operation",
    "start_timestamp": "$(date -Iseconds)",
    "hostname": "$(hostname)",
    "total_volumes": 0,
    "successful_operations": 0,
    "failed_operations": 0,
    "operation_details": []
}
EOF
    
    local total_volumes=0
    local successful_operations=0
    local failed_operations=0
    
    # Process each volume in the list
    while IFS= read -r volume_entry; do
        if [[ -n "$volume_entry" && ! "$volume_entry" =~ ^# ]]; then
            ((total_volumes++))
            
            # Parse volume entry (format: identifier|name|filesystem)
            IFS='|' read -r identifier name filesystem <<< "$volume_entry"
            
            echo "Processing volume: $identifier"
            
            local operation_success=false
            local operation_message=""
            
            case "$operation" in
                "verify")
                    if diskutil verifyVolume "$identifier" &>/dev/null; then
                        operation_success=true
                        operation_message="Volume verification passed"
                        ((successful_operations++))
                    else
                        operation_message="Volume verification failed"
                        ((failed_operations++))
                    fi
                    ;;
                    
                "repair")
                    if diskutil repairVolume "$identifier" &>/dev/null; then
                        operation_success=true
                        operation_message="Volume repair completed"
                        ((successful_operations++))
                    else
                        operation_message="Volume repair failed"
                        ((failed_operations++))
                    fi
                    ;;
                    
                "mount")
                    if diskutil mount "$identifier" &>/dev/null; then
                        operation_success=true
                        operation_message="Volume mounted successfully"
                        ((successful_operations++))
                    else
                        operation_message="Volume mount failed"
                        ((failed_operations++))
                    fi
                    ;;
                    
                "unmount")
                    if diskutil unmount "$identifier" &>/dev/null; then
                        operation_success=true
                        operation_message="Volume unmounted successfully"
                        ((successful_operations++))
                    else
                        operation_message="Volume unmount failed"
                        ((failed_operations++))
                    fi
                    ;;
                    
                *)
                    operation_message="Unknown operation: $operation"
                    ((failed_operations++))
                    ;;
            esac
            
            echo "  Result: $([ "$operation_success" = "true" ] && echo "✅ SUCCESS" || echo "❌ FAILED") - $operation_message"
            
            # Add to operation report
            local operation_detail=$(cat << EOF
{
    "identifier": "$identifier",
    "name": "$name",
    "filesystem": "$filesystem",
    "success": $operation_success,
    "message": "$operation_message",
    "timestamp": "$(date -Iseconds)"
}
EOF
)
            
            jq --argjson detail "$operation_detail" \
               '.operation_details += [$detail]' \
               "$operation_report" > "${operation_report}.tmp" && mv "${operation_report}.tmp" "$operation_report"
        fi
    done < "$volume_list"
    
    # Update final statistics
    jq --argjson total "$total_volumes" \
       --argjson successful "$successful_operations" \
       --argjson failed "$failed_operations" \
       '.total_volumes = $total | .successful_operations = $successful | .failed_operations = $failed | .end_timestamp = "'"$(date -Iseconds)"'"' \
       "$operation_report" > "${operation_report}.tmp" && mv "${operation_report}.tmp" "$operation_report"
    
    echo ""
    echo "Bulk Operation Summary:"
    echo "  Total Volumes: $total_volumes"
    echo "  Successful: $successful_operations"
    echo "  Failed: $failed_operations"
    echo "  Success Rate: $(( successful_operations * 100 / total_volumes ))%"
    echo "  Operation Report: $operation_report"
    
    log_action "Bulk volume operations completed: $operation ($successful_operations/$total_volumes successful)"
    
    return 0
}

# Fleet-wide storage management
deploy_storage_management() {
    local fleet_config="$1"
    local storage_policy="$2"
    
    log_action "Starting fleet-wide storage management deployment"
    
    if [[ ! -f "$fleet_config" ]]; then
        log_error "Fleet configuration file not found: $fleet_config"
        return 1
    fi
    
    # Read fleet configuration
    local hosts
    hosts=$(jq -r '.hosts[]' "$fleet_config")
    
    echo "Deploying storage management to fleet..."
    echo "Storage Policy: $storage_policy"
    
    # Deploy to each host
    while IFS= read -r host; do
        if [[ -n "$host" ]]; then
            echo "Deploying to: $host"
            
            # Copy storage management script to remote host
            scp "$0" "root@${host}:/tmp/roundfleet_storage.sh" || {
                log_error "Failed to copy script to $host"
                continue
            }
            
            # Apply storage policy on remote host
            ssh "root@${host}" "chmod +x /tmp/roundfleet_storage.sh && /tmp/roundfleet_storage.sh apply_policy '$storage_policy' &" || {
                log_error "Failed to apply storage policy on $host"
                continue
            }
            
            log_action "✅ Storage management deployed on: $host"
        fi
    done <<< "$hosts"
    
    log_action "Fleet storage deployment completed"
}

# Generate comprehensive storage reports
generate_storage_report() {
    local report_type="$1"
    local report_name="${2:-storage_report_$(date +%Y%m%d_%H%M%S)}"
    local report_file="$REPORTS_DIR/${report_name}.json"
    
    log_action "Generating storage report: $report_name (Type: $report_type)"
    
    case "$report_type" in
        "inventory")
            generate_storage_inventory_report "$report_file"
            ;;
        "health_assessment")
            generate_health_assessment_report "$report_file"
            ;;
        "performance_analysis")
            generate_performance_analysis_report "$report_file"
            ;;
        "security_audit")
            generate_security_audit_report "$report_file"
            ;;
        "compliance")
            generate_compliance_report "$report_file"
            ;;
        *)
            log_error "Unknown report type: $report_type"
            return 1
            ;;
    esac
    
    log_action "✅ Storage report generated: $report_file"
    echo "Report saved to: $report_file"
}

# Main function with command routing
main() {
    local command="$1"
    shift
    
    # Initialize
    create_directories
    initialize_storage_database
    
    case "$command" in
        "list")
            # Enhanced disk listing
            get_comprehensive_disk_info
            ;;
        "health_check")
            monitor_volume_health "$@"
            ;;
        "secure_erase")
            secure_erase_volume "$@"
            ;;
        "discover")
            discover_storage_infrastructure
            ;;
        "optimize")
            optimize_storage_performance "$@"
            ;;
        "bulk_operations")
            bulk_volume_operations "$@"
            ;;
        "apply_policy")
            apply_storage_policy "$@"
            ;;
        "fleet_deploy")
            deploy_storage_management "$@"
            ;;
        "generate_report")
            generate_storage_report "$@"
            ;;
        "show_categories")
            print_storage_categories
            ;;
        "show_policies")
            for policy in enterprise_standard high_security_financial creative_workflow development_environment compliance_strict performance_optimized cost_efficient; do
                echo "Policy: $policy"
                get_storage_policy "$policy" | jq .
                echo ""
            done
            ;;
        *)
            echo "Roundfleet Enterprise Storage Management System"
            echo "Usage: $0 <command> [options]"
            echo ""
            echo "Commands:"
            echo "  list                                       - Enhanced disk listing and analysis"
            echo "  health_check <identifier>                 - Comprehensive volume health monitoring"
            echo "  secure_erase <identifier> <level> <name>  - Secure volume erasure"
            echo "  discover                                   - Storage infrastructure discovery"
            echo "  optimize <profile>                        - Storage performance optimization"
            echo "  bulk_operations <operation> <volume_list> - Bulk volume operations"
            echo "  apply_policy <policy>                     - Apply storage management policy"
            echo "  fleet_deploy <fleet_config> <policy>     - Deploy to fleet"
            echo "  generate_report <type> [name]             - Generate storage reports"
            echo "  show_categories                           - Show storage categories"
            echo "  show_policies                             - Show storage policies"
            echo ""
            echo "Examples:"
            echo "  $0 list"
            echo "  $0 health_check disk1s1"
            echo "  $0 secure_erase disk2s1 secure CleanDisk"
            echo "  $0 optimize performance"
            echo "  $0 generate_report inventory"
            ;;
    esac
}

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

Fleet Deployment Configuration

Fleet Configuration Example

{
    "fleet_name": "Roundfleet Enterprise Storage",
    "deployment_date": "2025-07-07",
    "hosts": [
        "mac-workstation-01.company.com",
        "mac-server-01.company.com",
        "mac-dev-01.company.com"
    ],
    "storage_policies": {
        "default": "enterprise_standard",
        "secure_hosts": "high_security_financial",
        "creative_hosts": "creative_workflow"
    },
    "monitoring_schedule": {
        "health_checks": "daily",
        "performance_monitoring": "weekly",
        "security_audits": "monthly"
    }
}

Volume List Example for Bulk Operations

# Volume List for Bulk Operations
# Format: identifier|name|filesystem
disk1s1|Macintosh HD|APFS
disk2s1|Data Volume|APFS
disk3s1|Backup Drive|APFS
disk4s1|External Storage|ExFAT

Security Considerations

Storage Security

  • Encryption Enforcement - Ensure all sensitive volumes are encrypted with FileVault
  • Secure Erasure - Multiple security levels for proper data destruction
  • Access Controls - Monitor and control access to storage resources
  • Integrity Monitoring - Continuous verification of storage integrity
  • Threat Detection - Scan for unauthorized access and suspicious activities

Compliance Framework

  • Data Retention - Automated enforcement of data retention policies
  • Audit Trails - Comprehensive logging of all storage operations
  • Encryption Standards - Compliance with AES-256 and other encryption requirements
  • Backup Verification - Automated verification of backup integrity
  • Disaster Recovery - Storage-focused disaster recovery procedures

Performance Optimization

Storage Performance

  • SSD Optimization - TRIM enablement and wear leveling optimization
  • APFS Optimization - Container defragmentation and snapshot management
  • Cache Management - Intelligent caching and memory optimization
  • I/O Monitoring - Real-time monitoring of storage I/O performance
  • Bottleneck Detection - Automated detection and resolution of performance issues

Troubleshooting Guide

Common Issues

Disk Verification Failures

  • Run First Aid from Disk Utility
  • Boot from Recovery Mode for system volume repairs
  • Check for hardware issues with Apple Diagnostics

Performance Degradation

  • Monitor SMART status for drive health
  • Check for fragmentation on older filesystems
  • Verify adequate free space (maintain 10-15% free)

Mount/Unmount Issues

  • Check for processes using the volume: lsof /Volumes/VolumeName
  • Force unmount if necessary: diskutil unmount force /dev/diskXsY
  • Verify filesystem integrity before remounting

Diagnostic Commands

# Check disk health
diskutil verifyVolume disk1s1

# Monitor disk I/O
iostat -d 1

# Check filesystem usage
df -h

# View SMART status
smartctl -a /dev/disk0

Important Notes

  • Data Safety - Always backup critical data before performing disk operations
  • Administrative Privileges - Most disk operations require sudo/administrator access
  • Testing - Test all scripts on non-production systems before fleet deployment
  • Recovery Planning - Maintain bootable recovery drives and backup strategies
  • Monitoring - Implement continuous monitoring for early problem detection
  • Documentation - Keep detailed records of all storage configurations and changes

Disk Image Management on macOS

Create and manage disk images on your Roundfleet devices for efficient data packaging, software distribution, and system deployment. This tutorial covers disk image creation from folders, advanced formatting options, encryption, compression, and enterprise-scale image management workflows.

Understanding Disk Images

Disk images are file containers that replicate the exact structure and content of storage volumes, providing powerful capabilities for enterprise deployment:

Benefits of Disk Images

  • Software Distribution - Package applications and configurations for deployment
  • Data Backup - Create portable snapshots of folder contents
  • System Deployment - Standardize configurations across multiple devices
  • Secure Transport - Encrypted images for sensitive data transfer
  • Version Control - Maintain different versions of software packages
  • Network Efficiency - Compressed images reduce transfer time

Disk Image Types

  • .dmg - Apple Disk Image (primary format)
  • .iso - ISO 9660 format for cross-platform compatibility
  • .sparseimage - Sparse images that grow as needed
  • .sparsebundle - Bundle format for network storage

Basic Disk Image Creation

Simple Folder to Disk Image

#!/bin/bash

# Create basic disk image from folder
SOURCE_FOLDER="$1"
IMAGE_NAME="$2"
OUTPUT_PATH="$3"

if [[ -z "$SOURCE_FOLDER" || -z "$IMAGE_NAME" || -z "$OUTPUT_PATH" ]]; then
    echo "❌ Usage: $0 <source_folder> <image_name> <output_path>"
    echo "Example: $0 /Users/Shared MyImage /Users/username/Documents"
    exit 1
fi

# Validate source folder exists
if [[ ! -d "$SOURCE_FOLDER" ]]; then
    echo "❌ Source folder does not exist: $SOURCE_FOLDER"
    exit 1
fi

# Create output directory if it doesn't exist
mkdir -p "$OUTPUT_PATH"

echo "đŸ’ŋ Creating disk image from folder..."
echo "Source: $SOURCE_FOLDER"
echo "Image name: $IMAGE_NAME"
echo "Output: $OUTPUT_PATH/$IMAGE_NAME.dmg"

# Create the disk image
if hdiutil create -fs HFS+ -srcfolder "$SOURCE_FOLDER" -volname "$IMAGE_NAME" "$OUTPUT_PATH/$IMAGE_NAME.dmg"; then
    echo "✅ Disk image created successfully"
    
    # Get image size
    IMAGE_SIZE=$(du -h "$OUTPUT_PATH/$IMAGE_NAME.dmg" | cut -f1)
    echo "Image size: $IMAGE_SIZE"
    
    # Get source folder size for comparison
    SOURCE_SIZE=$(du -sh "$SOURCE_FOLDER" | cut -f1)
    echo "Source folder size: $SOURCE_SIZE"
else
    echo "❌ Failed to create disk image"
    exit 1
fi

Advanced Disk Image Creation

#!/bin/bash

# Advanced disk image creation with options
create_advanced_disk_image() {
    local source_folder="$1"
    local image_name="$2"
    local output_path="$3"
    local filesystem="${4:-HFS+}"
    local compression="${5:-UDBZ}"
    local encryption="${6:-false}"
    
    if [[ ! -d "$source_folder" ]]; then
        echo "❌ Source folder not found: $source_folder"
        return 1
    fi
    
    mkdir -p "$output_path"
    
    echo "đŸ’ŋ Creating advanced disk image..."
    echo "Source: $source_folder"
    echo "Filesystem: $filesystem"
    echo "Compression: $compression"
    echo "Encryption: $encryption"
    
    # Build hdiutil command
    local cmd="hdiutil create"
    cmd="$cmd -fs $filesystem"
    cmd="$cmd -srcfolder '$source_folder'"
    cmd="$cmd -volname '$image_name'"
    
    # Add compression if specified
    if [[ "$compression" != "none" ]]; then
        cmd="$cmd -format $compression"
    fi
    
    # Add encryption if requested
    if [[ "$encryption" == "true" ]]; then
        cmd="$cmd -encryption AES-256"
        cmd="$cmd -stdinpass"
        echo "🔐 Encryption enabled - you will be prompted for a password"
    fi
    
    cmd="$cmd '$output_path/$image_name.dmg'"
    
    # Execute command
    if [[ "$encryption" == "true" ]]; then
        echo "Enter password for disk image encryption:"
        read -s password
        echo "$password" | eval "$cmd"
    else
        eval "$cmd"
    fi
    
    if [[ $? -eq 0 ]]; then
        echo "✅ Advanced disk image created successfully"
        
        # Display image information
        echo ""
        echo "=== Image Information ==="
        hdiutil imageinfo "$output_path/$image_name.dmg" | grep -E "Format|Compressed|Encrypted|Checksum"
        
        return 0
    else
        echo "❌ Failed to create disk image"
        return 1
    fi
}

# Usage examples
# create_advanced_disk_image "/Users/Shared" "SharedData" "/tmp" "HFS+" "UDBZ" "false"
# create_advanced_disk_image "/Applications/MyApp.app" "MyApp" "/tmp" "HFS+" "UDZO" "true"

Filesystem and Format Options

Supported Filesystems

#!/bin/bash

# Display available filesystem and format options
show_disk_image_options() {
    echo "=== Available Filesystems ==="
    echo "HFS+     - Mac OS Extended (default)"
    echo "HFS+J    - Mac OS Extended (Journaled)"
    echo "HFSX     - Mac OS Extended (Case-sensitive)"
    echo "JHFS+X   - Mac OS Extended (Case-sensitive, Journaled)"
    echo "MS-DOS   - FAT32 (compatible with Windows)"
    echo "UDF      - Universal Disk Format"
    echo "APFS     - Apple File System (macOS 10.13+)"
    echo ""
    
    echo "=== Image Format Options ==="
    echo "UDRO     - Read-only, smaller size"
    echo "UDCO     - ADC compressed (obsolete)"
    echo "UDZO     - zlib compressed (most common)"
    echo "UDBZ     - bzip2 compressed (better compression)"
    echo "ULFO     - lzfse compressed (macOS 10.11+)"
    echo "ULMO     - lzma compressed"
    echo "UFBI     - Entire device"
    echo "SPARSE   - Sparse image (grows as needed)"
    echo "SPARSEBUNDLE - Sparse bundle (network friendly)"
    echo ""
    
    echo "=== Encryption Options ==="
    echo "AES-128  - 128-bit AES encryption"
    echo "AES-256  - 256-bit AES encryption (recommended)"
}

# Create disk image with specific options
create_custom_disk_image() {
    local source="$1"
    local name="$2"
    local output="$3"
    local fs="$4"
    local format="$5"
    local encrypt="$6"
    
    echo "Creating custom disk image with:"
    echo "  Filesystem: $fs"
    echo "  Format: $format"
    echo "  Encryption: $encrypt"
    
    local cmd="hdiutil create -fs '$fs' -format '$format'"
    
    if [[ "$encrypt" != "none" ]]; then
        cmd="$cmd -encryption '$encrypt' -stdinpass"
    fi
    
    cmd="$cmd -srcfolder '$source' -volname '$name' '$output/$name.dmg'"
    
    if [[ "$encrypt" != "none" ]]; then
        echo "Enter encryption password:"
        read -s password
        echo "$password" | eval "$cmd"
    else
        eval "$cmd"
    fi
}

# Example usage
# show_disk_image_options
# create_custom_disk_image "/path/to/folder" "MyImage" "/output/path" "HFS+" "UDBZ" "AES-256"

Batch Disk Image Operations

Batch Image Creation

#!/bin/bash

# Batch create disk images from multiple folders
batch_create_disk_images() {
    local base_path="$1"
    local output_dir="$2"
    local filesystem="${3:-HFS+}"
    local format="${4:-UDBZ}"
    
    if [[ ! -d "$base_path" ]]; then
        echo "❌ Base path not found: $base_path"
        return 1
    fi
    
    mkdir -p "$output_dir"
    
    echo "🔄 Starting batch disk image creation..."
    echo "Base path: $base_path"
    echo "Output directory: $output_dir"
    echo "Filesystem: $filesystem"
    echo "Format: $format"
    echo ""
    
    local success_count=0
    local failed_count=0
    local total_size=0
    
    # Process each subdirectory
    find "$base_path" -type d -mindepth 1 -maxdepth 1 | while read -r folder; do
        local folder_name=$(basename "$folder")
        local image_path="$output_dir/${folder_name}.dmg"
        
        echo "Processing: $folder_name"
        
        # Skip if image already exists
        if [[ -f "$image_path" ]]; then
            echo "  â­ī¸  Image already exists, skipping"
            continue
        fi
        
        # Create disk image
        if hdiutil create -fs "$filesystem" -format "$format" \
           -srcfolder "$folder" -volname "$folder_name" \
           "$image_path" >/dev/null 2>&1; then
            
            local size=$(du -h "$image_path" | cut -f1)
            echo "  ✅ Created successfully ($size)"
            ((success_count++))
            
            # Add to total size calculation
            local size_bytes=$(du -b "$image_path" | cut -f1)
            total_size=$((total_size + size_bytes))
        else
            echo "  ❌ Failed to create image"
            ((failed_count++))
        fi
    done
    
    echo ""
    echo "=== Batch Operation Summary ==="
    echo "Successful: $success_count"
    echo "Failed: $failed_count"
    echo "Total size: $(numfmt --to=iec $total_size)"
}

# Usage example
# batch_create_disk_images "/Users/Shared/Projects" "/tmp/project_images" "HFS+" "UDBZ"

Image Verification and Analysis

#!/bin/bash

# Verify and analyze disk images
verify_disk_image() {
    local image_path="$1"
    
    if [[ ! -f "$image_path" ]]; then
        echo "❌ Image file not found: $image_path"
        return 1
    fi
    
    echo "🔍 Verifying disk image: $(basename "$image_path")"
    
    # Basic image information
    echo ""
    echo "=== Basic Information ==="
    echo "File size: $(du -h "$image_path" | cut -f1)"
    echo "File type: $(file "$image_path" | cut -d: -f2- | xargs)"
    
    # Detailed image information
    echo ""
    echo "=== Detailed Image Information ==="
    hdiutil imageinfo "$image_path" | grep -E "Format|Partition|Compressed|Encrypted|Checksum|Total"
    
    # Verify image integrity
    echo ""
    echo "=== Integrity Verification ==="
    if hdiutil verify "$image_path" >/dev/null 2>&1; then
        echo "✅ Image integrity verified successfully"
    else
        echo "❌ Image integrity verification failed"
        return 1
    fi
    
    # Test mount capability
    echo ""
    echo "=== Mount Test ==="
    local mount_point=$(mktemp -d)
    
    if hdiutil attach "$image_path" -mountpoint "$mount_point" -nobrowse -quiet; then
        echo "✅ Image mounts successfully"
        
        # Get volume information
        echo "Volume info: $(df -h "$mount_point" | tail -1 | awk '{print $2 " total, " $3 " used, " $4 " available"}')"
        
        # Count contents
        local file_count=$(find "$mount_point" -type f | wc -l | xargs)
        local dir_count=$(find "$mount_point" -type d | wc -l | xargs)
        echo "Contents: $file_count files, $dir_count directories"
        
        # Unmount
        hdiutil detach "$mount_point" -quiet
        rmdir "$mount_point"
    else
        echo "❌ Image failed to mount"
        rmdir "$mount_point"
        return 1
    fi
    
    echo ""
    echo "✅ Image verification completed successfully"
    return 0
}

# Batch verification
verify_multiple_images() {
    local image_dir="$1"
    
    if [[ ! -d "$image_dir" ]]; then
        echo "❌ Image directory not found: $image_dir"
        return 1
    fi
    
    echo "🔍 Verifying all disk images in: $image_dir"
    echo ""
    
    local verified=0
    local failed=0
    
    find "$image_dir" -name "*.dmg" -type f | while read -r image; do
        echo "Verifying: $(basename "$image")"
        if verify_disk_image "$image" >/dev/null 2>&1; then
            echo "  ✅ Verified"
            ((verified++))
        else
            echo "  ❌ Failed"
            ((failed++))
        fi
    done
    
    echo ""
    echo "Verification complete: $verified passed, $failed failed"
}

Enterprise Disk Image Management

#!/bin/bash

# Roundfleet Disk Image Management Tool
# Comprehensive disk image creation and management for enterprise environments

# Configuration
LOG_FILE="/var/log/roundfleet_diskimage.log"
BACKUP_DIR="/var/backups/roundfleet/images"
REPORT_DIR="/var/reports/roundfleet/images"
CONFIG_FILE="/etc/roundfleet/image_policy.conf"
TEMP_DIR="/tmp/roundfleet_images"

# Default settings
DEFAULT_FILESYSTEM="HFS+"
DEFAULT_FORMAT="UDBZ"
DEFAULT_ENCRYPTION="AES-256"
ENABLE_COMPRESSION=true
ENABLE_VERIFICATION=true
MAX_IMAGE_SIZE="10G"
CLEANUP_TEMP_FILES=true

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

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

# Check available disk space
check_disk_space() {
    local target_dir="$1"
    local required_space="$2"  # in bytes
    
    local available_space=$(df "$target_dir" | tail -1 | awk '{print $4}')
    available_space=$((available_space * 1024))  # Convert to bytes
    
    if [[ "$available_space" -lt "$required_space" ]]; then
        echo "❌ Insufficient disk space"
        echo "Required: $(numfmt --to=iec $required_space)"
        echo "Available: $(numfmt --to=iec $available_space)"
        return 1
    fi
    
    return 0
}

# Create enterprise disk image with full logging and validation
create_enterprise_disk_image() {
    local source_path="$1"
    local image_name="$2"
    local output_dir="$3"
    local filesystem="${4:-$DEFAULT_FILESYSTEM}"
    local format="${5:-$DEFAULT_FORMAT}"
    local encrypt="${6:-false}"
    local description="$7"
    
    log_action "Starting enterprise disk image creation: $image_name"
    
    # Validation
    if [[ ! -d "$source_path" ]]; then
        echo "❌ Source path not found: $source_path"
        log_action "ERROR: Source path not found: $source_path"
        return 1
    fi
    
    # Calculate source size
    local source_size_bytes=$(du -sb "$source_path" | cut -f1)
    local source_size_human=$(du -sh "$source_path" | cut -f1)
    
    echo "📁 Source analysis:"
    echo "  Path: $source_path"
    echo "  Size: $source_size_human ($source_size_bytes bytes)"
    
    # Check disk space (estimate 2x source size for safety)
    local estimated_space=$((source_size_bytes * 2))
    if ! check_disk_space "$output_dir" "$estimated_space"; then
        log_action "ERROR: Insufficient disk space for image creation"
        return 1
    fi
    
    # Create output directory
    mkdir -p "$output_dir"
    
    local output_path="$output_dir/$image_name.dmg"
    local start_time=$(date +%s)
    
    echo ""
    echo "đŸ’ŋ Creating disk image..."
    echo "  Name: $image_name"
    echo "  Filesystem: $filesystem"
    echo "  Format: $format"
    echo "  Output: $output_path"
    
    # Build command
    local cmd="hdiutil create -fs '$filesystem' -format '$format'"
    cmd="$cmd -srcfolder '$source_path' -volname '$image_name'"
    
    # Add encryption if requested
    if [[ "$encrypt" == "true" ]]; then
        cmd="$cmd -encryption '$DEFAULT_ENCRYPTION' -stdinpass"
        echo "  Encryption: Enabled ($DEFAULT_ENCRYPTION)"
    fi
    
    cmd="$cmd '$output_path'"
    
    # Execute image creation
    local creation_success=false
    
    if [[ "$encrypt" == "true" ]]; then
        echo ""
        echo "🔐 Enter password for disk image encryption:"
        read -s password
        if echo "$password" | eval "$cmd" >/dev/null 2>&1; then
            creation_success=true
        fi
    else
        if eval "$cmd" >/dev/null 2>&1; then
            creation_success=true
        fi
    fi
    
    local end_time=$(date +%s)
    local duration=$((end_time - start_time))
    
    if [[ "$creation_success" == "true" ]]; then
        local image_size_bytes=$(du -b "$output_path" | cut -f1)
        local image_size_human=$(du -h "$output_path" | cut -f1)
        local compression_ratio=$(echo "scale=2; $image_size_bytes * 100 / $source_size_bytes" | bc)
        
        echo ""
        echo "✅ Disk image created successfully"
        echo "  Creation time: ${duration}s"
        echo "  Image size: $image_size_human"
        echo "  Compression ratio: ${compression_ratio}%"
        
        # Verify image if enabled
        if [[ "$ENABLE_VERIFICATION" == "true" ]]; then
            echo ""
            echo "🔍 Verifying image integrity..."
            if hdiutil verify "$output_path" >/dev/null 2>&1; then
                echo "✅ Image verification passed"
                log_action "Image created and verified: $image_name ($image_size_human)"
            else
                echo "❌ Image verification failed"
                log_action "ERROR: Image verification failed: $image_name"
                return 1
            fi
        fi
        
        # Generate image metadata
        create_image_metadata "$output_path" "$source_path" "$description"
        
        return 0
    else
        echo "❌ Failed to create disk image"
        log_action "ERROR: Failed to create disk image: $image_name"
        return 1
    fi
}

# Create metadata file for the image
create_image_metadata() {
    local image_path="$1"
    local source_path="$2"
    local description="$3"
    
    local metadata_file="${image_path%.dmg}.json"
    
    cat > "$metadata_file" << EOF
{
    "image_name": "$(basename "$image_path")",
    "creation_date": "$(date -Iseconds)",
    "source_path": "$source_path",
    "image_path": "$image_path",
    "description": "$description",
    "file_size": $(du -b "$image_path" | cut -f1),
    "file_size_human": "$(du -h "$image_path" | cut -f1)",
    "checksum_md5": "$(md5 -q "$image_path")",
    "checksum_sha256": "$(shasum -a 256 "$image_path" | cut -d' ' -f1)",
    "format_info": $(hdiutil imageinfo "$image_path" -plist | plutil -convert json -o - -)
}
EOF
    
    echo "📄 Metadata saved: $metadata_file"
}

# Generate comprehensive image report
generate_image_report() {
    local image_dir="${1:-$BACKUP_DIR}"
    local report_file="$REPORT_DIR/image_report_$(date +%Y%m%d_%H%M%S).txt"
    
    echo "📊 Generating disk image report..."
    
    {
        echo "Roundfleet Disk Image Management Report"
        echo "Generated: $(date)"
        echo "Image Directory: $image_dir"
        echo "======================================"
        echo ""
        
        if [[ ! -d "$image_dir" ]]; then
            echo "❌ Image directory not found: $image_dir"
            return 1
        fi
        
        # Count and analyze images
        local total_images=$(find "$image_dir" -name "*.dmg" -type f | wc -l)
        local total_size_bytes=0
        local verified_count=0
        local failed_count=0
        
        echo "=== Summary ==="
        echo "Total disk images: $total_images"
        
        if [[ "$total_images" -eq 0 ]]; then
            echo "No disk images found in directory"
            return 0
        fi
        
        echo ""
        echo "=== Image Details ==="
        printf "%-30s %-10s %-15s %-10s\n" "Name" "Size" "Format" "Status"
        printf "%-30s %-10s %-15s %-10s\n" "----" "----" "------" "------"
        
        find "$image_dir" -name "*.dmg" -type f | sort | while read -r image_path; do
            local image_name=$(basename "$image_path")
            local image_size=$(du -h "$image_path" | cut -f1)
            local image_size_bytes=$(du -b "$image_path" | cut -f1)
            
            # Get format info
            local format_info=$(hdiutil imageinfo "$image_path" 2>/dev/null | grep "Format Description" | cut -d: -f2- | xargs)
            if [[ -z "$format_info" ]]; then
                format_info="Unknown"
            fi
            
            # Verify integrity
            local status="Unknown"
            if hdiutil verify "$image_path" >/dev/null 2>&1; then
                status="✅ Valid"
                ((verified_count++))
            else
                status="❌ Failed"
                ((failed_count++))
            fi
            
            printf "%-30s %-10s %-15s %-10s\n" "$image_name" "$image_size" "$format_info" "$status"
            
            total_size_bytes=$((total_size_bytes + image_size_bytes))
        done
        
        echo ""
        echo "=== Statistics ==="
        echo "Total size: $(numfmt --to=iec $total_size_bytes)"
        echo "Verified images: $verified_count"
        echo "Failed verification: $failed_count"
        echo "Average size: $(numfmt --to=iec $((total_size_bytes / total_images)))"
        
        # Storage recommendations
        echo ""
        echo "=== Recommendations ==="
        if [[ "$failed_count" -gt 0 ]]; then
            echo "âš ī¸  $failed_count images failed verification - investigate and recreate"
        fi
        
        if [[ "$total_size_bytes" -gt $((50 * 1024 * 1024 * 1024)) ]]; then  # 50GB
            echo "💡 Consider archiving older images to free up space"
        fi
        
        echo "💡 Regular verification recommended for critical images"
        
    } > "$report_file"
    
    echo "📊 Report saved to: $report_file"
    log_action "Image report generated: $report_file"
}

# Main execution function
main() {
    local action="${1:-help}"
    local source="${2:-}"
    local name="${3:-}"
    local output="${4:-$BACKUP_DIR}"
    
    log_action "=== Roundfleet Disk Image Management Started ==="
    
    setup_directories
    
    case "$action" in
        "create")
            if [[ -n "$source" && -n "$name" ]]; then
                create_enterprise_disk_image "$source" "$name" "$output"
            else
                echo "❌ Usage: $0 create <source_folder> <image_name> [output_dir]"
                echo "Example: $0 create /Users/Shared MyImage /tmp"
            fi
            ;;
        "batch")
            if [[ -n "$source" ]]; then
                batch_create_disk_images "$source" "$output"
            else
                echo "❌ Usage: $0 batch <base_folder> [output_dir]"
                echo "Example: $0 batch /Users/Shared/Projects /tmp/images"
            fi
            ;;
        "verify")
            if [[ -n "$source" ]]; then
                if [[ -f "$source" ]]; then
                    verify_disk_image "$source"
                elif [[ -d "$source" ]]; then
                    verify_multiple_images "$source"
                else
                    echo "❌ Path not found: $source"
                fi
            else
                echo "❌ Usage: $0 verify <image_file_or_directory>"
            fi
            ;;
        "report")
            generate_image_report "$source"
            ;;
        "info")
            if [[ -n "$source" && -f "$source" ]]; then
                echo "=== Image Information ==="
                hdiutil imageinfo "$source"
            else
                echo "❌ Usage: $0 info <image_file>"
            fi
            ;;
        "options")
            show_disk_image_options
            ;;
        "help"|*)
            echo "Roundfleet Disk Image Management Tool"
            echo "Usage: $0 [action] [options]"
            echo ""
            echo "Actions:"
            echo "  create <source> <name> [output]  - Create disk image from folder"
            echo "  batch <base_dir> [output]        - Create images from all subdirectories"
            echo "  verify <image_or_dir>            - Verify image integrity"
            echo "  report [image_dir]               - Generate comprehensive report"
            echo "  info <image_file>                - Show detailed image information"
            echo "  options                          - Show available filesystem and format options"
            echo "  help                             - Show this help message"
            echo ""
            echo "Examples:"
            echo "  $0 create /Users/Shared MyData   # Create MyData.dmg from /Users/Shared"
            echo "  $0 batch /Applications /tmp       # Create images for all apps"
            echo "  $0 verify /tmp/MyData.dmg         # Verify single image"
            echo "  $0 report /tmp                    # Generate report for all images in /tmp"
            echo ""
            echo "Configuration:"
            echo "  Default filesystem: $DEFAULT_FILESYSTEM"
            echo "  Default format: $DEFAULT_FORMAT"
            echo "  Default encryption: $DEFAULT_ENCRYPTION"
            echo "  Verification enabled: $ENABLE_VERIFICATION"
            ;;
    esac
    
    log_action "=== Roundfleet Disk Image Management Completed ==="
}

# Execute main function
main "$@"

Image Format Comparison

FormatCompressionSizeCompatibilityUse Case
UDRONoneLargeUniversalTesting, temporary images
UDZOzlib (good)MediummacOS 10.2+General purpose, good balance
UDBZbzip2 (better)SmallmacOS 10.4+Archive storage, slower access
ULFOlzfse (fast)SmallmacOS 10.11+Modern systems, fast compression
SPARSENoneVariablemacOSGrowing images, development

Security and Encryption

Encrypted Image Creation

# Create encrypted disk image with enterprise policies
create_secure_image() {
    local source="$1"
    local name="$2"
    local output="$3"
    local encryption_level="${4:-AES-256}"
    
    echo "🔐 Creating encrypted disk image..."
    echo "Encryption: $encryption_level"
    
    # Generate secure password if not provided
    if [[ -z "$IMAGE_PASSWORD" ]]; then
        echo "Enter encryption password (or set IMAGE_PASSWORD environment variable):"
        read -s IMAGE_PASSWORD
    fi
    
    echo "$IMAGE_PASSWORD" | hdiutil create \
        -fs HFS+ \
        -format UDBZ \
        -encryption "$encryption_level" \
        -stdinpass \
        -srcfolder "$source" \
        -volname "$name" \
        "$output/$name.dmg"
    
    if [[ $? -eq 0 ]]; then
        echo "✅ Encrypted image created successfully"
        echo "🔒 Image is protected with $encryption_level encryption"
    else
        echo "❌ Failed to create encrypted image"
        return 1
    fi
}

Important Notes

  • Disk Space - Ensure sufficient space for image creation (2x source size recommended)
  • Performance - Compression trades size for creation/access speed
  • Security - Use AES-256 encryption for sensitive data
  • Compatibility - Choose appropriate filesystem for target systems
  • Verification - Always verify critical images after creation
  • Enterprise Deployment - Test image mounting on target systems before bulk deployment

Disable Automatic macOS Updates

In enterprise environments, controlling when and how macOS updates are installed is crucial for maintaining system stability and ensuring compatibility with business applications. This tutorial shows how to disable automatic macOS updates using shell scripts.

Understanding macOS Update Settings

macOS has two main automatic update behaviors:

  • Automatic Download: Downloads updates in the background
  • Automatic Check: Periodically checks Apple's servers for new updates

Both can be controlled via the com.apple.SoftwareUpdate preference domain.

Basic Scripts

Disable Automatic Download

#!/bin/bash
defaults write /Library/Preferences/com.apple.SoftwareUpdate AutomaticDownload -boolean false

Disable Automatic Check

#!/bin/bash
defaults write /Library/Preferences/com.apple.SoftwareUpdate AutomaticCheckEnabled -boolean false

Enterprise Deployment Script

For large-scale deployment across your Roundfleet:

#!/bin/bash

# Disable Automatic macOS Updates - Enterprise Script
# Compatible with macOS 10.14+

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

# Function to get current user
get_current_user() {
    stat -f "%Su" /dev/console
}

# Main configuration function
configure_updates() {
    local current_user
    current_user=$(get_current_user)
    
    log_message "Starting macOS update configuration for user: $current_user"
    
    # Disable automatic download
    if defaults write /Library/Preferences/com.apple.SoftwareUpdate AutomaticDownload -boolean false; then
        log_message "✓ Automatic download disabled successfully"
    else
        log_message "✗ Failed to disable automatic download"
        return 1
    fi
    
    # Disable automatic check
    if defaults write /Library/Preferences/com.apple.SoftwareUpdate AutomaticCheckEnabled -boolean false; then
        log_message "✓ Automatic check disabled successfully"
    else
        log_message "✗ Failed to disable automatic check"
        return 1
    fi
    
    # Disable automatic installation (additional security)
    if defaults write /Library/Preferences/com.apple.SoftwareUpdate AutomaticallyInstallMacOSUpdates -boolean false; then
        log_message "✓ Automatic installation disabled successfully"
    else
        log_message "✗ Failed to disable automatic installation"
    fi
    
    # Kill Software Update preferences to force reload
    killall -HUP cfprefsd 2>/dev/null || true
    
    log_message "macOS update configuration completed"
    return 0
}

# Verification function
verify_configuration() {
    local download_status check_status install_status
    
    download_status=$(defaults read /Library/Preferences/com.apple.SoftwareUpdate AutomaticDownload 2>/dev/null || echo "not set")
    check_status=$(defaults read /Library/Preferences/com.apple.SoftwareUpdate AutomaticCheckEnabled 2>/dev/null || echo "not set")
    install_status=$(defaults read /Library/Preferences/com.apple.SoftwareUpdate AutomaticallyInstallMacOSUpdates 2>/dev/null || echo "not set")
    
    log_message "Configuration verification:"
    log_message "  Automatic Download: $download_status"
    log_message "  Automatic Check: $check_status"
    log_message "  Automatic Install: $install_status"
}

# Execute main function
if configure_updates; then
    verify_configuration
    log_message "Script executed successfully"
    exit 0
else
    log_message "Script execution failed"
    exit 1
fi

Verification Script

Check current update settings:

#!/bin/bash

echo "=== macOS Update Settings Status ==="
echo "Automatic Download: $(defaults read /Library/Preferences/com.apple.SoftwareUpdate AutomaticDownload 2>/dev/null || echo 'Not configured')"
echo "Automatic Check: $(defaults read /Library/Preferences/com.apple.SoftwareUpdate AutomaticCheckEnabled 2>/dev/null || echo 'Not configured')"
echo "Automatic Install: $(defaults read /Library/Preferences/com.apple.SoftwareUpdate AutomaticallyInstallMacOSUpdates 2>/dev/null || echo 'Not configured')"

Re-enabling Updates

To restore automatic updates:

#!/bin/bash

# Re-enable automatic download
defaults write /Library/Preferences/com.apple.SoftwareUpdate AutomaticDownload -boolean true

# Re-enable automatic check
defaults write /Library/Preferences/com.apple.SoftwareUpdate AutomaticCheckEnabled -boolean true

# Re-enable automatic installation
defaults write /Library/Preferences/com.apple.SoftwareUpdate AutomaticallyInstallMacOSUpdates -boolean true

echo "Automatic updates re-enabled"

Troubleshooting

IssueSolution
Settings revert after restartEnsure scripts run with admin privileges
System Preferences shows old valuesRestart System Preferences or run killall -HUP cfprefsd
Changes don't applyCheck /var/log/macos_update_config.log for errors
Updates still downloadVerify the preference file permissions

Important Notes

  • Users with admin privileges can manually change these settings
  • The System Preferences/Settings app may need to be restarted to reflect changes
  • Consider using Configuration Profiles for stricter enforcement
  • Test on a small group before enterprise-wide deployment

Configuration Profile Alternative

For stricter control, consider deploying a Configuration Profile instead:

<key>AutomaticCheckEnabled</key>
<false/>
<key>AutomaticDownload</key>
<false/>
<key>AutomaticallyInstallMacOSUpdates</key>
<false/>

Directory Listing and File Management on macOS

Master file and directory listing operations on your Roundfleet devices using powerful command-line tools. This tutorial covers basic file listing, hidden file discovery, detailed information display, and advanced sorting techniques for effective file system management.

Understanding macOS Directory Operations

macOS provides robust command-line tools for directory management:

  • ls - List directory contents with various options
  • find - Search for files and directories with advanced criteria
  • tree - Display directory structure in tree format
  • stat - Display detailed file/directory information

Basic File Listing Operations

List All Files in Directory

#!/bin/bash

# Basic directory listing
FOLDER_PATH="/Users/QA/Desktop/Wallpapers"

echo "Files in $FOLDER_PATH:"
ls "$FOLDER_PATH"

echo "Directory listing completed successfully"

Recursive Directory Listing

#!/bin/bash

# List all files recursively (including subdirectories)
FOLDER_PATH="/Users/QA/Desktop/Wallpapers"

echo "Recursive listing of $FOLDER_PATH:"
ls -R "$FOLDER_PATH"

echo "Recursive directory listing completed"

Hidden Files and Directories

View Hidden Content

#!/bin/bash

# Display all files including hidden ones
FOLDER_PATH="/Users/QA/Desktop/Wallpapers"

echo "All files (including hidden) in $FOLDER_PATH:"
ls -a "$FOLDER_PATH"

echo "Hidden files displayed successfully"

Hidden Files Analysis

#!/bin/bash

# Comprehensive hidden file analysis
analyze_hidden_files() {
    local folder_path="$1"
    
    echo "=== Hidden Files Analysis for: $folder_path ==="
    
    # Count hidden files
    local hidden_count
    hidden_count=$(ls -la "$folder_path" | grep "^\." | wc -l)
    echo "Hidden files found: $((hidden_count - 2))" # Subtract . and ..
    
    # List hidden files with details
    echo -e "\nHidden files:"
    ls -la "$folder_path" | grep "^\." | grep -v "^total"
    
    # Check for common hidden file types
    echo -e "\nCommon hidden file types:"
    ls -a "$folder_path" | grep "^\." | grep -E "\.(DS_Store|Spotlight-V100|Trashes|fseventsd)" || echo "No common system hidden files found"
}

# Usage
analyze_hidden_files "/Users/QA/Desktop/Wallpapers"

Detailed File Information

Long Format Listing

#!/bin/bash

# Display detailed file information
FOLDER_PATH="/Users/QA/Desktop/Wallpapers"

echo "Detailed file information for $FOLDER_PATH:"
ls -l "$FOLDER_PATH"

echo "Detailed listing completed"

Human-Readable File Sizes

#!/bin/bash

# Display file sizes in human-readable format
FOLDER_PATH="/Users/QA/Desktop/Wallpapers"

echo "Files with human-readable sizes in $FOLDER_PATH:"
ls -lh "$FOLDER_PATH"

echo "Human-readable listing completed"

Comprehensive File Details

#!/bin/bash

# Advanced file information display
show_file_details() {
    local folder_path="$1"
    
    echo "=== Comprehensive File Details: $folder_path ==="
    
    # Basic listing with permissions, sizes, dates
    echo "Detailed file listing:"
    ls -lah "$folder_path"
    
    echo -e "\nDirectory summary:"
    echo "Total items: $(ls -1 "$folder_path" | wc -l)"
    echo "Total size: $(du -sh "$folder_path" | cut -f1)"
    echo "Disk usage: $(du -sk "$folder_path" | cut -f1) KB"
    
    # File type breakdown
    echo -e "\nFile type analysis:"
    find "$folder_path" -maxdepth 1 -type f -exec file {} \; | cut -d: -f2 | sort | uniq -c | sort -nr
}

# Usage
show_file_details "/Users/QA/Desktop/Wallpapers"

File Sorting Options

Sort by Modification Time

#!/bin/bash

# Sort files by last modification time (newest first)
FOLDER_PATH="/Users/QA/Desktop/Wallpapers"

echo "Files sorted by modification time (newest first):"
ls -t "$FOLDER_PATH"

echo "Time-based sorting completed"

Sort by File Size

#!/bin/bash

# Sort files by size (largest first)
FOLDER_PATH="/Users/QA/Desktop/Wallpapers"

echo "Files sorted by size (largest first):"
ls -lhS "$FOLDER_PATH"

echo "Size-based sorting completed"

Advanced Sorting Options

#!/bin/bash

# Multiple sorting criteria
advanced_sorting() {
    local folder_path="$1"
    
    echo "=== Advanced File Sorting: $folder_path ==="
    
    echo "1. By modification time (newest first):"
    ls -lt "$folder_path" | head -10
    
    echo -e "\n2. By modification time (oldest first):"
    ls -ltr "$folder_path" | head -10
    
    echo -e "\n3. By size (largest first):"
    ls -lhS "$folder_path" | head -10
    
    echo -e "\n4. By size (smallest first):"
    ls -lhSr "$folder_path" | head -10
    
    echo -e "\n5. By name (alphabetical):"
    ls -l "$folder_path" | sort -k9
    
    echo -e "\n6. By extension:"
    ls -1 "$folder_path" | grep '\.' | sort -t. -k2
}

# Usage
advanced_sorting "/Users/QA/Desktop/Wallpapers"

Enterprise Directory Management System

#!/bin/bash

# Roundfleet Directory Management Tool
# Comprehensive file and directory analysis for fleet devices

# Configuration
SCRIPT_VERSION="1.0.0"
LOG_FILE="/var/log/roundfleet_directory.log"
REPORT_DIR="/etc/roundfleet/reports/directory"
CONFIG_DIR="/etc/roundfleet/directory"

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

# Directory categories for analysis
declare -A DIRECTORY_CATEGORIES=(
    ["system"]="/System,/Library,/usr,/bin,/sbin"
    ["user"]="/Users,/home"
    ["applications"]="/Applications,/Applications/Utilities"
    ["documents"]="/Documents,/Desktop,/Downloads"
    ["media"]="/Movies,/Music,/Pictures"
    ["temporary"]="/tmp,/var/tmp,/var/cache"
    ["logs"]="/var/log,/Library/Logs"
    ["configuration"]="/etc,/private/etc,/Library/Preferences"
    ["development"]="/usr/local,/opt,/Developer"
    ["network"]="/Network,/Volumes"
)

# Directory policies for different scanning levels
declare -A DIRECTORY_POLICIES=(
    ["quick_scan"]="basic_listing,file_count,size_summary"
    ["standard_scan"]="detailed_listing,hidden_files,type_analysis,permission_check"
    ["comprehensive_scan"]="full_recursive,security_scan,duplicate_detection,metadata_extraction"
    ["security_audit"]="permission_audit,ownership_check,sensitive_file_scan,access_log"
    ["performance_scan"]="large_file_detection,fragmentation_check,cache_analysis"
    ["compliance_scan"]="policy_validation,retention_check,classification_audit"
)

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

# Directory analysis engine
analyze_directory() {
    local target_path="$1"
    local scan_level="${2:-standard_scan}"
    local category="${3:-general}"
    
    log_action "Starting directory analysis: $target_path (Level: $scan_level, Category: $category)"
    
    if [[ ! -d "$target_path" ]]; then
        log_action "ERROR: Directory not found: $target_path"
        return 1
    fi
    
    local report_file="$REPORT_DIR/directory_analysis_$(echo "$target_path" | tr '/' '_')_$(date +%Y%m%d_%H%M%S).json"
    
    # Initialize report
    cat > "$report_file" << EOF
{
    "analysis_info": {
        "target_path": "$target_path",
        "scan_level": "$scan_level",
        "category": "$category",
        "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
        "hostname": "$(hostname)",
        "script_version": "$SCRIPT_VERSION"
    },
    "directory_metrics": {},
    "file_analysis": {},
    "security_findings": {},
    "recommendations": []
}
EOF
    
    # Basic directory metrics
    local total_items=$(find "$target_path" -maxdepth 1 2>/dev/null | wc -l)
    local total_files=$(find "$target_path" -maxdepth 1 -type f 2>/dev/null | wc -l)
    local total_dirs=$(find "$target_path" -maxdepth 1 -type d 2>/dev/null | wc -l)
    local total_size=$(du -sk "$target_path" 2>/dev/null | cut -f1)
    
    # Update report with metrics
    jq --argjson total_items "$((total_items - 1))" \
       --argjson total_files "$total_files" \
       --argjson total_dirs "$((total_dirs - 1))" \
       --argjson total_size_kb "$total_size" \
       '.directory_metrics = {
           "total_items": $total_items,
           "total_files": $total_files,
           "total_directories": $total_dirs,
           "total_size_kb": $total_size_kb,
           "average_file_size": (if $total_files > 0 then ($total_size_kb / $total_files) else 0 end)
       }' "$report_file" > "${report_file}.tmp" && mv "${report_file}.tmp" "$report_file"
    
    # Perform analysis based on scan level
    case "$scan_level" in
        "quick_scan")
            perform_quick_scan "$target_path" "$report_file"
            ;;
        "standard_scan")
            perform_standard_scan "$target_path" "$report_file"
            ;;
        "comprehensive_scan")
            perform_comprehensive_scan "$target_path" "$report_file"
            ;;
        "security_audit")
            perform_security_audit "$target_path" "$report_file"
            ;;
        "performance_scan")
            perform_performance_scan "$target_path" "$report_file"
            ;;
        "compliance_scan")
            perform_compliance_scan "$target_path" "$report_file"
            ;;
    esac
    
    log_action "Directory analysis completed: $report_file"
    echo "$report_file"
}

# Quick scan implementation
perform_quick_scan() {
    local target_path="$1"
    local report_file="$2"
    
    echo "Performing quick scan of $target_path..."
    
    # Basic file listing
    local file_listing=$(ls -la "$target_path" 2>/dev/null | tail -n +2)
    
    # File type distribution
    local file_types=$(find "$target_path" -maxdepth 1 -type f -exec file {} \; 2>/dev/null | cut -d: -f2 | sort | uniq -c | sort -nr)
    
    # Update report
    jq --arg file_listing "$file_listing" \
       --arg file_types "$file_types" \
       '.file_analysis.quick_scan = {
           "file_listing": $file_listing,
           "file_type_distribution": $file_types
       }' "$report_file" > "${report_file}.tmp" && mv "${report_file}.tmp" "$report_file"
}

# Standard scan implementation
perform_standard_scan() {
    local target_path="$1"
    local report_file="$2"
    
    echo "Performing standard scan of $target_path..."
    
    # Detailed file analysis
    local detailed_listing=$(ls -lah "$target_path" 2>/dev/null)
    local hidden_files=$(ls -la "$target_path" 2>/dev/null | grep "^\." | wc -l)
    local executable_files=$(find "$target_path" -maxdepth 1 -type f -executable 2>/dev/null | wc -l)
    
    # File size analysis
    local large_files=$(find "$target_path" -maxdepth 1 -type f -size +10M 2>/dev/null)
    local small_files=$(find "$target_path" -maxdepth 1 -type f -size -1k 2>/dev/null | wc -l)
    
    # File age analysis
    local recent_files=$(find "$target_path" -maxdepth 1 -type f -mtime -7 2>/dev/null | wc -l)
    local old_files=$(find "$target_path" -maxdepth 1 -type f -mtime +365 2>/dev/null | wc -l)
    
    # Update report
    jq --arg detailed_listing "$detailed_listing" \
       --argjson hidden_files "$((hidden_files - 2))" \
       --argjson executable_files "$executable_files" \
       --arg large_files "$large_files" \
       --argjson small_files "$small_files" \
       --argjson recent_files "$recent_files" \
       --argjson old_files "$old_files" \
       '.file_analysis.standard_scan = {
           "detailed_listing": $detailed_listing,
           "hidden_files_count": $hidden_files,
           "executable_files_count": $executable_files,
           "large_files": $large_files,
           "small_files_count": $small_files,
           "recent_files_count": $recent_files,
           "old_files_count": $old_files
       }' "$report_file" > "${report_file}.tmp" && mv "${report_file}.tmp" "$report_file"
}

# Comprehensive scan implementation
perform_comprehensive_scan() {
    local target_path="$1"
    local report_file="$2"
    
    echo "Performing comprehensive scan of $target_path..."
    
    # Recursive analysis
    local total_recursive_items=$(find "$target_path" 2>/dev/null | wc -l)
    local max_depth=$(find "$target_path" -type d 2>/dev/null | awk -F/ '{print NF}' | sort -n | tail -1)
    
    # File extension analysis
    local extensions=$(find "$target_path" -type f 2>/dev/null | grep '\.' | rev | cut -d. -f1 | rev | sort | uniq -c | sort -nr)
    
    # Duplicate file detection
    local duplicates=$(find "$target_path" -type f 2>/dev/null -exec md5 {} \; | sort | uniq -d -w 32)
    
    # Symbolic link analysis
    local symlinks=$(find "$target_path" -type l 2>/dev/null)
    
    # Update report
    jq --argjson total_recursive "$((total_recursive_items - 1))" \
       --argjson max_depth "$((max_depth - $(echo "$target_path" | tr -cd '/' | wc -c) - 1))" \
       --arg extensions "$extensions" \
       --arg duplicates "$duplicates" \
       --arg symlinks "$symlinks" \
       '.file_analysis.comprehensive_scan = {
           "total_recursive_items": $total_recursive,
           "maximum_depth": $max_depth,
           "file_extensions": $extensions,
           "duplicate_files": $duplicates,
           "symbolic_links": $symlinks
       }' "$report_file" > "${report_file}.tmp" && mv "${report_file}.tmp" "$report_file"
}

# Security audit implementation
perform_security_audit() {
    local target_path="$1"
    local report_file="$2"
    
    echo "Performing security audit of $target_path..."
    
    # Permission analysis
    local world_writable=$(find "$target_path" -type f -perm -002 2>/dev/null)
    local world_readable=$(find "$target_path" -type f -perm -004 2>/dev/null | wc -l)
    local setuid_files=$(find "$target_path" -type f -perm -4000 2>/dev/null)
    local setgid_files=$(find "$target_path" -type f -perm -2000 2>/dev/null)
    
    # Ownership analysis
    local root_owned=$(find "$target_path" -user root 2>/dev/null | wc -l)
    local no_owner=$(find "$target_path" -nouser 2>/dev/null)
    local no_group=$(find "$target_path" -nogroup 2>/dev/null)
    
    # Sensitive file patterns
    local sensitive_patterns="password|secret|key|token|credential|private"
    local sensitive_files=$(find "$target_path" -type f 2>/dev/null | xargs grep -l -i "$sensitive_patterns" 2>/dev/null)
    
    # Update report
    jq --arg world_writable "$world_writable" \
       --argjson world_readable "$world_readable" \
       --arg setuid_files "$setuid_files" \
       --arg setgid_files "$setgid_files" \
       --argjson root_owned "$root_owned" \
       --arg no_owner "$no_owner" \
       --arg no_group "$no_group" \
       --arg sensitive_files "$sensitive_files" \
       '.security_findings = {
           "world_writable_files": $world_writable,
           "world_readable_count": $world_readable,
           "setuid_files": $setuid_files,
           "setgid_files": $setgid_files,
           "root_owned_count": $root_owned,
           "orphaned_files": $no_owner,
           "orphaned_groups": $no_group,
           "sensitive_files": $sensitive_files
       }' "$report_file" > "${report_file}.tmp" && mv "${report_file}.tmp" "$report_file"
}

# Performance scan implementation
perform_performance_scan() {
    local target_path="$1"
    local report_file="$2"
    
    echo "Performing performance scan of $target_path..."
    
    # Large file analysis
    local files_over_100mb=$(find "$target_path" -type f -size +100M 2>/dev/null)
    local files_over_1gb=$(find "$target_path" -type f -size +1G 2>/dev/null | wc -l)
    
    # Cache and temporary file analysis
    local cache_files=$(find "$target_path" -name "*cache*" -o -name "*.tmp" -o -name "*.temp" 2>/dev/null)
    local log_files=$(find "$target_path" -name "*.log" 2>/dev/null)
    
    # File access patterns
    local recently_accessed=$(find "$target_path" -type f -atime -1 2>/dev/null | wc -l)
    local never_accessed=$(find "$target_path" -type f -atime +365 2>/dev/null | wc -l)
    
    # Update report
    jq --arg files_over_100mb "$files_over_100mb" \
       --argjson files_over_1gb "$files_over_1gb" \
       --arg cache_files "$cache_files" \
       --arg log_files "$log_files" \
       --argjson recently_accessed "$recently_accessed" \
       --argjson never_accessed "$never_accessed" \
       '.file_analysis.performance_scan = {
           "large_files_100mb": $files_over_100mb,
           "large_files_1gb_count": $files_over_1gb,
           "cache_temp_files": $cache_files,
           "log_files": $log_files,
           "recently_accessed_count": $recently_accessed,
           "stale_files_count": $never_accessed
       }' "$report_file" > "${report_file}.tmp" && mv "${report_file}.tmp" "$report_file"
}

# Compliance scan implementation
perform_compliance_scan() {
    local target_path="$1"
    local report_file="$2"
    
    echo "Performing compliance scan of $target_path..."
    
    # Data classification patterns
    local pii_patterns="ssn|social.security|credit.card|phone|email|address"
    local financial_patterns="account.number|routing|swift|iban|tax.id"
    local health_patterns="medical|patient|diagnosis|prescription|hipaa"
    
    local pii_files=$(find "$target_path" -type f 2>/dev/null | xargs grep -l -i "$pii_patterns" 2>/dev/null)
    local financial_files=$(find "$target_path" -type f 2>/dev/null | xargs grep -l -i "$financial_patterns" 2>/dev/null)
    local health_files=$(find "$target_path" -type f 2>/dev/null | xargs grep -l -i "$health_patterns" 2>/dev/null)
    
    # Retention analysis
    local files_over_7_years=$(find "$target_path" -type f -mtime +2555 2>/dev/null | wc -l)
    local files_over_3_years=$(find "$target_path" -type f -mtime +1095 2>/dev/null | wc -l)
    
    # Update report
    jq --arg pii_files "$pii_files" \
       --arg financial_files "$financial_files" \
       --arg health_files "$health_files" \
       --argjson files_over_7_years "$files_over_7_years" \
       --argjson files_over_3_years "$files_over_3_years" \
       '.file_analysis.compliance_scan = {
           "pii_files": $pii_files,
           "financial_files": $financial_files,
           "health_files": $health_files,
           "retention_7_years": $files_over_7_years,
           "retention_3_years": $files_over_3_years
       }' "$report_file" > "${report_file}.tmp" && mv "${report_file}.tmp" "$report_file"
}

# Fleet directory management
manage_fleet_directories() {
    local action="$1"
    local target_pattern="$2"
    local scan_level="${3:-standard_scan}"
    
    log_action "Fleet directory management: $action on $target_pattern"
    
    case "$action" in
        "scan_all")
            for category in "${!DIRECTORY_CATEGORIES[@]}"; do
                IFS=',' read -ra PATHS <<< "${DIRECTORY_CATEGORIES[$category]}"
                for path in "${PATHS[@]}"; do
                    if [[ -d "$path" ]]; then
                        analyze_directory "$path" "$scan_level" "$category"
                    fi
                done
            done
            ;;
        "scan_category")
            if [[ -n "${DIRECTORY_CATEGORIES[$target_pattern]}" ]]; then
                IFS=',' read -ra PATHS <<< "${DIRECTORY_CATEGORIES[$target_pattern]}"
                for path in "${PATHS[@]}"; do
                    if [[ -d "$path" ]]; then
                        analyze_directory "$path" "$scan_level" "$target_pattern"
                    fi
                done
            fi
            ;;
        "scan_path")
            if [[ -d "$target_pattern" ]]; then
                analyze_directory "$target_pattern" "$scan_level" "custom"
            fi
            ;;
        "generate_report")
            generate_fleet_report
            ;;
    esac
}

# Generate comprehensive fleet report
generate_fleet_report() {
    local fleet_report="$REPORT_DIR/fleet_directory_report_$(date +%Y%m%d_%H%M%S).json"
    
    echo "Generating fleet directory report..."
    
    # Combine all individual reports
    local reports=($(find "$REPORT_DIR" -name "directory_analysis_*.json" -mtime -1))
    
    cat > "$fleet_report" << EOF
{
    "fleet_report": {
        "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
        "hostname": "$(hostname)",
        "total_reports": ${#reports[@]},
        "reports": []
    }
}
EOF
    
    for report in "${reports[@]}"; do
        if [[ -f "$report" ]]; then
            jq --slurpfile new_report "$report" '.fleet_report.reports += $new_report' "$fleet_report" > "${fleet_report}.tmp" && mv "${fleet_report}.tmp" "$fleet_report"
        fi
    done
    
    log_action "Fleet report generated: $fleet_report"
    echo "$fleet_report"
}

# Main execution function
main() {
    local action="${1:-analyze}"
    local target="${2:-/Users}"
    local scan_level="${3:-standard_scan}"
    
    log_action "=== Roundfleet Directory Management Started ==="
    log_action "Action: $action, Target: $target, Scan Level: $scan_level"
    
    case "$action" in
        "analyze")
            analyze_directory "$target" "$scan_level"
            ;;
        "fleet-scan")
            manage_fleet_directories "scan_all" "" "$scan_level"
            ;;
        "category-scan")
            manage_fleet_directories "scan_category" "$target" "$scan_level"
            ;;
        "fleet-report")
            manage_fleet_directories "generate_report"
            ;;
        "help")
            echo "Usage: $0 [action] [target] [scan_level]"
            echo "Actions: analyze, fleet-scan, category-scan, fleet-report, help"
            echo "Scan Levels: quick_scan, standard_scan, comprehensive_scan, security_audit, performance_scan, compliance_scan"
            echo "Categories: ${!DIRECTORY_CATEGORIES[*]}"
            ;;
        *)
            log_action "ERROR: Unknown action: $action"
            exit 1
            ;;
    esac
    
    log_action "=== Directory management completed ==="
}

# Execute main function
main "$@"

Directory Listing Best Practices

Handle Spaces in File Names

# Safe handling of file names with spaces
while IFS= read -r -d '' file; do
    echo "Processing: $file"
    # Your processing logic here
done < <(find "/path/with spaces" -type f -print0)

Filter by File Types

# List only image files
ls -la /Users/QA/Desktop/Wallpapers/*.{jpg,jpeg,png,gif,bmp} 2>/dev/null

# List only text files
find /path/to/directory -name "*.txt" -o -name "*.md" -o -name "*.doc"

Performance Considerations

# For large directories, use find with limited depth
find /large/directory -maxdepth 2 -type f | head -100

# Use xargs for processing many files
find /directory -name "*.log" | xargs wc -l

Common Directory Operations

Directory Size Analysis

#!/bin/bash

# Analyze directory sizes
analyze_directory_sizes() {
    local base_path="$1"
    
    echo "Directory size analysis for: $base_path"
    echo "=================================="
    
    # Top 10 largest subdirectories
    du -h "$base_path"/* 2>/dev/null | sort -hr | head -10
    
    echo -e "\nTotal directory size:"
    du -sh "$base_path"
}

analyze_directory_sizes "/Users"

File Count by Type

#!/bin/bash

# Count files by extension
count_files_by_type() {
    local directory="$1"
    
    echo "File type distribution in: $directory"
    find "$directory" -type f | grep '\.' | rev | cut -d. -f1 | rev | sort | uniq -c | sort -nr
}

count_files_by_type "/Users/QA/Desktop/Wallpapers"

Important Notes

  • Use quotes around paths containing spaces: ls "/path with spaces"
  • Escape special characters with backslash when not using quotes
  • Check permissions before accessing system directories
  • Test scripts on sample directories before production use
  • Monitor performance when analyzing large directory structures
  • Consider security when listing sensitive directories in logs

Device Naming and Identity Management on macOS

Implement enterprise-grade device naming and identity management across your Roundfleet deployment with standardized naming conventions, automated provisioning, and comprehensive identity validation. This tutorial provides solutions for maintaining consistent device identification and network presence.

Understanding macOS Device Identity

macOS devices have three distinct naming components that affect identification and network behavior:

  • Computer Name - User-friendly name displayed in Sharing preferences and Finder
  • Local Host Name - Network identifier with ".local" suffix for Bonjour/mDNS
  • Hostname - Primary network hostname used in terminal and network services
  • NetBIOS Name - Windows network compatibility identifier

Basic Device Naming Operations

Change Computer Name

#!/bin/bash

# Set computer name
scutil --set ComputerName "$ComputerName"

echo "Computer name set to: $ComputerName"

Change Local Host Name

#!/bin/bash

# Set local hostname for Bonjour/mDNS discovery
scutil --set LocalHostName "$LocalHostName"

echo "Local hostname set to: $LocalHostName"

Change Hostname

#!/bin/bash

# Set primary hostname for network services
# Example: Your-iMac.domain.com
scutil --set HostName "$HostName"

echo "Hostname set to: $HostName"

Flush DNS Cache

#!/bin/bash

# Flush DNS cache after name changes
sudo dscacheutil --flushcache

echo "DNS cache flushed successfully"

Enterprise Naming Standards

Standardized Naming Convention Script

#!/bin/bash

# Roundfleet Enterprise Device Naming Tool
# Implements standardized naming conventions across fleet

# Configuration
CONFIG_FILE="/etc/roundfleet/naming_policy.conf"
LOG_FILE="/var/log/roundfleet_naming.log"
REPORT_DIR="/var/log/roundfleet_reports"

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

# Default naming policy
cat > "$CONFIG_FILE" 2>/dev/null << 'EOF' || true
# Roundfleet Device Naming Policy
# Version: 2.0

# Naming Convention Format
# Pattern: {PREFIX}-{LOCATION}-{TYPE}-{SEQUENCE}
# Example: MF-NYC-MBP-001

# Organization Settings
ORG_PREFIX="MF"
DOMAIN_SUFFIX="roundfleet.local"
ENABLE_AUTO_NAMING=true
VALIDATE_NAMES=true

# Location Codes
LOCATION_CODES="NYC,SF,LA,CHI,BOS,SEA,ATL,MIA"
DEFAULT_LOCATION="NYC"

# Device Type Mapping
# Format: MODEL_IDENTIFIER:SHORT_CODE
DEVICE_TYPES=(
    "MacBookPro:MBP"
    "MacBookAir:MBA"
    "iMac:iMac"
    "iMacPro:iMP"
    "MacPro:MP"
    "Macmini:MM"
    "MacStudio:MS"
)

# Network Settings
ENABLE_NETBIOS=true
SYNC_ALL_NAMES=true
FLUSH_DNS_AFTER_CHANGE=true
EOF

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

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

# Get device model information
get_device_model() {
    local model_identifier
    model_identifier=$(system_profiler SPHardwareDataType | grep "Model Identifier" | awk -F: '{print $2}' | xargs)
    
    # Map model to device type
    for mapping in "${DEVICE_TYPES[@]}"; do
        local model_pattern="${mapping%:*}"
        local type_code="${mapping#*:}"
        
        if [[ "$model_identifier" == *"$model_pattern"* ]]; then
            echo "$type_code"
            return 0
        fi
    done
    
    # Default fallback
    echo "MAC"
}

# Get location from user input or configuration
get_location_code() {
    local location="$1"
    
    if [[ -z "$location" ]]; then
        location="$DEFAULT_LOCATION"
    fi
    
    # Validate location code
    if [[ ",$LOCATION_CODES," == *",$location,"* ]]; then
        echo "$location"
    else
        echo "$DEFAULT_LOCATION"
        log_action "WARNING: Invalid location '$location', using default '$DEFAULT_LOCATION'"
    fi
}

# Generate sequence number
generate_sequence() {
    local prefix="$1"
    local sequence_file="/var/lib/roundfleet/sequences/${prefix}.seq"
    
    mkdir -p "$(dirname "$sequence_file")"
    
    if [[ -f "$sequence_file" ]]; then
        local current_seq
        current_seq=$(cat "$sequence_file")
        ((current_seq++))
    else
        current_seq=1
    fi
    
    printf "%03d" "$current_seq" > "$sequence_file"
    printf "%03d" "$current_seq"
}

# Generate standardized device name
generate_device_name() {
    local location="$1"
    local custom_suffix="$2"
    
    local device_type
    device_type=$(get_device_model)
    
    local location_code
    location_code=$(get_location_code "$location")
    
    local base_prefix="${ORG_PREFIX}-${location_code}-${device_type}"
    
    if [[ -n "$custom_suffix" ]]; then
        echo "${base_prefix}-${custom_suffix}"
    else
        local sequence
        sequence=$(generate_sequence "$base_prefix")
        echo "${base_prefix}-${sequence}"
    fi
}

# Validate naming compliance
validate_device_name() {
    local name="$1"
    local errors=()
    
    # Length validation
    if [[ ${#name} -gt 15 ]]; then
        errors+=("Name too long (max 15 characters for NetBIOS compatibility)")
    fi
    
    # Character validation
    if [[ "$name" =~ [^A-Za-z0-9\-] ]]; then
        errors+=("Invalid characters (only alphanumeric and hyphens allowed)")
    fi
    
    # Format validation
    if [[ ! "$name" =~ ^[A-Z]{2,4}-[A-Z]{2,4}-[A-Z]{2,4}-[0-9]{3}$ ]] && [[ "$VALIDATE_NAMES" == "true" ]]; then
        errors+=("Name doesn't match organization standard format")
    fi
    
    if [[ ${#errors[@]} -eq 0 ]]; then
        return 0
    else
        printf '%s\n' "${errors[@]}"
        return 1
    fi
}

# Apply device names with validation
apply_device_names() {
    local computer_name="$1"
    local hostname="$2"
    local local_hostname="$3"
    
    echo "=== Applying Device Names ==="
    
    # Validate all names
    local validation_errors=0
    
    if ! validate_device_name "$computer_name"; then
        echo "❌ Computer name validation failed"
        ((validation_errors++))
    fi
    
    if [[ -n "$hostname" ]] && ! validate_device_name "${hostname%%.*}"; then
        echo "❌ Hostname validation failed"
        ((validation_errors++))
    fi
    
    if [[ -n "$local_hostname" ]] && ! validate_device_name "$local_hostname"; then
        echo "❌ Local hostname validation failed"
        ((validation_errors++))
    fi
    
    if [[ $validation_errors -gt 0 ]] && [[ "$VALIDATE_NAMES" == "true" ]]; then
        echo "âš ī¸  Name validation failed, aborting changes"
        return 1
    fi
    
    # Apply computer name
    if [[ -n "$computer_name" ]]; then
        scutil --set ComputerName "$computer_name"
        echo "✅ Computer name: $computer_name"
        log_action "Computer name changed to: $computer_name"
    fi
    
    # Apply hostname
    if [[ -n "$hostname" ]]; then
        scutil --set HostName "$hostname"
        echo "✅ Hostname: $hostname"
        log_action "Hostname changed to: $hostname"
    fi
    
    # Apply local hostname
    if [[ -n "$local_hostname" ]]; then
        scutil --set LocalHostName "$local_hostname"
        echo "✅ Local hostname: $local_hostname"
        log_action "Local hostname changed to: $local_hostname"
    fi
    
    # Apply NetBIOS name if enabled
    if [[ "$ENABLE_NETBIOS" == "true" ]] && [[ -n "$computer_name" ]]; then
        defaults write /Library/Preferences/SystemConfiguration/com.apple.smb.server NetBIOSName "$computer_name"
        echo "✅ NetBIOS name: $computer_name"
        log_action "NetBIOS name changed to: $computer_name"
    fi
    
    # Flush DNS cache
    if [[ "$FLUSH_DNS_AFTER_CHANGE" == "true" ]]; then
        sudo dscacheutil --flushcache
        echo "✅ DNS cache flushed"
        log_action "DNS cache flushed after name changes"
    fi
    
    return 0
}

# Auto-generate and apply names
auto_provision_device() {
    local location="$1"
    local custom_suffix="$2"
    
    echo "=== Auto-Provisioning Device Names ==="
    
    if [[ "$ENABLE_AUTO_NAMING" != "true" ]]; then
        echo "❌ Auto-naming disabled in policy"
        return 1
    fi
    
    # Generate base name
    local base_name
    base_name=$(generate_device_name "$location" "$custom_suffix")
    
    # Create all naming variants
    local computer_name="$base_name"
    local local_hostname="$base_name"
    local hostname="${base_name}.${DOMAIN_SUFFIX}"
    
    echo "Generated names:"
    echo "  Computer Name: $computer_name"
    echo "  Local Hostname: $local_hostname"
    echo "  Hostname: $hostname"
    echo ""
    
    # Apply names
    apply_device_names "$computer_name" "$hostname" "$local_hostname"
}

# Get current device identity
get_current_identity() {
    echo "=== Current Device Identity ==="
    
    local computer_name
    computer_name=$(scutil --get ComputerName 2>/dev/null || echo "Not Set")
    
    local hostname
    hostname=$(scutil --get HostName 2>/dev/null || echo "Not Set")
    
    local local_hostname
    local_hostname=$(scutil --get LocalHostName 2>/dev/null || echo "Not Set")
    
    local netbios_name
    netbios_name=$(defaults read /Library/Preferences/SystemConfiguration/com.apple.smb.server NetBIOSName 2>/dev/null || echo "Not Set")
    
    echo "Computer Name: $computer_name"
    echo "Hostname: $hostname"
    echo "Local Hostname: $local_hostname"
    echo "NetBIOS Name: $netbios_name"
    echo "Serial Number: $(system_profiler SPHardwareDataType | grep "Serial Number" | awk -F: '{print $2}' | xargs)"
    echo "Model: $(system_profiler SPHardwareDataType | grep "Model Identifier" | awk -F: '{print $2}' | xargs)"
}

# Generate compliance report
generate_naming_report() {
    local report_file="$REPORT_DIR/device_naming_$(date +%Y%m%d_%H%M%S).json"
    
    echo "=== Generating Naming Compliance Report ==="
    
    local computer_name hostname local_hostname netbios_name
    computer_name=$(scutil --get ComputerName 2>/dev/null || echo "")
    hostname=$(scutil --get HostName 2>/dev/null || echo "")
    local_hostname=$(scutil --get LocalHostName 2>/dev/null || echo "")
    netbios_name=$(defaults read /Library/Preferences/SystemConfiguration/com.apple.smb.server NetBIOSName 2>/dev/null || echo "")
    
    # Check compliance
    local computer_compliant="false"
    local hostname_compliant="false"
    local naming_compliant="false"
    
    if validate_device_name "$computer_name" >/dev/null 2>&1; then
        computer_compliant="true"
    fi
    
    if [[ -n "$hostname" ]] && validate_device_name "${hostname%%.*}" >/dev/null 2>&1; then
        hostname_compliant="true"
    fi
    
    if [[ "$computer_compliant" == "true" ]] && [[ "$hostname_compliant" == "true" ]]; then
        naming_compliant="true"
    fi
    
    # Create JSON report
    cat > "$report_file" << EOF
{
  "report_type": "device_naming_compliance",
  "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
  "device_info": {
    "hostname": "$(hostname)",
    "serial_number": "$(system_profiler SPHardwareDataType | grep "Serial Number" | awk -F: '{print $2}' | xargs)",
    "model_identifier": "$(system_profiler SPHardwareDataType | grep "Model Identifier" | awk -F: '{print $2}' | xargs)",
    "macos_version": "$(sw_vers -productVersion)"
  },
  "current_names": {
    "computer_name": "$computer_name",
    "hostname": "$hostname",
    "local_hostname": "$local_hostname",
    "netbios_name": "$netbios_name"
  },
  "compliance": {
    "computer_name_compliant": $computer_compliant,
    "hostname_compliant": $hostname_compliant,
    "overall_compliant": $naming_compliant,
    "policy_version": "2.0"
  },
  "policy_settings": {
    "org_prefix": "$ORG_PREFIX",
    "domain_suffix": "$DOMAIN_SUFFIX",
    "auto_naming_enabled": $ENABLE_AUTO_NAMING,
    "validation_enabled": $VALIDATE_NAMES
  }
}
EOF
    
    echo "Naming report saved to: $report_file"
    log_action "Device naming report generated: $report_file"
}

# Main function with argument handling
main() {
    log_action "=== Roundfleet Device Naming Tool Started ==="
    
    case "${1:-status}" in
        "auto-provision")
            auto_provision_device "$2" "$3"
            ;;
        "set-names")
            apply_device_names "$2" "$3" "$4"
            ;;
        "validate")
            get_current_identity
            echo ""
            if validate_device_name "$2" 2>/dev/null; then
                echo "✅ Name '$2' is compliant"
            else
                echo "❌ Name '$2' validation failed:"
                validate_device_name "$2"
            fi
            ;;
        "report")
            generate_naming_report
            ;;
        "status"|*)
            get_current_identity
            ;;
    esac
    
    log_action "=== Device naming operation completed ==="
}

# Execute main function
main "$@"

Advanced Identity Management

Network Identity Synchronization

#!/bin/bash

# Synchronize all naming components for consistency
sync_network_identity() {
    echo "=== Network Identity Synchronization ==="
    
    # Get current computer name as source
    local source_name
    source_name=$(scutil --get ComputerName 2>/dev/null)
    
    if [[ -z "$source_name" ]]; then
        echo "❌ No computer name set, cannot synchronize"
        return 1
    fi
    
    # Generate consistent names
    local clean_name
    clean_name=$(echo "$source_name" | tr '[:upper:]' '[:lower:]' | tr ' ' '-')
    
    local local_hostname="$clean_name"
    local hostname="${clean_name}.local"
    
    echo "Synchronizing identity from: $source_name"
    echo "Local Hostname: $local_hostname"
    echo "Hostname: $hostname"
    
    # Apply synchronized names
    scutil --set LocalHostName "$local_hostname"
    scutil --set HostName "$hostname"
    
    # Update NetBIOS
    defaults write /Library/Preferences/SystemConfiguration/com.apple.smb.server NetBIOSName "$source_name"
    
    # Flush DNS cache
    sudo dscacheutil --flushcache
    
    echo "✅ Network identity synchronized"
}

sync_network_identity

Bulk Device Provisioning

#!/bin/bash

# Bulk device naming for fleet deployment
bulk_provision_devices() {
    local csv_file="$1"
    local report_file="/tmp/bulk_naming_$(date +%Y%m%d_%H%M%S).csv"
    
    echo "=== Bulk Device Provisioning ==="
    echo "Serial,Computer_Name,Hostname,Status,Timestamp" > "$report_file"
    
    # Read CSV file with device assignments
    # Format: Serial,Location,CustomSuffix
    while IFS=',' read -r serial location suffix; do
        # Skip header
        [[ "$serial" == "Serial" ]] && continue
        
        local current_serial
        current_serial=$(system_profiler SPHardwareDataType | grep "Serial Number" | awk -F: '{print $2}' | xargs)
        
        if [[ "$current_serial" == "$serial" ]]; then
            echo "Processing device: $serial"
            
            # Generate names for this device
            local device_name
            device_name=$(generate_device_name "$location" "$suffix")
            
            local computer_name="$device_name"
            local hostname="${device_name}.roundfleet.local"
            
            # Apply names
            if apply_device_names "$computer_name" "$hostname" "$device_name"; then
                echo "$serial,$computer_name,$hostname,SUCCESS,$(date)" >> "$report_file"
                echo "✅ Successfully provisioned: $computer_name"
            else
                echo "$serial,$computer_name,$hostname,FAILED,$(date)" >> "$report_file"
                echo "❌ Failed to provision: $computer_name"
            fi
            
            break
        fi
    done < "$csv_file"
    
    echo "Bulk provisioning report: $report_file"
}

# Example usage:
# bulk_provision_devices "/path/to/device_assignments.csv"

Identity Validation and Compliance

Comprehensive Validation Script

#!/bin/bash

# Complete device identity validation
validate_device_identity() {
    echo "=== Device Identity Validation ==="
    
    local issues=0
    local warnings=0
    
    # Get all current names
    local computer_name hostname local_hostname
    computer_name=$(scutil --get ComputerName 2>/dev/null)
    hostname=$(scutil --get HostName 2>/dev/null)
    local_hostname=$(scutil --get LocalHostName 2>/dev/null)
    
    # Computer name validation
    if [[ -z "$computer_name" ]]; then
        echo "❌ Computer name not set"
        ((issues++))
    elif ! validate_device_name "$computer_name" >/dev/null 2>&1; then
        echo "âš ī¸  Computer name format non-compliant: $computer_name"
        ((warnings++))
    else
        echo "✅ Computer name compliant: $computer_name"
    fi
    
    # Hostname validation
    if [[ -z "$hostname" ]]; then
        echo "âš ī¸  Hostname not set"
        ((warnings++))
    elif ! validate_device_name "${hostname%%.*}" >/dev/null 2>&1; then
        echo "âš ī¸  Hostname format non-compliant: $hostname"
        ((warnings++))
    else
        echo "✅ Hostname compliant: $hostname"
    fi
    
    # Local hostname validation
    if [[ -z "$local_hostname" ]]; then
        echo "âš ī¸  Local hostname not set"
        ((warnings++))
    elif ! validate_device_name "$local_hostname" >/dev/null 2>&1; then
        echo "âš ī¸  Local hostname format non-compliant: $local_hostname"
        ((warnings++))
    else
        echo "✅ Local hostname compliant: $local_hostname"
    fi
    
    # Consistency check
    if [[ -n "$computer_name" && -n "$local_hostname" ]]; then
        local expected_local
        expected_local=$(echo "$computer_name" | tr '[:upper:]' '[:lower:]' | tr ' ' '-')
        
        if [[ "$local_hostname" != "$expected_local" ]]; then
            echo "âš ī¸  Names not synchronized (Computer: $computer_name, Local: $local_hostname)"
            ((warnings++))
        fi
    fi
    
    # Network connectivity validation
    echo ""
    echo "=== Network Identity Testing ==="
    
    # Test Bonjour resolution
    if ping -c 1 "${local_hostname}.local" >/dev/null 2>&1; then
        echo "✅ Bonjour resolution working"
    else
        echo "âš ī¸  Bonjour resolution failed"
        ((warnings++))
    fi
    
    # Test hostname resolution
    if [[ -n "$hostname" ]] && ping -c 1 "$hostname" >/dev/null 2>&1; then
        echo "✅ Hostname resolution working"
    elif [[ -n "$hostname" ]]; then
        echo "âš ī¸  Hostname resolution failed"
        ((warnings++))
    fi
    
    # Summary
    echo ""
    echo "=== Validation Summary ==="
    echo "Issues: $issues"
    echo "Warnings: $warnings"
    
    if [[ $issues -eq 0 && $warnings -eq 0 ]]; then
        echo "✅ Device identity fully compliant"
        return 0
    elif [[ $issues -eq 0 ]]; then
        echo "âš ī¸  Device identity has warnings but is functional"
        return 1
    else
        echo "❌ Device identity has critical issues"
        return 2
    fi
}

validate_device_identity

Network Service Integration

DNS and Directory Services

#!/bin/bash

# Update DNS and directory service entries
update_network_services() {
    echo "=== Network Services Update ==="
    
    # Get current names
    local computer_name hostname
    computer_name=$(scutil --get ComputerName 2>/dev/null)
    hostname=$(scutil --get HostName 2>/dev/null)
    
    # Update mDNSResponder
    echo "Restarting mDNSResponder..."
    sudo launchctl kickstart -k system/com.apple.mDNSResponder
    
    # Update NetBIOS registration
    if [[ -n "$computer_name" ]]; then
        echo "Updating NetBIOS registration..."
        defaults write /Library/Preferences/SystemConfiguration/com.apple.smb.server NetBIOSName "$computer_name"
        sudo launchctl kickstart -k system/com.apple.smbd
    fi
    
    # Flush all caches
    echo "Flushing system caches..."
    sudo dscacheutil --flushcache
    sudo killall -HUP mDNSResponder
    
    # Update Open Directory if bound
    if dsconfigldap -v >/dev/null 2>&1; then
        echo "Updating Open Directory registration..."
        sudo dsconfigldap -f
    fi
    
    echo "✅ Network services updated"
}

update_network_services

Important Configuration Notes

System Configuration Utility (scutil)

The scutil command manages macOS system configuration:

  • ComputerName - User-visible device name
  • HostName - Primary network hostname
  • LocalHostName - Bonjour/mDNS identifier
  • NetBIOSName - Windows network compatibility

Best Practices for Enterprise

  1. Standardized Naming Convention

    • Use consistent format: ORG-LOCATION-TYPE-SEQUENCE
    • Keep names under 15 characters for NetBIOS compatibility
    • Avoid special characters and spaces
  2. Network Considerations

    • Ensure unique names across network segments
    • Test DNS resolution after changes
    • Coordinate with network administrators
  3. Fleet Management

    • Implement automated provisioning
    • Maintain naming databases
    • Regular compliance auditing
    • Backup configuration before changes
  4. Security Implications

    • Device names may reveal organizational structure
    • Consider privacy requirements
    • Implement access controls for naming changes

Troubleshooting Common Issues

  • Name changes not taking effect - Restart networking services or reboot
  • Bonjour conflicts - Ensure unique LocalHostName values
  • DNS resolution issues - Flush cache and restart mDNSResponder
  • Windows network problems - Verify NetBIOS name configuration

Remember to test naming changes thoroughly and coordinate with network administrators before implementing across your Roundfleet deployment.

Device Location Tracking on macOS

Track and monitor the geographical location of your Roundfleet devices using IP address geolocation services. This tutorial covers location discovery, security monitoring, geofencing policies, and compliance reporting for enterprise device management.

Understanding IP-Based Location Tracking

IP geolocation provides valuable information about device location and network environment, essential for enterprise security and compliance. This method tracks devices based on their internet connection rather than GPS, making it suitable for fleet management and security monitoring.

Key Information Retrieved

  • IP Address - Public IP address of the device
  • Geographic Location - City, region, and country
  • Coordinates - Latitude and longitude for mapping
  • Network Provider - ISP or organization details
  • Timezone - Local timezone information
  • Security Context - Network environment assessment

Basic Location Discovery

Simple IP Geolocation

#!/bin/bash

# Basic location lookup using IP address
curl -s https://ipinfo.io

echo "Location information retrieved successfully"

Enhanced Location Query

#!/bin/bash

# Enhanced location discovery with formatted output
get_device_location() {
    echo "📍 Retrieving device location information..."
    
    # Query location data
    local location_data
    location_data=$(curl -s https://ipinfo.io)
    
    if [[ $? -eq 0 && -n "$location_data" ]]; then
        echo "✅ Location data retrieved successfully:"
        echo "$location_data" | jq '.' 2>/dev/null || echo "$location_data"
    else
        echo "❌ Failed to retrieve location information"
        return 1
    fi
}

# Execute location discovery
get_device_location

Structured Location Information

#!/bin/bash

# Parse and display structured location information
parse_location_data() {
    echo "🌍 Device Location Analysis"
    echo "=========================="
    
    # Get location data
    local location_json
    location_json=$(curl -s https://ipinfo.io)
    
    if [[ $? -ne 0 ]]; then
        echo "❌ Failed to retrieve location data"
        return 1
    fi
    
    # Parse individual fields
    local ip city region country loc org timezone
    ip=$(echo "$location_json" | jq -r '.ip // "Unknown"')
    city=$(echo "$location_json" | jq -r '.city // "Unknown"')
    region=$(echo "$location_json" | jq -r '.region // "Unknown"')
    country=$(echo "$location_json" | jq -r '.country // "Unknown"')
    loc=$(echo "$location_json" | jq -r '.loc // "Unknown"')
    org=$(echo "$location_json" | jq -r '.org // "Unknown"')
    timezone=$(echo "$location_json" | jq -r '.timezone // "Unknown"')
    
    # Display formatted information
    echo "🔗 IP Address: $ip"
    echo "đŸ™ī¸  City: $city"
    echo "đŸ—ēī¸  Region: $region"
    echo "🌎 Country: $country"
    echo "📍 Coordinates: $loc"
    echo "đŸĸ Organization: $org"
    echo "🕐 Timezone: $timezone"
    
    # Additional security information
    echo ""
    echo "🔒 Security Assessment:"
    if [[ "$org" == *"VPN"* ]] || [[ "$org" == *"Proxy"* ]]; then
        echo "  âš ī¸  Potential VPN/Proxy detected"
    else
        echo "  ✅ Direct internet connection"
    fi
}

# Execute location parsing
parse_location_data

Advanced Location Tracking

Multi-Source Location Verification

#!/bin/bash

# Verify location using multiple geolocation services
verify_location_multi_source() {
    echo "🔍 Multi-source location verification..."
    
    # Service 1: ipinfo.io
    echo "Checking ipinfo.io..."
    local ipinfo_data
    ipinfo_data=$(curl -s https://ipinfo.io)
    
    # Service 2: ipapi.co (alternative)
    echo "Checking ipapi.co..."
    local ipapi_data
    ipapi_data=$(curl -s https://ipapi.co/json/)
    
    # Service 3: ip-api.com (backup)
    echo "Checking ip-api.com..."
    local ipapi_alt_data
    ipapi_alt_data=$(curl -s http://ip-api.com/json/)
    
    # Compare results
    echo ""
    echo "📊 Location Verification Results:"
    echo "================================="
    
    if [[ -n "$ipinfo_data" ]]; then
        echo "ipinfo.io Results:"
        echo "$ipinfo_data" | jq '.city, .region, .country' 2>/dev/null || echo "$ipinfo_data"
        echo ""
    fi
    
    if [[ -n "$ipapi_data" ]]; then
        echo "ipapi.co Results:"
        echo "$ipapi_data" | jq '.city, .region, .country_name' 2>/dev/null || echo "$ipapi_data"
        echo ""
    fi
    
    if [[ -n "$ipapi_alt_data" ]]; then
        echo "ip-api.com Results:"
        echo "$ipapi_alt_data" | jq '.city, .regionName, .country' 2>/dev/null || echo "$ipapi_alt_data"
    fi
}

# Execute multi-source verification
verify_location_multi_source

Location Change Detection

#!/bin/bash

# Monitor and detect location changes
monitor_location_changes() {
    local previous_location_file="/tmp/last_known_location.json"
    local current_location
    
    echo "📱 Monitoring device location changes..."
    
    # Get current location
    current_location=$(curl -s https://ipinfo.io)
    
    if [[ $? -ne 0 ]]; then
        echo "❌ Failed to retrieve current location"
        return 1
    fi
    
    # Check if previous location exists
    if [[ -f "$previous_location_file" ]]; then
        local previous_location
        previous_location=$(cat "$previous_location_file")
        
        # Compare locations
        local current_city previous_city
        current_city=$(echo "$current_location" | jq -r '.city // "Unknown"')
        previous_city=$(echo "$previous_location" | jq -r '.city // "Unknown"')
        
        if [[ "$current_city" != "$previous_city" ]]; then
            echo "🚨 Location change detected!"
            echo "Previous: $previous_city"
            echo "Current: $current_city"
            
            # Log the change
            echo "$(date): Location changed from $previous_city to $current_city" >> /var/log/location_changes.log
        else
            echo "✅ No location change detected"
        fi
    else
        echo "📝 First time location check - saving baseline"
    fi
    
    # Save current location as previous
    echo "$current_location" > "$previous_location_file"
}

# Execute location monitoring
monitor_location_changes

Enterprise Location Management Script

#!/bin/bash

# Roundfleet Device Location Management System
# Comprehensive location tracking and security monitoring for enterprise devices

# Configuration
LOG_FILE="/var/log/roundfleet_location.log"
CONFIG_FILE="/etc/roundfleet/location_policy.conf"
LOCATION_DB="/var/lib/roundfleet/location_history.db"
ALERT_THRESHOLD_MILES=100

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

# Setup directories and files
setup_environment() {
    sudo mkdir -p "$(dirname "$LOG_FILE")" 2>/dev/null
    sudo mkdir -p "$(dirname "$CONFIG_FILE")" 2>/dev/null
    sudo mkdir -p "$(dirname "$LOCATION_DB")" 2>/dev/null
    
    # Create location database if it doesn't exist
    if [[ ! -f "$LOCATION_DB" ]]; then
        echo "timestamp,ip,city,region,country,lat,lon,org,timezone" > "$LOCATION_DB"
    fi
}

# Load configuration
load_config() {
    if [[ -f "$CONFIG_FILE" ]]; then
        source "$CONFIG_FILE"
        log_action "Configuration loaded from $CONFIG_FILE"
    else
        # Default configuration
        LOCATION_TRACKING_ENABLED=true
        GEOFENCE_ENABLED=false
        ALLOWED_COUNTRIES=("US" "CA" "GB")
        BLOCKED_NETWORKS=("VPN" "TOR" "PROXY")
        MONITORING_INTERVAL=3600  # 1 hour
        REPORT_EMAIL="[email protected]"
        
        log_action "Using default location configuration"
    fi
}

# Get comprehensive location information
get_location_info() {
    local provider="${1:-ipinfo.io}"
    
    case "$provider" in
        "ipinfo.io")
            curl -s https://ipinfo.io
            ;;
        "ipapi.co")
            curl -s https://ipapi.co/json/
            ;;
        "ip-api.com")
            curl -s http://ip-api.com/json/
            ;;
        *)
            curl -s https://ipinfo.io
            ;;
    esac
}

# Validate location data
validate_location() {
    local location_data="$1"
    
    # Check if data is valid JSON
    if ! echo "$location_data" | jq empty 2>/dev/null; then
        log_action "Invalid location data format"
        return 1
    fi
    
    # Check for required fields
    local ip city country
    ip=$(echo "$location_data" | jq -r '.ip // empty')
    city=$(echo "$location_data" | jq -r '.city // empty')
    country=$(echo "$location_data" | jq -r '.country // empty')
    
    if [[ -z "$ip" ]] || [[ -z "$city" ]] || [[ -z "$country" ]]; then
        log_action "Missing required location fields"
        return 1
    fi
    
    return 0
}

# Store location in database
store_location() {
    local location_data="$1"
    
    if ! validate_location "$location_data"; then
        return 1
    fi
    
    # Parse location data
    local timestamp ip city region country lat lon org timezone
    timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    ip=$(echo "$location_data" | jq -r '.ip')
    city=$(echo "$location_data" | jq -r '.city')
    region=$(echo "$location_data" | jq -r '.region // ""')
    country=$(echo "$location_data" | jq -r '.country')
    lat=$(echo "$location_data" | jq -r '.loc | split(",")[0] // ""')
    lon=$(echo "$location_data" | jq -r '.loc | split(",")[1] // ""')
    org=$(echo "$location_data" | jq -r '.org // ""')
    timezone=$(echo "$location_data" | jq -r '.timezone // ""')
    
    # Append to database
    echo "$timestamp,$ip,$city,$region,$country,$lat,$lon,$org,$timezone" >> "$LOCATION_DB"
    
    log_action "Location stored: $city, $region, $country"
}

# Check geofence compliance
check_geofence() {
    local location_data="$1"
    local country
    country=$(echo "$location_data" | jq -r '.country')
    
    if [[ "$GEOFENCE_ENABLED" == "true" ]]; then
        # Check if country is in allowed list
        local allowed=false
        for allowed_country in "${ALLOWED_COUNTRIES[@]}"; do
            if [[ "$country" == "$allowed_country" ]]; then
                allowed=true
                break
            fi
        done
        
        if [[ "$allowed" == "false" ]]; then
            log_action "ALERT: Device outside allowed geofence - Country: $country"
            send_security_alert "Geofence violation" "Device detected in unauthorized country: $country"
            return 1
        fi
    fi
    
    return 0
}

# Check for suspicious networks
check_network_security() {
    local location_data="$1"
    local org
    org=$(echo "$location_data" | jq -r '.org')
    
    # Check against blocked networks
    for blocked_network in "${BLOCKED_NETWORKS[@]}"; do
        if [[ "$org" == *"$blocked_network"* ]]; then
            log_action "SECURITY ALERT: Suspicious network detected - $org"
            send_security_alert "Suspicious Network" "Device connected via potentially risky network: $org"
            return 1
        fi
    done
    
    return 0
}

# Send security alerts
send_security_alert() {
    local alert_type="$1"
    local message="$2"
    local hostname
    hostname=$(hostname)
    
    # Log the alert
    log_action "SECURITY ALERT [$alert_type]: $message"
    
    # Send email alert (if configured)
    if command -v mail >/dev/null 2>&1 && [[ -n "$REPORT_EMAIL" ]]; then
        echo "Security Alert from Roundfleet Device: $hostname
        
Alert Type: $alert_type
Message: $message
Timestamp: $(date)
Device: $hostname

This is an automated security alert from Roundfleet Location Monitoring." | \
        mail -s "Roundfleet Security Alert: $alert_type" "$REPORT_EMAIL"
    fi
}

# Calculate distance between coordinates
calculate_distance() {
    local lat1="$1" lon1="$2" lat2="$3" lon2="$4"
    
    # Use python for more accurate calculation if available
    if command -v python3 >/dev/null 2>&1; then
        python3 -c "
import math
def haversine(lat1, lon1, lat2, lon2):
    R = 3959  # Earth's radius in miles
    dlat = math.radians(float(lat2) - float(lat1))
    dlon = math.radians(float(lon2) - float(lon1))
    a = math.sin(dlat/2)**2 + math.cos(math.radians(float(lat1))) * math.cos(math.radians(float(lat2))) * math.sin(dlon/2)**2
    c = 2 * math.asin(math.sqrt(a))
    return R * c
print(f'{haversine($lat1, $lon1, $lat2, $lon2):.2f}')
"
    else
        echo "0"
    fi
}

# Monitor location changes
monitor_location() {
    log_action "Starting location monitoring..."
    
    while true; do
        # Get current location
        local current_location
        current_location=$(get_location_info)
        
        if validate_location "$current_location"; then
            # Store location
            store_location "$current_location"
            
            # Security checks
            check_geofence "$current_location"
            check_network_security "$current_location"
            
            # Check for significant movement
            check_location_change "$current_location"
        else
            log_action "Failed to retrieve valid location data"
        fi
        
        sleep "$MONITORING_INTERVAL"
    done
}

# Check for significant location changes
check_location_change() {
    local current_location="$1"
    local last_location_file="/tmp/last_location.json"
    
    if [[ -f "$last_location_file" ]]; then
        local previous_location
        previous_location=$(cat "$last_location_file")
        
        # Get coordinates
        local curr_lat curr_lon prev_lat prev_lon
        curr_lat=$(echo "$current_location" | jq -r '.loc | split(",")[0] // ""')
        curr_lon=$(echo "$current_location" | jq -r '.loc | split(",")[1] // ""')
        prev_lat=$(echo "$previous_location" | jq -r '.loc | split(",")[0] // ""')
        prev_lon=$(echo "$previous_location" | jq -r '.loc | split(",")[1] // ""')
        
        if [[ -n "$curr_lat" && -n "$curr_lon" && -n "$prev_lat" && -n "$prev_lon" ]]; then
            local distance
            distance=$(calculate_distance "$prev_lat" "$prev_lon" "$curr_lat" "$curr_lon")
            
            if (( $(echo "$distance > $ALERT_THRESHOLD_MILES" | bc -l) )); then
                log_action "ALERT: Significant location change detected - Distance: ${distance} miles"
                send_security_alert "Location Change" "Device moved ${distance} miles from previous location"
            fi
        fi
    fi
    
    # Save current location
    echo "$current_location" > "$last_location_file"
}

# Generate location report
generate_location_report() {
    local report_file="/tmp/roundfleet_location_report_$(date +%Y%m%d_%H%M%S).txt"
    local hostname
    hostname=$(hostname)
    
    {
        echo "Roundfleet Device Location Report"
        echo "==============================="
        echo "Generated: $(date)"
        echo "Device: $hostname"
        echo ""
        
        echo "Current Location:"
        local current_location
        current_location=$(get_location_info)
        if validate_location "$current_location"; then
            echo "$current_location" | jq '.'
        else
            echo "Unable to retrieve current location"
        fi
        echo ""
        
        echo "Location History (Last 10 entries):"
        if [[ -f "$LOCATION_DB" ]]; then
            tail -10 "$LOCATION_DB" | column -t -s ','
        else
            echo "No location history available"
        fi
        echo ""
        
        echo "Security Events (Last 10):"
        if [[ -f "$LOG_FILE" ]]; then
            grep -i "alert\|security" "$LOG_FILE" | tail -10
        else
            echo "No security events logged"
        fi
        
    } > "$report_file"
    
    echo "📄 Location report generated: $report_file"
    log_action "Location report generated: $report_file"
}

# Main function
main() {
    case "${1:-status}" in
        "track")
            setup_environment
            load_config
            log_action "=== Location Tracking: Single Check ==="
            current_location=$(get_location_info)
            if validate_location "$current_location"; then
                store_location "$current_location"
                check_geofence "$current_location"
                check_network_security "$current_location"
                echo "$current_location" | jq '.'
            fi
            ;;
        "monitor")
            setup_environment
            load_config
            log_action "=== Location Monitoring: Continuous ==="
            monitor_location
            ;;
        "report")
            setup_environment
            load_config
            generate_location_report
            ;;
        "history")
            if [[ -f "$LOCATION_DB" ]]; then
                echo "📍 Location History:"
                column -t -s ',' "$LOCATION_DB"
            else
                echo "No location history available"
            fi
            ;;
        "status"|*)
            setup_environment
            load_config
            echo "📊 Roundfleet Location Status:"
            echo "============================"
            current_location=$(get_location_info)
            if validate_location "$current_location"; then
                echo "$current_location" | jq '.'
            else
                echo "Unable to retrieve location information"
            fi
            ;;
    esac
}

# Execute main function with parameters
main "$@"

Location Tracking Commands

Quick Reference

TaskCommand
Get current locationcurl -s https://ipinfo.io
Formatted location infocurl -s https://ipinfo.io | jq '.'
Save location to filecurl -s https://ipinfo.io > location.json
Get specific fieldcurl -s https://ipinfo.io | jq -r '.city'

Location Data Fields

# Extract specific information
IP=$(curl -s https://ipinfo.io | jq -r '.ip')
CITY=$(curl -s https://ipinfo.io | jq -r '.city')
REGION=$(curl -s https://ipinfo.io | jq -r '.region')
COUNTRY=$(curl -s https://ipinfo.io | jq -r '.country')
COORDINATES=$(curl -s https://ipinfo.io | jq -r '.loc')
ORGANIZATION=$(curl -s https://ipinfo.io | jq -r '.org')
TIMEZONE=$(curl -s https://ipinfo.io | jq -r '.timezone')

Security and Compliance

Privacy Considerations

  1. Data Collection - Only collect necessary location data
  2. Storage Security - Encrypt location databases
  3. Access Control - Limit access to location information
  4. Retention Policy - Define data retention periods
  5. User Consent - Ensure proper authorization

Geofencing Implementation

#!/bin/bash

# Simple geofencing check
check_location_compliance() {
    local location_data
    location_data=$(curl -s https://ipinfo.io)
    
    local country
    country=$(echo "$location_data" | jq -r '.country')
    
    case "$country" in
        "US"|"CA"|"GB")
            echo "✅ Location approved: $country"
            ;;
        *)
            echo "âš ī¸  Location outside approved regions: $country"
            # Log security event
            logger "Roundfleet: Device in unauthorized location: $country"
            ;;
    esac
}

Troubleshooting

Common Issues

  1. Network connectivity problems

    • Check internet connection
    • Verify firewall settings
    • Test alternative geolocation services
  2. Inaccurate location data

    • VPN/proxy connections affect accuracy
    • ISP location may not match physical location
    • Use multiple services for verification
  3. API rate limits

    • Implement proper delays between requests
    • Use authenticated API keys when available
    • Cache location data appropriately

Verification Commands

# Test network connectivity
ping -c 3 ipinfo.io

# Check if jq is installed
which jq || echo "jq not installed"

# Verify location service availability
curl -I https://ipinfo.io

Important Notes

  • Accuracy limitations: IP geolocation provides approximate location, not precise coordinates
  • Network dependencies: Requires internet connectivity to function
  • Privacy compliance: Ensure compliance with local privacy laws and regulations
  • VPN detection: Results may be affected by VPN or proxy services
  • Rate limiting: Implement appropriate delays to avoid service rate limits
  • Data storage: Securely store and manage collected location data

Enterprise Deployment

For enterprise deployment, consider:

  1. Policy definition - Establish clear location tracking policies
  2. Legal compliance - Ensure compliance with privacy regulations
  3. Security monitoring - Implement real-time location alerts
  4. Data governance - Define data retention and access policies
  5. User communication - Inform users about location tracking practices

Desktop Wallpaper Management on macOS

Implement enterprise-grade desktop wallpaper management across your Roundfleet deployment with standardized branding policies, automated image deployment, and comprehensive compliance monitoring. This tutorial provides solutions for maintaining consistent corporate visual identity and brand presence.

Understanding macOS Desktop Wallpaper Management

macOS provides several methods for setting desktop wallpapers programmatically:

  • AppleScript via osascript - Cross-application scripting for Finder integration
  • System Preferences - Native configuration through System Database
  • Desktop Pictures Database - Direct SQLite database manipulation
  • Configuration Profiles - MDM-based wallpaper deployment
  • User Defaults - Per-user preference management

Basic Wallpaper Operations

Set Desktop Wallpaper

#!/bin/bash

# Basic wallpaper setting
path="$1"
osascript -e 'tell application "Finder" to set desktop picture to POSIX file "'"$path"'"'
ret=$?

if [ $ret == "0" ]; then
    echo "Wallpaper set successfully"
else
    echo "Operation failed."
fi

Enhanced Wallpaper Setting with Validation

#!/bin/bash

# Enhanced wallpaper setting with validation and error handling
set_wallpaper() {
    local image_path="$1"
    local user_name="$2"
    
    # Validate image file exists
    if [[ ! -f "$image_path" ]]; then
        echo "❌ Error: Image file not found: $image_path"
        return 1
    fi
    
    # Validate image format
    local file_type
    file_type=$(file --mime-type "$image_path" | awk '{print $2}')
    
    if [[ ! "$file_type" =~ ^image/ ]]; then
        echo "❌ Error: Invalid image format: $file_type"
        return 1
    fi
    
    # Set wallpaper using AppleScript
    echo "Setting wallpaper: $image_path"
    
    if [[ -n "$user_name" ]]; then
        # Set for specific user
        sudo -u "$user_name" osascript -e "tell application \"Finder\" to set desktop picture to POSIX file \"$image_path\""
    else
        # Set for current user
        osascript -e "tell application \"Finder\" to set desktop picture to POSIX file \"$image_path\""
    fi
    
    local result=$?
    
    if [[ $result -eq 0 ]]; then
        echo "✅ Wallpaper set successfully for ${user_name:-current user}"
        return 0
    else
        echo "❌ Failed to set wallpaper (exit code: $result)"
        return 1
    fi
}

# Usage example
# set_wallpaper "/Users/Admin/Pictures/company_wallpaper.png" "admin"

Enterprise Wallpaper Management System

Comprehensive Wallpaper Management Tool

#!/bin/bash

# Roundfleet Enterprise Desktop Wallpaper Management Tool
# Centralized branding and wallpaper policy enforcement

# Configuration
CONFIG_FILE="/etc/roundfleet/wallpaper_policy.conf"
LOG_FILE="/var/log/roundfleet_wallpaper.log"
WALLPAPER_DIR="/Library/Roundfleet/Wallpapers"
REPORT_DIR="/var/log/roundfleet_reports"

# Create directories
mkdir -p "$(dirname "$CONFIG_FILE")" "$(dirname "$LOG_FILE")" "$WALLPAPER_DIR" "$REPORT_DIR"

# Default wallpaper policy
cat > "$CONFIG_FILE" 2>/dev/null << 'EOF' || true
# Roundfleet Wallpaper Management Policy
# Version: 2.0

# Branding Configuration
ENFORCE_CORPORATE_BRANDING=true
ALLOW_USER_CUSTOMIZATION=false
DEFAULT_WALLPAPER="corporate_standard.jpg"
FALLBACK_WALLPAPER="roundfleet_default.png"

# Wallpaper Repository
WALLPAPER_REPOSITORY_URL="https://assets.roundfleet.com/wallpapers"
LOCAL_WALLPAPER_DIR="/Library/Roundfleet/Wallpapers"
SYNC_WALLPAPERS=true

# Policy Settings
SCHEDULE_WALLPAPER_CHANGES=false
WALLPAPER_ROTATION_INTERVAL=86400  # 24 hours
VALIDATE_IMAGE_INTEGRITY=true
LOG_WALLPAPER_CHANGES=true

# User Restrictions
BLOCK_SYSTEM_PREFERENCES_DESKTOP=false
HIDE_DESKTOP_PREFERENCES=false
LOCK_WALLPAPER_SETTINGS=false

# Supported Formats
SUPPORTED_FORMATS="jpg,jpeg,png,heic,bmp,tiff,gif"
MAX_FILE_SIZE_MB=10
MIN_RESOLUTION="1024x768"
EOF

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

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

# Validate image file
validate_image() {
    local image_path="$1"
    local errors=()
    
    # Check file existence
    if [[ ! -f "$image_path" ]]; then
        errors+=("File does not exist")
        printf '%s\n' "${errors[@]}"
        return 1
    fi
    
    # Check file format
    local file_type
    file_type=$(file --mime-type "$image_path" 2>/dev/null | awk '{print $2}')
    
    if [[ ! "$file_type" =~ ^image/ ]]; then
        errors+=("Invalid image format: $file_type")
    fi
    
    # Check file extension
    local extension
    extension=$(echo "${image_path##*.}" | tr '[:upper:]' '[:lower:]')
    
    if [[ ",$SUPPORTED_FORMATS," != *",$extension,"* ]]; then
        errors+=("Unsupported file format: $extension")
    fi
    
    # Check file size
    if command -v stat >/dev/null; then
        local file_size_mb
        file_size_mb=$(( $(stat -f%z "$image_path" 2>/dev/null || echo 0) / 1024 / 1024 ))
        
        if [[ $file_size_mb -gt $MAX_FILE_SIZE_MB ]]; then
            errors+=("File too large: ${file_size_mb}MB (max: ${MAX_FILE_SIZE_MB}MB)")
        fi
    fi
    
    # Check image dimensions
    if command -v sips >/dev/null; then
        local dimensions
        dimensions=$(sips -g pixelWidth -g pixelHeight "$image_path" 2>/dev/null | grep -E "pixelWidth|pixelHeight" | awk '{print $2}' | tr '\n' 'x' | sed 's/x$//')
        
        if [[ -n "$dimensions" ]]; then
            local width height
            width=$(echo "$dimensions" | cut -d'x' -f1)
            height=$(echo "$dimensions" | cut -d'x' -f2)
            local min_width min_height
            min_width=$(echo "$MIN_RESOLUTION" | cut -d'x' -f1)
            min_height=$(echo "$MIN_RESOLUTION" | cut -d'x' -f2)
            
            if [[ $width -lt $min_width || $height -lt $min_height ]]; then
                errors+=("Resolution too low: ${dimensions} (min: ${MIN_RESOLUTION})")
            fi
        fi
    fi
    
    if [[ ${#errors[@]} -eq 0 ]]; then
        return 0
    else
        printf '%s\n' "${errors[@]}"
        return 1
    fi
}

# Download wallpaper from repository
download_wallpaper() {
    local wallpaper_name="$1"
    local local_path="$WALLPAPER_DIR/$wallpaper_name"
    
    if [[ "$SYNC_WALLPAPERS" != "true" ]]; then
        echo "Wallpaper sync disabled"
        return 1
    fi
    
    echo "Downloading wallpaper: $wallpaper_name"
    
    # Download using curl
    if curl -fsSL "$WALLPAPER_REPOSITORY_URL/$wallpaper_name" -o "$local_path.tmp"; then
        # Validate downloaded image
        if validate_image "$local_path.tmp" >/dev/null 2>&1; then
            mv "$local_path.tmp" "$local_path"
            echo "✅ Downloaded and validated: $wallpaper_name"
            log_action "Downloaded wallpaper: $wallpaper_name"
            return 0
        else
            rm -f "$local_path.tmp"
            echo "❌ Downloaded file failed validation"
            return 1
        fi
    else
        echo "❌ Failed to download wallpaper"
        return 1
    fi
}

# Set wallpaper for user
set_user_wallpaper() {
    local image_path="$1"
    local target_user="$2"
    
    echo "=== Setting Wallpaper ==="
    echo "Image: $image_path"
    echo "User: ${target_user:-current user}"
    
    # Validate image
    if ! validate_image "$image_path"; then
        echo "❌ Image validation failed"
        return 1
    fi
    
    # Set wallpaper
    if [[ -n "$target_user" ]]; then
        # Set for specific user (requires appropriate permissions)
        sudo -u "$target_user" osascript -e "tell application \"Finder\" to set desktop picture to POSIX file \"$image_path\"" 2>/dev/null
    else
        # Set for current user
        osascript -e "tell application \"Finder\" to set desktop picture to POSIX file \"$image_path\""
    fi
    
    local result=$?
    
    if [[ $result -eq 0 ]]; then
        echo "✅ Wallpaper set successfully"
        log_action "Wallpaper set: $image_path for user: ${target_user:-current}"
        return 0
    else
        echo "❌ Failed to set wallpaper (exit code: $result)"
        log_action "FAILED to set wallpaper: $image_path for user: ${target_user:-current}"
        return 1
    fi
}

# Apply corporate wallpaper
apply_corporate_wallpaper() {
    local wallpaper_name="${1:-$DEFAULT_WALLPAPER}"
    local target_user="$2"
    
    echo "=== Applying Corporate Wallpaper ==="
    
    if [[ "$ENFORCE_CORPORATE_BRANDING" != "true" ]]; then
        echo "Corporate branding enforcement disabled"
        return 0
    fi
    
    # Check if wallpaper exists locally
    local wallpaper_path="$WALLPAPER_DIR/$wallpaper_name"
    
    if [[ ! -f "$wallpaper_path" ]]; then
        echo "Wallpaper not found locally, attempting download..."
        if ! download_wallpaper "$wallpaper_name"; then
            echo "Using fallback wallpaper..."
            wallpaper_path="$WALLPAPER_DIR/$FALLBACK_WALLPAPER"
            
            if [[ ! -f "$wallpaper_path" ]]; then
                echo "❌ No wallpaper available (including fallback)"
                return 1
            fi
        else
            wallpaper_path="$WALLPAPER_DIR/$wallpaper_name"
        fi
    fi
    
    # Apply wallpaper
    set_user_wallpaper "$wallpaper_path" "$target_user"
}

# Get current wallpaper information
get_current_wallpaper() {
    echo "=== Current Wallpaper Information ==="
    
    # Get current wallpaper path using AppleScript
    local current_wallpaper
    current_wallpaper=$(osascript -e 'tell application "Finder" to get desktop picture as string' 2>/dev/null)
    
    if [[ -n "$current_wallpaper" ]]; then
        # Convert from HFS+ path to POSIX path
        local posix_path
        posix_path=$(osascript -e "get POSIX path of \"$current_wallpaper\"" 2>/dev/null)
        
        echo "Current wallpaper: $posix_path"
        
        if [[ -f "$posix_path" ]]; then
            echo "File size: $(du -h "$posix_path" | cut -f1)"
            
            # Get image dimensions if sips is available
            if command -v sips >/dev/null; then
                local dimensions
                dimensions=$(sips -g pixelWidth -g pixelHeight "$posix_path" 2>/dev/null | grep -E "pixelWidth|pixelHeight" | awk '{print $2}' | tr '\n' 'x' | sed 's/x$//')
                echo "Dimensions: $dimensions"
            fi
            
            # Check if it's a corporate wallpaper
            if [[ "$posix_path" == "$WALLPAPER_DIR"* ]]; then
                echo "✅ Corporate wallpaper detected"
            else
                echo "âš ī¸  Non-corporate wallpaper detected"
            fi
        else
            echo "âš ī¸  Wallpaper file not found"
        fi
    else
        echo "❌ Unable to retrieve current wallpaper"
    fi
}

# Sync wallpaper repository
sync_wallpaper_repository() {
    echo "=== Syncing Wallpaper Repository ==="
    
    if [[ "$SYNC_WALLPAPERS" != "true" ]]; then
        echo "Wallpaper sync disabled"
        return 0
    fi
    
    # Create wallpaper directory
    mkdir -p "$WALLPAPER_DIR"
    
    # Download manifest file
    local manifest_file="$WALLPAPER_DIR/.manifest"
    
    if curl -fsSL "$WALLPAPER_REPOSITORY_URL/manifest.txt" -o "$manifest_file.tmp" 2>/dev/null; then
        echo "Downloaded wallpaper manifest"
        
        # Process manifest and download wallpapers
        while IFS= read -r wallpaper_name; do
            [[ -z "$wallpaper_name" || "$wallpaper_name" =~ ^# ]] && continue
            
            local local_path="$WALLPAPER_DIR/$wallpaper_name"
            
            if [[ ! -f "$local_path" ]]; then
                echo "Downloading: $wallpaper_name"
                download_wallpaper "$wallpaper_name"
            else
                echo "Already exists: $wallpaper_name"
            fi
        done < "$manifest_file.tmp"
        
        mv "$manifest_file.tmp" "$manifest_file"
        echo "✅ Wallpaper repository synchronized"
        log_action "Wallpaper repository synchronized"
    else
        echo "❌ Failed to download manifest"
        return 1
    fi
}

# Generate compliance report
generate_wallpaper_report() {
    local report_file="$REPORT_DIR/wallpaper_compliance_$(date +%Y%m%d_%H%M%S).json"
    
    echo "=== Generating Wallpaper Compliance Report ==="
    
    # Get current wallpaper
    local current_wallpaper
    current_wallpaper=$(osascript -e 'tell application "Finder" to get desktop picture as string' 2>/dev/null)
    local posix_path=""
    local is_corporate="false"
    local compliance_status="non_compliant"
    
    if [[ -n "$current_wallpaper" ]]; then
        posix_path=$(osascript -e "get POSIX path of \"$current_wallpaper\"" 2>/dev/null)
        
        if [[ "$posix_path" == "$WALLPAPER_DIR"* ]]; then
            is_corporate="true"
            compliance_status="compliant"
        fi
    fi
    
    # Create JSON report
    cat > "$report_file" << EOF
{
  "report_type": "wallpaper_compliance",
  "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
  "device_info": {
    "hostname": "$(hostname)",
    "serial_number": "$(system_profiler SPHardwareDataType | grep "Serial Number" | awk -F: '{print $2}' | xargs)",
    "macos_version": "$(sw_vers -productVersion)",
    "current_user": "$(whoami)"
  },
  "wallpaper_status": {
    "current_wallpaper": "$posix_path",
    "is_corporate_wallpaper": $is_corporate,
    "compliance_status": "$compliance_status",
    "branding_enforced": $ENFORCE_CORPORATE_BRANDING
  },
  "policy_settings": {
    "corporate_branding_enforced": $ENFORCE_CORPORATE_BRANDING,
    "user_customization_allowed": $ALLOW_USER_CUSTOMIZATION,
    "default_wallpaper": "$DEFAULT_WALLPAPER",
    "wallpaper_sync_enabled": $SYNC_WALLPAPERS
  },
  "repository_info": {
    "local_wallpaper_count": $(find "$WALLPAPER_DIR" -name "*.jpg" -o -name "*.png" -o -name "*.jpeg" 2>/dev/null | wc -l | xargs),
    "last_sync": "$(stat -f %Sm "$WALLPAPER_DIR/.manifest" 2>/dev/null || echo "never")"
  }
}
EOF
    
    echo "Wallpaper compliance report saved to: $report_file"
    log_action "Wallpaper compliance report generated: $report_file"
}

# Main function with argument handling
main() {
    log_action "=== Roundfleet Wallpaper Management Tool Started ==="
    
    case "${1:-status}" in
        "set")
            set_user_wallpaper "$2" "$3"
            ;;
        "corporate")
            apply_corporate_wallpaper "$2" "$3"
            ;;
        "sync")
            sync_wallpaper_repository
            ;;
        "validate")
            if validate_image "$2"; then
                echo "✅ Image validation passed: $2"
            else
                echo "❌ Image validation failed: $2"
            fi
            ;;
        "download")
            download_wallpaper "$2"
            ;;
        "report")
            generate_wallpaper_report
            ;;
        "status"|*)
            get_current_wallpaper
            ;;
    esac
    
    log_action "=== Wallpaper management operation completed ==="
}

# Execute main function
main "$@"

Advanced Wallpaper Management

Automated Wallpaper Rotation

#!/bin/bash

# Automated wallpaper rotation system
setup_wallpaper_rotation() {
    echo "=== Setting Up Wallpaper Rotation ==="
    
    if [[ "$SCHEDULE_WALLPAPER_CHANGES" != "true" ]]; then
        echo "Wallpaper rotation disabled in policy"
        return 0
    fi
    
    # Create rotation script
    local rotation_script="/usr/local/bin/roundfleet-wallpaper-rotate"
    
    cat > "$rotation_script" << 'EOF'
#!/bin/bash
# Roundfleet Wallpaper Rotation Script

WALLPAPER_DIR="/Library/Roundfleet/Wallpapers"
LOG_FILE="/var/log/roundfleet_wallpaper.log"

# Get list of available wallpapers
mapfile -t wallpapers < <(find "$WALLPAPER_DIR" -name "*.jpg" -o -name "*.png" -o -name "*.jpeg" 2>/dev/null)

if [[ ${#wallpapers[@]} -eq 0 ]]; then
    echo "$(date) - No wallpapers found for rotation" >> "$LOG_FILE"
    exit 1
fi

# Select random wallpaper
random_wallpaper="${wallpapers[$RANDOM % ${#wallpapers[@]}]}"

# Apply wallpaper
/usr/local/bin/roundfleet-wallpaper set "$random_wallpaper"

echo "$(date) - Rotated to wallpaper: $random_wallpaper" >> "$LOG_FILE"
EOF
    
    chmod +x "$rotation_script"
    
    # Create LaunchDaemon for scheduling
    local plist_file="/Library/LaunchDaemons/com.roundfleet.wallpaper-rotation.plist"
    
    cat > "$plist_file" << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.roundfleet.wallpaper-rotation</string>
    <key>ProgramArguments</key>
    <array>
        <string>$rotation_script</string>
    </array>
    <key>StartInterval</key>
    <integer>$WALLPAPER_ROTATION_INTERVAL</integer>
    <key>RunAtLoad</key>
    <false/>
</dict>
</plist>
EOF
    
    # Load the daemon
    launchctl load "$plist_file"
    
    echo "✅ Wallpaper rotation configured (interval: ${WALLPAPER_ROTATION_INTERVAL}s)"
}

setup_wallpaper_rotation

Multi-Display Wallpaper Management

#!/bin/bash

# Multi-display wallpaper management
set_multi_display_wallpapers() {
    echo "=== Multi-Display Wallpaper Management ==="
    
    # Get display count
    local display_count
    display_count=$(system_profiler SPDisplaysDataType | grep -c "Resolution:")
    
    echo "Detected displays: $display_count"
    
    if [[ $display_count -gt 1 ]]; then
        echo "Setting wallpapers for multiple displays..."
        
        # Set different wallpapers for each display
        for ((i=1; i<=display_count; i++)); do
            local wallpaper_file="display_${i}_wallpaper.jpg"
            local wallpaper_path="$WALLPAPER_DIR/$wallpaper_file"
            
            if [[ -f "$wallpaper_path" ]]; then
                echo "Setting wallpaper for display $i: $wallpaper_file"
                
                # Use AppleScript to set wallpaper for specific display
                osascript << EOF
                tell application "System Events"
                    tell desktop $i
                        set picture to "$wallpaper_path"
                    end tell
                end tell
EOF
            else
                echo "âš ī¸  Wallpaper not found for display $i: $wallpaper_file"
            fi
        done
    else
        echo "Single display detected, using standard wallpaper"
        apply_corporate_wallpaper
    fi
}

set_multi_display_wallpapers

Wallpaper Policy Enforcement

#!/bin/bash

# Monitor and enforce wallpaper policies
monitor_wallpaper_compliance() {
    echo "=== Wallpaper Compliance Monitoring ==="
    
    # Check current wallpaper compliance
    local current_wallpaper
    current_wallpaper=$(osascript -e 'tell application "Finder" to get desktop picture as string' 2>/dev/null)
    
    if [[ -n "$current_wallpaper" ]]; then
        local posix_path
        posix_path=$(osascript -e "get POSIX path of \"$current_wallpaper\"" 2>/dev/null)
        
        # Check if wallpaper is from corporate repository
        if [[ "$posix_path" != "$WALLPAPER_DIR"* ]] && [[ "$ENFORCE_CORPORATE_BRANDING" == "true" ]]; then
            echo "âš ī¸  Non-corporate wallpaper detected: $posix_path"
            log_action "POLICY VIOLATION: Non-corporate wallpaper detected: $posix_path"
            
            # Auto-remediate if enabled
            if [[ "$ALLOW_USER_CUSTOMIZATION" != "true" ]]; then
                echo "Auto-remediating with corporate wallpaper..."
                apply_corporate_wallpaper
                log_action "Auto-remediated wallpaper policy violation"
            fi
        else
            echo "✅ Wallpaper compliance: OK"
        fi
    else
        echo "❌ Unable to check wallpaper compliance"
    fi
}

monitor_wallpaper_compliance

Integration and Deployment

MDM Integration Script

#!/bin/bash

# MDM integration for wallpaper deployment
deploy_wallpaper_via_mdm() {
    local wallpaper_url="$1"
    local deployment_mode="${2:-immediate}"
    
    echo "=== MDM Wallpaper Deployment ==="
    echo "Source: $wallpaper_url"
    echo "Mode: $deployment_mode"
    
    # Download wallpaper
    local temp_file="/tmp/mdm_wallpaper_$(date +%s).jpg"
    
    if curl -fsSL "$wallpaper_url" -o "$temp_file"; then
        echo "✅ Downloaded wallpaper from MDM"
        
        # Validate and deploy
        if validate_image "$temp_file"; then
            # Copy to corporate wallpaper directory
            local dest_file="$WALLPAPER_DIR/mdm_deployed_$(basename "$temp_file")"
            cp "$temp_file" "$dest_file"
            
            # Apply immediately or schedule
            case "$deployment_mode" in
                "immediate")
                    set_user_wallpaper "$dest_file"
                    ;;
                "next_login")
                    # Set as default for next login
                    defaults write /Library/Preferences/com.apple.desktop Background "{default = {ImageFilePath = '$dest_file'; }; }"
                    ;;
                "scheduled")
                    # Add to rotation pool
                    echo "Added to rotation pool: $dest_file"
                    ;;
            esac
            
            # Cleanup
            rm -f "$temp_file"
            echo "✅ MDM wallpaper deployment completed"
        else
            echo "❌ MDM wallpaper validation failed"
            rm -f "$temp_file"
            return 1
        fi
    else
        echo "❌ Failed to download wallpaper from MDM"
        return 1
    fi
}

# Example usage:
# deploy_wallpaper_via_mdm "https://mdm.company.com/wallpapers/quarterly_branding.jpg" "immediate"

Important Configuration Notes

AppleScript and Security

  • Privacy permissions required for script execution
  • User consent needed for Finder access on first run
  • Automation permissions for System Events access
  • Full Disk Access may be required for some operations

Supported Image Formats

  • JPEG/JPG - Most common, good compression
  • PNG - Supports transparency, larger files
  • HEIC - Apple's modern format, efficient
  • TIFF/BMP - Legacy formats, large files
  • GIF - Animated support (single frame used)

Best Practices for Enterprise

  1. Image Optimization

    • Use appropriate resolution for target displays
    • Optimize file sizes for network deployment
    • Test images across different display configurations
  2. Branding Consistency

    • Maintain corporate color schemes
    • Include company logos and messaging
    • Consider seasonal or campaign-specific variations
  3. Deployment Strategy

    • Use centralized image repositories
    • Implement staged rollouts for new wallpapers
    • Provide fallback options for connectivity issues
  4. User Experience

    • Consider user preferences where policy allows
    • Provide clear communication about branding policies
    • Offer opt-out mechanisms for non-critical branding

Troubleshooting Common Issues

  • Permission denied errors - Check script execution permissions and user context
  • Image not displaying - Verify file format compatibility and path accessibility
  • Policy conflicts - Review configuration profile settings and user defaults
  • Performance issues - Optimize image file sizes and deployment timing

Remember to test wallpaper changes across different display configurations and user scenarios before deploying to your entire Roundfleet environment.

Deploy ZIP Files to Macs Using URLs

Deploying applications and files across your Roundfleet can be streamlined by hosting ZIP files on a server and automatically downloading them to target devices. This tutorial shows how to create robust scripts for ZIP file deployment using URLs.

Understanding the Process

The deployment process involves:

  1. Download - Fetch the ZIP file from a URL using curl
  2. Extract - Unzip the contents using unzip
  3. Install - Optionally install or move files to their final location
  4. Cleanup - Remove temporary files

Basic ZIP Deployment Script

Simple Download and Extract

#!/bin/bash

# Basic ZIP deployment script
cd /tmp

# Download the ZIP file
curl -k https://example.com/myapp.zip -o "myapp.zip"

# Extract the contents
unzip "myapp.zip"

Enhanced Enterprise Script

For production environments with error handling and logging:

#!/bin/bash

# ZIP File Deployment Script for Roundfleet
# Compatible with macOS 10.14+

# Configuration variables
DOWNLOAD_URL="$1"  # First argument: URL to ZIP file
ZIP_NAME="$2"      # Second argument: ZIP filename
DESTINATION="${3:-/tmp}"  # Third argument: destination (default: /tmp)
LOG_FILE="/var/log/zip_deployment.log"

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

# Function to validate URL
validate_url() {
    local url="$1"
    if [[ ! "$url" =~ ^https?:// ]]; then
        log_message "✗ Invalid URL format: $url"
        return 1
    fi
    return 0
}

# Function to check internet connectivity
check_connectivity() {
    if ! ping -c 1 google.com &> /dev/null; then
        log_message "✗ No internet connectivity"
        return 1
    fi
    return 0
}

# Function to download ZIP file
download_zip() {
    local url="$1"
    local filename="$2"
    local destination="$3"
    
    log_message "Starting download from: $url"
    
    # Create destination directory if it doesn't exist
    mkdir -p "$destination"
    cd "$destination" || return 1
    
    # Download with progress and error handling
    if curl -L --fail --connect-timeout 30 --max-time 300 \
            --progress-bar "$url" -o "$filename"; then
        log_message "✓ Download completed: $filename"
        return 0
    else
        log_message "✗ Download failed from: $url"
        return 1
    fi
}

# Function to extract ZIP file
extract_zip() {
    local filename="$1"
    local destination="$2"
    
    cd "$destination" || return 1
    
    # Check if ZIP file exists
    if [[ ! -f "$filename" ]]; then
        log_message "✗ ZIP file not found: $filename"
        return 1
    fi
    
    # Test ZIP integrity
    if ! unzip -t "$filename" &> /dev/null; then
        log_message "✗ ZIP file is corrupted: $filename"
        return 1
    fi
    
    # Extract files
    if unzip -o "$filename"; then
        log_message "✓ Extraction completed: $filename"
        return 0
    else
        log_message "✗ Extraction failed: $filename"
        return 1
    fi
}

# Function to install application (if .app bundle found)
install_application() {
    local source_dir="$1"
    
    # Look for .app bundles
    local app_bundle
    app_bundle=$(find "$source_dir" -name "*.app" -type d | head -1)
    
    if [[ -n "$app_bundle" ]]; then
        local app_name
        app_name=$(basename "$app_bundle")
        
        log_message "Found application bundle: $app_name"
        
        # Copy to Applications folder
        if cp -R "$app_bundle" "/Applications/"; then
            log_message "✓ Application installed: $app_name"
            return 0
        else
            log_message "✗ Application installation failed: $app_name"
            return 1
        fi
    else
        log_message "! No application bundle found for installation"
        return 0
    fi
}

# Function to cleanup temporary files
cleanup() {
    local destination="$1"
    local filename="$2"
    
    cd "$destination" || return 1
    
    if [[ -f "$filename" ]]; then
        rm -f "$filename"
        log_message "✓ Cleanup completed: $filename"
    fi
}

# Main deployment function
deploy_zip() {
    log_message "=== Starting ZIP deployment ==="
    
    # Validate inputs
    if [[ -z "$DOWNLOAD_URL" ]] || [[ -z "$ZIP_NAME" ]]; then
        log_message "✗ Usage: $0 <download_url> <zip_filename> [destination]"
        return 1
    fi
    
    # Validate URL format
    if ! validate_url "$DOWNLOAD_URL"; then
        return 1
    fi
    
    # Check connectivity
    if ! check_connectivity; then
        return 1
    fi
    
    # Download ZIP file
    if ! download_zip "$DOWNLOAD_URL" "$ZIP_NAME" "$DESTINATION"; then
        return 1
    fi
    
    # Extract ZIP file
    if ! extract_zip "$ZIP_NAME" "$DESTINATION"; then
        return 1
    fi
    
    # Attempt application installation
    install_application "$DESTINATION"
    
    # Cleanup temporary ZIP file
    cleanup "$DESTINATION" "$ZIP_NAME"
    
    log_message "=== ZIP deployment completed successfully ==="
    return 0
}

# Execute main function
if deploy_zip; then
    exit 0
else
    log_message "=== ZIP deployment failed ==="
    exit 1
fi

Quick Deployment Scripts

Download to Applications

#!/bin/bash

# Download and install app directly to Applications
URL="https://example.com/MyApp.zip"
ZIP_NAME="MyApp.zip"

cd /tmp
curl -L "$URL" -o "$ZIP_NAME"
unzip "$ZIP_NAME"

# Find and move .app bundle
APP_BUNDLE=$(find . -name "*.app" -type d | head -1)
if [[ -n "$APP_BUNDLE" ]]; then
    cp -R "$APP_BUNDLE" /Applications/
    echo "Application installed successfully"
fi

# Cleanup
rm -f "$ZIP_NAME"
rm -rf "${ZIP_NAME%.zip}"

Download with Checksum Verification

#!/bin/bash

URL="https://example.com/myapp.zip"
ZIP_NAME="myapp.zip"
EXPECTED_SHA256="abc123..."  # Replace with actual checksum

cd /tmp
curl -L "$URL" -o "$ZIP_NAME"

# Verify checksum
if echo "$EXPECTED_SHA256  $ZIP_NAME" | shasum -a 256 -c; then
    echo "Checksum verified"
    unzip "$ZIP_NAME"
else
    echo "Checksum verification failed"
    exit 1
fi

Usage Examples

Command Line Usage

# Basic usage
./deploy_zip.sh "https://example.com/app.zip" "app.zip"

# Custom destination
./deploy_zip.sh "https://example.com/app.zip" "app.zip" "/Applications"

# With logging
./deploy_zip.sh "https://example.com/app.zip" "app.zip" 2>&1 | tee deployment.log

Roundfleet Deployment

#!/bin/bash

# Deploy multiple applications
APPS=(
    "https://cdn.example.com/productivity.zip:productivity.zip"
    "https://cdn.example.com/security.zip:security.zip"
    "https://cdn.example.com/utilities.zip:utilities.zip"
)

for app in "${APPS[@]}"; do
    IFS=':' read -r url filename <<< "$app"
    echo "Deploying: $filename"
    ./deploy_zip.sh "$url" "$filename"
done

Troubleshooting

IssueSolution
Download failsCheck URL accessibility and internet connection
ZIP extraction errorsVerify ZIP file integrity with unzip -t
Permission deniedRun script with admin privileges
App not installingCheck for .app bundle in extracted contents
Slow downloadsIncrease curl timeout values

Security Considerations

  • HTTPS URLs - Always use secure connections when possible
  • Checksum verification - Verify file integrity before extraction
  • Code signing - Verify application signatures before installation
  • Sandboxed downloads - Use /tmp for temporary storage

File Location Reference

  • Temporary files: /tmp/
  • Applications: /Applications/
  • User applications: ~/Applications/
  • System utilities: /usr/local/bin/
  • Logs: /var/log/zip_deployment.log

Advanced Features

Progress Monitoring

# Show download progress
curl --progress-bar -L "$URL" -o "$ZIP_NAME"

# Or with detailed progress
curl -# -L "$URL" -o "$ZIP_NAME"

Retry Logic

# Retry download up to 3 times
for i in {1..3}; do
    if curl -L "$URL" -o "$ZIP_NAME"; then
        break
    elif [[ $i -eq 3 ]]; then
        echo "Download failed after 3 attempts"
        exit 1
    fi
    sleep 5
done

Important Notes

  • ZIP files are temporarily stored in /tmp by default
  • Use secure HTTPS URLs when possible
  • Test scripts on a small group before enterprise deployment
  • Monitor disk space when deploying large files
  • Consider bandwidth limitations in your network

Delete Mobile Accounts on macOS Devices

This comprehensive guide demonstrates how to delete mobile accounts on macOS devices for effective user management, device reassignment, and organizational cleanup scenarios.

Overview

Mobile accounts on macOS are user profiles designed for seamless access to resources across different devices within organizations. Unlike local accounts, mobile accounts are centrally managed by directory services like Open Directory or Active Directory, enabling administrators to control access, enforce policies, and manage user data centrally.

Common Scenarios for Mobile Account Deletion

  • Employee departures: Clean up accounts when employees leave the organization
  • Role changes: Remove old mobile accounts when users change positions
  • Device reassignment: Prepare devices for new users
  • Security compliance: Remove inactive or compromised accounts
  • Storage optimization: Free up disk space by removing unused accounts
  • Organizational restructuring: Clean up accounts during company changes

Basic Mobile Account Deletion

Simple Mobile Account Removal Script

Create a basic script to remove all mobile accounts from a macOS device:

#!/bin/bash

# Basic mobile account deletion script
# Usage: ./delete_mobile_accounts.sh

delete_mobile_accounts() {
    echo "Starting mobile account deletion process..."
    
    # Check if running as root
    if [ "$EUID" -ne 0 ]; then
        echo "Error: This script must be run as root"
        exit 1
    fi
    
    # Counter for deleted accounts
    local deleted_count=0
    
    # Loop through all users
    for username in $(dscl . -list /Users | grep -v '^_'); do
        # Check if user has mobile account authentication
        auth_authority=$(dscl . -read "/Users/$username" AuthenticationAuthority 2>/dev/null | grep "LocalCachedUser")
        
        if [ -n "$auth_authority" ]; then
            echo "Removing mobile account: $username"
            
            # Delete user from directory services
            dscl . -delete "/Users/$username"
            
            # Remove user's home directory
            rm -rf "/Users/$username"
            
            ((deleted_count++))
        fi
    done
    
    echo "Mobile accounts removal complete. Deleted $deleted_count accounts."
    echo "Note: Please restart the device for changes to take full effect."
}

# Execute deletion
delete_mobile_accounts

Enhanced Mobile Account Management Script

#!/bin/bash

# Enhanced mobile account management with safety checks and logging
# Usage: ./enhanced_mobile_account_manager.sh

enhanced_mobile_account_manager() {
    local log_file="/var/log/roundfleet_mobile_accounts.log"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    local backup_dir="/var/backups/roundfleet/mobile_accounts"
    
    # Check if running as root
    if [ "$EUID" -ne 0 ]; then
        echo "Error: This script must be run as root"
        exit 1
    fi
    
    # Create log directory
    mkdir -p /var/log
    mkdir -p "$backup_dir"
    
    echo "[$timestamp] Enhanced mobile account manager started" >> "$log_file"
    
    # Display current mobile accounts
    display_mobile_accounts
    
    # Confirm deletion
    echo ""
    read -p "Do you want to proceed with mobile account deletion? (y/N): " confirm
    
    if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
        create_account_backup
        delete_mobile_accounts_enhanced
    else
        echo "Operation cancelled."
        echo "[$timestamp] Mobile account deletion cancelled by user" >> "$log_file"
    fi
}

display_mobile_accounts() {
    echo "======================================="
    echo "Current Mobile Accounts on Device"
    echo "======================================="
    
    local mobile_accounts_found=false
    
    for username in $(dscl . -list /Users | grep -v '^_'); do
        auth_authority=$(dscl . -read "/Users/$username" AuthenticationAuthority 2>/dev/null | grep "LocalCachedUser")
        
        if [ -n "$auth_authority" ]; then
            mobile_accounts_found=true
            
            # Get additional user information
            local real_name=$(dscl . -read "/Users/$username" RealName 2>/dev/null | cut -d: -f2 | xargs)
            local uid=$(dscl . -read "/Users/$username" UniqueID 2>/dev/null | cut -d: -f2 | xargs)
            local home_dir=$(dscl . -read "/Users/$username" NFSHomeDirectory 2>/dev/null | cut -d: -f2 | xargs)
            local last_login=$(last -1 "$username" 2>/dev/null | head -1 | awk '{print $3, $4, $5, $6}')
            
            echo "Username: $username"
            echo "  Real Name: $real_name"
            echo "  UID: $uid"
            echo "  Home Directory: $home_dir"
            echo "  Last Login: $last_login"
            
            # Check home directory size
            if [ -d "$home_dir" ]; then
                local dir_size=$(du -sh "$home_dir" 2>/dev/null | cut -f1)
                echo "  Home Directory Size: $dir_size"
            fi
            
            echo ""
        fi
    done
    
    if [ "$mobile_accounts_found" = false ]; then
        echo "No mobile accounts found on this device."
        echo "[$timestamp] No mobile accounts found on device" >> "$log_file"
        exit 0
    fi
}

create_account_backup() {
    echo "Creating backup of mobile account information..."
    
    local backup_file="$backup_dir/mobile_accounts_backup_$(date +%Y%m%d_%H%M%S).txt"
    
    cat > "$backup_file" << EOF
Roundfleet Mobile Account Backup
Generated: $(date)
Device: $(scutil --get ComputerName)
macOS Version: $(sw_vers -productVersion)

Mobile Accounts Found:
EOF
    
    for username in $(dscl . -list /Users | grep -v '^_'); do
        auth_authority=$(dscl . -read "/Users/$username" AuthenticationAuthority 2>/dev/null | grep "LocalCachedUser")
        
        if [ -n "$auth_authority" ]; then
            echo "Username: $username" >> "$backup_file"
            dscl . -read "/Users/$username" >> "$backup_file"
            echo "---" >> "$backup_file"
        fi
    done
    
    echo "Backup created: $backup_file"
    echo "[$timestamp] Mobile account backup created: $backup_file" >> "$log_file"
}

delete_mobile_accounts_enhanced() {
    echo "======================================="
    echo "Deleting Mobile Accounts"
    echo "======================================="
    
    local deleted_count=0
    local failed_count=0
    
    for username in $(dscl . -list /Users | grep -v '^_'); do
        auth_authority=$(dscl . -read "/Users/$username" AuthenticationAuthority 2>/dev/null | grep "LocalCachedUser")
        
        if [ -n "$auth_authority" ]; then
            echo "Processing mobile account: $username"
            
            # Check if user is currently logged in
            if who | grep -q "^$username "; then
                echo "  Warning: User $username is currently logged in. Skipping..."
                echo "[$timestamp] Skipped deletion of $username - user currently logged in" >> "$log_file"
                ((failed_count++))
                continue
            fi
            
            # Delete user from directory services
            if dscl . -delete "/Users/$username" 2>/dev/null; then
                echo "  Deleted user record from directory services"
            else
                echo "  Warning: Failed to delete user record from directory services"
                echo "[$timestamp] Failed to delete user record for $username" >> "$log_file"
                ((failed_count++))
                continue
            fi
            
            # Remove user's home directory
            local home_dir=$(dscl . -read "/Users/$username" NFSHomeDirectory 2>/dev/null | cut -d: -f2 | xargs)
            if [ -d "$home_dir" ]; then
                if rm -rf "$home_dir" 2>/dev/null; then
                    echo "  Removed home directory: $home_dir"
                else
                    echo "  Warning: Failed to remove home directory: $home_dir"
                    echo "[$timestamp] Failed to remove home directory for $username: $home_dir" >> "$log_file"
                fi
            fi
            
            echo "  Successfully deleted mobile account: $username"
            echo "[$timestamp] Successfully deleted mobile account: $username" >> "$log_file"
            ((deleted_count++))
        fi
    done
    
    echo ""
    echo "======================================="
    echo "Mobile Account Deletion Summary"
    echo "======================================="
    echo "Successfully deleted: $deleted_count accounts"
    echo "Failed to delete: $failed_count accounts"
    echo "Total processed: $((deleted_count + failed_count)) accounts"
    echo ""
    echo "Note: Please restart the device for changes to take full effect."
    
    echo "[$timestamp] Mobile account deletion completed - Success: $deleted_count, Failed: $failed_count" >> "$log_file"
}

# Execute enhanced management
enhanced_mobile_account_manager

Advanced Mobile Account Management

Selective Mobile Account Management

#!/bin/bash

# Selective mobile account management system
# Usage: ./selective_mobile_account_manager.sh

selective_mobile_account_manager() {
    local log_file="/var/log/roundfleet_selective_mobile_accounts.log"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    
    # Check if running as root
    if [ "$EUID" -ne 0 ]; then
        echo "Error: This script must be run as root"
        exit 1
    fi
    
    echo "[$timestamp] Selective mobile account manager started" >> "$log_file"
    
    while true; do
        display_selective_menu
        read -p "Select an option (1-7): " choice
        
        case $choice in
            1)
                list_mobile_accounts_detailed
                ;;
            2)
                delete_specific_mobile_account
                ;;
            3)
                delete_inactive_mobile_accounts
                ;;
            4)
                delete_mobile_accounts_by_criteria
                ;;
            5)
                export_mobile_account_report
                ;;
            6)
                restore_mobile_account_backup
                ;;
            7)
                echo "Exiting selective mobile account manager."
                exit 0
                ;;
            *)
                echo "Invalid option. Please try again."
                ;;
        esac
        
        echo ""
        read -p "Press Enter to continue..."
    done
}

display_selective_menu() {
    clear
    echo "======================================="
    echo "Roundfleet Selective Mobile Account Manager"
    echo "======================================="
    echo ""
    echo "1. List all mobile accounts with details"
    echo "2. Delete specific mobile account"
    echo "3. Delete inactive mobile accounts"
    echo "4. Delete mobile accounts by criteria"
    echo "5. Export mobile account report"
    echo "6. Restore from backup"
    echo "7. Exit"
    echo ""
}

list_mobile_accounts_detailed() {
    echo "======================================="
    echo "Detailed Mobile Account Information"
    echo "======================================="
    
    local mobile_accounts=()
    local count=0
    
    for username in $(dscl . -list /Users | grep -v '^_'); do
        auth_authority=$(dscl . -read "/Users/$username" AuthenticationAuthority 2>/dev/null | grep "LocalCachedUser")
        
        if [ -n "$auth_authority" ]; then
            mobile_accounts+=("$username")
            ((count++))
            
            echo "[$count] Mobile Account: $username"
            
            # Get detailed information
            local real_name=$(dscl . -read "/Users/$username" RealName 2>/dev/null | cut -d: -f2 | xargs)
            local uid=$(dscl . -read "/Users/$username" UniqueID 2>/dev/null | cut -d: -f2 | xargs)
            local gid=$(dscl . -read "/Users/$username" PrimaryGroupID 2>/dev/null | cut -d: -f2 | xargs)
            local home_dir=$(dscl . -read "/Users/$username" NFSHomeDirectory 2>/dev/null | cut -d: -f2 | xargs)
            local shell=$(dscl . -read "/Users/$username" UserShell 2>/dev/null | cut -d: -f2 | xargs)
            
            echo "    Real Name: $real_name"
            echo "    UID: $uid"
            echo "    GID: $gid"
            echo "    Home Directory: $home_dir"
            echo "    Shell: $shell"
            
            # Check if user is currently logged in
            if who | grep -q "^$username "; then
                echo "    Status: Currently logged in"
            else
                echo "    Status: Not logged in"
            fi
            
            # Get last login information
            local last_login=$(last -1 "$username" 2>/dev/null | head -1)
            if [ -n "$last_login" ]; then
                echo "    Last Login: $last_login"
            else
                echo "    Last Login: Never"
            fi
            
            # Check home directory size
            if [ -d "$home_dir" ]; then
                local dir_size=$(du -sh "$home_dir" 2>/dev/null | cut -f1)
                echo "    Home Directory Size: $dir_size"
                
                # Check last modification time
                local last_modified=$(stat -f "%Sm" "$home_dir" 2>/dev/null)
                echo "    Last Modified: $last_modified"
            else
                echo "    Home Directory: Not found"
            fi
            
            echo ""
        fi
    done
    
    if [ $count -eq 0 ]; then
        echo "No mobile accounts found on this device."
    else
        echo "Total mobile accounts found: $count"
    fi
}

delete_specific_mobile_account() {
    echo "======================================="
    echo "Delete Specific Mobile Account"
    echo "======================================="
    
    # List mobile accounts with numbers
    local mobile_accounts=()
    local count=0
    
    for username in $(dscl . -list /Users | grep -v '^_'); do
        auth_authority=$(dscl . -read "/Users/$username" AuthenticationAuthority 2>/dev/null | grep "LocalCachedUser")
        
        if [ -n "$auth_authority" ]; then
            mobile_accounts+=("$username")
            ((count++))
            echo "[$count] $username"
        fi
    done
    
    if [ $count -eq 0 ]; then
        echo "No mobile accounts found on this device."
        return
    fi
    
    echo ""
    read -p "Enter the number of the account to delete (1-$count): " selection
    
    if [[ "$selection" =~ ^[0-9]+$ ]] && [ "$selection" -ge 1 ] && [ "$selection" -le $count ]; then
        local selected_user="${mobile_accounts[$((selection-1))]}"
        
        echo ""
        echo "Selected account: $selected_user"
        
        # Show account details
        local real_name=$(dscl . -read "/Users/$selected_user" RealName 2>/dev/null | cut -d: -f2 | xargs)
        local home_dir=$(dscl . -read "/Users/$selected_user" NFSHomeDirectory 2>/dev/null | cut -d: -f2 | xargs)
        
        echo "Real Name: $real_name"
        echo "Home Directory: $home_dir"
        
        # Check if user is logged in
        if who | grep -q "^$selected_user "; then
            echo "Warning: User is currently logged in!"
            read -p "Do you want to continue anyway? (y/N): " force_delete
            if [ "$force_delete" != "y" ] && [ "$force_delete" != "Y" ]; then
                echo "Deletion cancelled."
                return
            fi
        fi
        
        echo ""
        read -p "Are you sure you want to delete this account? (y/N): " confirm
        
        if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
            delete_single_mobile_account "$selected_user"
        else
            echo "Deletion cancelled."
        fi
    else
        echo "Invalid selection."
    fi
}

delete_single_mobile_account() {
    local username="$1"
    
    echo "Deleting mobile account: $username"
    
    # Create backup of user data
    local backup_dir="/var/backups/roundfleet/mobile_accounts"
    mkdir -p "$backup_dir"
    
    local backup_file="$backup_dir/${username}_backup_$(date +%Y%m%d_%H%M%S).txt"
    
    echo "Creating backup of user data..."
    dscl . -read "/Users/$username" > "$backup_file"
    
    # Delete user from directory services
    if dscl . -delete "/Users/$username" 2>/dev/null; then
        echo "User record deleted from directory services"
    else
        echo "Failed to delete user record from directory services"
        return 1
    fi
    
    # Remove user's home directory
    local home_dir=$(dscl . -read "/Users/$username" NFSHomeDirectory 2>/dev/null | cut -d: -f2 | xargs)
    if [ -d "$home_dir" ]; then
        read -p "Do you want to remove the home directory? (y/N): " remove_home
        if [ "$remove_home" = "y" ] || [ "$remove_home" = "Y" ]; then
            if rm -rf "$home_dir"; then
                echo "Home directory removed: $home_dir"
            else
                echo "Failed to remove home directory: $home_dir"
            fi
        else
            echo "Home directory preserved: $home_dir"
        fi
    fi
    
    echo "Successfully deleted mobile account: $username"
    echo "Backup created: $backup_file"
    echo "[$timestamp] Successfully deleted mobile account: $username" >> "$log_file"
}

delete_inactive_mobile_accounts() {
    echo "======================================="
    echo "Delete Inactive Mobile Accounts"
    echo "======================================="
    
    read -p "Enter number of days since last login to consider inactive (default: 30): " days_inactive
    days_inactive=${days_inactive:-30}
    
    echo "Searching for mobile accounts inactive for more than $days_inactive days..."
    
    local inactive_accounts=()
    local current_timestamp=$(date +%s)
    local cutoff_timestamp=$((current_timestamp - (days_inactive * 24 * 60 * 60)))
    
    for username in $(dscl . -list /Users | grep -v '^_'); do
        auth_authority=$(dscl . -read "/Users/$username" AuthenticationAuthority 2>/dev/null | grep "LocalCachedUser")
        
        if [ -n "$auth_authority" ]; then
            # Check last login
            local last_login=$(last -1 "$username" 2>/dev/null | head -1 | awk '{print $3, $4, $5, $6}')
            
            if [ -n "$last_login" ]; then
                local last_login_timestamp=$(date -j -f "%a %b %d %H:%M:%S %Y" "$last_login" +%s 2>/dev/null)
                
                if [ -n "$last_login_timestamp" ] && [ "$last_login_timestamp" -lt "$cutoff_timestamp" ]; then
                    inactive_accounts+=("$username")
                    echo "Inactive account found: $username (last login: $last_login)"
                fi
            else
                # No login record found - consider as inactive
                inactive_accounts+=("$username")
                echo "Inactive account found: $username (no login record)"
            fi
        fi
    done
    
    if [ ${#inactive_accounts[@]} -eq 0 ]; then
        echo "No inactive mobile accounts found."
        return
    fi
    
    echo ""
    echo "Found ${#inactive_accounts[@]} inactive mobile accounts."
    read -p "Do you want to delete all inactive accounts? (y/N): " confirm
    
    if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
        for username in "${inactive_accounts[@]}"; do
            echo "Deleting inactive account: $username"
            delete_single_mobile_account "$username"
        done
        echo "Inactive mobile accounts deletion completed."
    else
        echo "Deletion cancelled."
    fi
}

delete_mobile_accounts_by_criteria() {
    echo "======================================="
    echo "Delete Mobile Accounts by Criteria"
    echo "======================================="
    
    echo "Available criteria:"
    echo "1. By UID range"
    echo "2. By home directory pattern"
    echo "3. By real name pattern"
    echo "4. By last login date"
    echo ""
    read -p "Select criteria (1-4): " criteria
    
    case $criteria in
        1)
            delete_by_uid_range
            ;;
        2)
            delete_by_home_pattern
            ;;
        3)
            delete_by_name_pattern
            ;;
        4)
            delete_by_login_date
            ;;
        *)
            echo "Invalid criteria selected."
            ;;
    esac
}

delete_by_uid_range() {
    read -p "Enter minimum UID: " min_uid
    read -p "Enter maximum UID: " max_uid
    
    echo "Searching for mobile accounts with UID between $min_uid and $max_uid..."
    
    local matching_accounts=()
    
    for username in $(dscl . -list /Users | grep -v '^_'); do
        auth_authority=$(dscl . -read "/Users/$username" AuthenticationAuthority 2>/dev/null | grep "LocalCachedUser")
        
        if [ -n "$auth_authority" ]; then
            local uid=$(dscl . -read "/Users/$username" UniqueID 2>/dev/null | cut -d: -f2 | xargs)
            
            if [ "$uid" -ge "$min_uid" ] && [ "$uid" -le "$max_uid" ]; then
                matching_accounts+=("$username")
                echo "Found matching account: $username (UID: $uid)"
            fi
        fi
    done
    
    if [ ${#matching_accounts[@]} -eq 0 ]; then
        echo "No mobile accounts found matching the UID criteria."
        return
    fi
    
    echo ""
    echo "Found ${#matching_accounts[@]} matching mobile accounts."
    read -p "Do you want to delete all matching accounts? (y/N): " confirm
    
    if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
        for username in "${matching_accounts[@]}"; do
            delete_single_mobile_account "$username"
        done
        echo "Mobile accounts deletion by UID range completed."
    else
        echo "Deletion cancelled."
    fi
}

delete_by_home_pattern() {
    read -p "Enter home directory pattern (e.g., /Users/temp*): " pattern
    
    echo "Searching for mobile accounts with home directory matching pattern: $pattern"
    
    local matching_accounts=()
    
    for username in $(dscl . -list /Users | grep -v '^_'); do
        auth_authority=$(dscl . -read "/Users/$username" AuthenticationAuthority 2>/dev/null | grep "LocalCachedUser")
        
        if [ -n "$auth_authority" ]; then
            local home_dir=$(dscl . -read "/Users/$username" NFSHomeDirectory 2>/dev/null | cut -d: -f2 | xargs)
            
            if [[ "$home_dir" == $pattern ]]; then
                matching_accounts+=("$username")
                echo "Found matching account: $username (Home: $home_dir)"
            fi
        fi
    done
    
    if [ ${#matching_accounts[@]} -eq 0 ]; then
        echo "No mobile accounts found matching the home directory pattern."
        return
    fi
    
    echo ""
    echo "Found ${#matching_accounts[@]} matching mobile accounts."
    read -p "Do you want to delete all matching accounts? (y/N): " confirm
    
    if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
        for username in "${matching_accounts[@]}"; do
            delete_single_mobile_account "$username"
        done
        echo "Mobile accounts deletion by home directory pattern completed."
    else
        echo "Deletion cancelled."
    fi
}

delete_by_name_pattern() {
    read -p "Enter real name pattern (e.g., *Test*): " pattern
    
    echo "Searching for mobile accounts with real name matching pattern: $pattern"
    
    local matching_accounts=()
    
    for username in $(dscl . -list /Users | grep -v '^_'); do
        auth_authority=$(dscl . -read "/Users/$username" AuthenticationAuthority 2>/dev/null | grep "LocalCachedUser")
        
        if [ -n "$auth_authority" ]; then
            local real_name=$(dscl . -read "/Users/$username" RealName 2>/dev/null | cut -d: -f2 | xargs)
            
            if [[ "$real_name" == $pattern ]]; then
                matching_accounts+=("$username")
                echo "Found matching account: $username (Real Name: $real_name)"
            fi
        fi
    done
    
    if [ ${#matching_accounts[@]} -eq 0 ]; then
        echo "No mobile accounts found matching the real name pattern."
        return
    fi
    
    echo ""
    echo "Found ${#matching_accounts[@]} matching mobile accounts."
    read -p "Do you want to delete all matching accounts? (y/N): " confirm
    
    if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
        for username in "${matching_accounts[@]}"; do
            delete_single_mobile_account "$username"
        done
        echo "Mobile accounts deletion by real name pattern completed."
    else
        echo "Deletion cancelled."
    fi
}

delete_by_login_date() {
    read -p "Enter cutoff date (YYYY-MM-DD): " cutoff_date
    
    local cutoff_timestamp=$(date -j -f "%Y-%m-%d" "$cutoff_date" +%s 2>/dev/null)
    
    if [ -z "$cutoff_timestamp" ]; then
        echo "Invalid date format. Please use YYYY-MM-DD format."
        return
    fi
    
    echo "Searching for mobile accounts with last login before $cutoff_date..."
    
    local matching_accounts=()
    
    for username in $(dscl . -list /Users | grep -v '^_'); do
        auth_authority=$(dscl . -read "/Users/$username" AuthenticationAuthority 2>/dev/null | grep "LocalCachedUser")
        
        if [ -n "$auth_authority" ]; then
            local last_login=$(last -1 "$username" 2>/dev/null | head -1 | awk '{print $3, $4, $5, $6}')
            
            if [ -n "$last_login" ]; then
                local last_login_timestamp=$(date -j -f "%a %b %d %H:%M:%S %Y" "$last_login" +%s 2>/dev/null)
                
                if [ -n "$last_login_timestamp" ] && [ "$last_login_timestamp" -lt "$cutoff_timestamp" ]; then
                    matching_accounts+=("$username")
                    echo "Found matching account: $username (last login: $last_login)"
                fi
            else
                # No login record - consider as before cutoff
                matching_accounts+=("$username")
                echo "Found matching account: $username (no login record)"
            fi
        fi
    done
    
    if [ ${#matching_accounts[@]} -eq 0 ]; then
        echo "No mobile accounts found with last login before $cutoff_date."
        return
    fi
    
    echo ""
    echo "Found ${#matching_accounts[@]} matching mobile accounts."
    read -p "Do you want to delete all matching accounts? (y/N): " confirm
    
    if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
        for username in "${matching_accounts[@]}"; do
            delete_single_mobile_account "$username"
        done
        echo "Mobile accounts deletion by login date completed."
    else
        echo "Deletion cancelled."
    fi
}

export_mobile_account_report() {
    echo "======================================="
    echo "Export Mobile Account Report"
    echo "======================================="
    
    local report_file="/tmp/mobile_accounts_report_$(date +%Y%m%d_%H%M%S).txt"
    
    cat > "$report_file" << EOF
Roundfleet Mobile Account Report
Generated: $(date)
Device: $(scutil --get ComputerName)
macOS Version: $(sw_vers -productVersion)

Mobile Accounts Summary:
EOF
    
    local count=0
    for username in $(dscl . -list /Users | grep -v '^_'); do
        auth_authority=$(dscl . -read "/Users/$username" AuthenticationAuthority 2>/dev/null | grep "LocalCachedUser")
        
        if [ -n "$auth_authority" ]; then
            ((count++))
            
            echo "" >> "$report_file"
            echo "[$count] Username: $username" >> "$report_file"
            
            # Get detailed information
            local real_name=$(dscl . -read "/Users/$username" RealName 2>/dev/null | cut -d: -f2 | xargs)
            local uid=$(dscl . -read "/Users/$username" UniqueID 2>/dev/null | cut -d: -f2 | xargs)
            local home_dir=$(dscl . -read "/Users/$username" NFSHomeDirectory 2>/dev/null | cut -d: -f2 | xargs)
            local last_login=$(last -1 "$username" 2>/dev/null | head -1)
            
            echo "    Real Name: $real_name" >> "$report_file"
            echo "    UID: $uid" >> "$report_file"
            echo "    Home Directory: $home_dir" >> "$report_file"
            echo "    Last Login: $last_login" >> "$report_file"
            
            # Check if user is logged in
            if who | grep -q "^$username "; then
                echo "    Status: Currently logged in" >> "$report_file"
            else
                echo "    Status: Not logged in" >> "$report_file"
            fi
            
            # Check home directory size
            if [ -d "$home_dir" ]; then
                local dir_size=$(du -sh "$home_dir" 2>/dev/null | cut -f1)
                echo "    Home Directory Size: $dir_size" >> "$report_file"
            fi
        fi
    done
    
    echo "" >> "$report_file"
    echo "Total Mobile Accounts: $count" >> "$report_file"
    
    echo "Mobile account report exported to: $report_file"
}

restore_mobile_account_backup() {
    echo "======================================="
    echo "Restore Mobile Account Backup"
    echo "======================================="
    
    local backup_dir="/var/backups/roundfleet/mobile_accounts"
    
    if [ ! -d "$backup_dir" ]; then
        echo "No backup directory found: $backup_dir"
        return
    fi
    
    echo "Available backups:"
    ls -la "$backup_dir"/*.txt 2>/dev/null || echo "No backup files found."
    
    echo ""
    read -p "Enter the backup filename to restore: " backup_file
    
    if [ -f "$backup_dir/$backup_file" ]; then
        echo "Backup file found: $backup_dir/$backup_file"
        echo "Note: This feature shows backup content for reference."
        echo "Manual restoration may be required for complex scenarios."
        echo ""
        cat "$backup_dir/$backup_file"
    else
        echo "Backup file not found: $backup_dir/$backup_file"
    fi
}

# Execute selective management
selective_mobile_account_manager

Enterprise Mobile Account Management

Automated Mobile Account Cleanup

#!/bin/bash

# Automated mobile account cleanup for enterprise environments
# Usage: ./automated_mobile_cleanup.sh

automated_mobile_cleanup() {
    local config_file="/etc/roundfleet/mobile_cleanup_config.conf"
    local log_file="/var/log/roundfleet_automated_cleanup.log"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    
    # Check if running as root
    if [ "$EUID" -ne 0 ]; then
        echo "Error: This script must be run as root"
        exit 1
    fi
    
    # Create configuration if it doesn't exist
    if [ ! -f "$config_file" ]; then
        create_cleanup_config
    fi
    
    source "$config_file"
    
    echo "[$timestamp] Automated mobile account cleanup started" >> "$log_file"
    
    # Execute cleanup based on configuration
    execute_automated_cleanup
}

create_cleanup_config() {
    mkdir -p /etc/roundfleet
    
    cat > "/etc/roundfleet/mobile_cleanup_config.conf" << 'EOF'
# Roundfleet Automated Mobile Account Cleanup Configuration

# Organization settings
ORGANIZATION_NAME="Roundfleet Organization"
IT_CONTACT="[email protected]"

# Cleanup criteria
CLEANUP_INACTIVE_DAYS="30"
CLEANUP_ENABLED="true"
PRESERVE_ADMIN_ACCOUNTS="true"

# Safety settings
REQUIRE_CONFIRMATION="true"
CREATE_BACKUP="true"
PRESERVE_HOME_DATA="false"
SKIP_LOGGED_IN_USERS="true"

# Notification settings
SEND_NOTIFICATIONS="true"
NOTIFICATION_EMAIL="[email protected]"

# Scheduling
ENABLE_SCHEDULED_CLEANUP="false"
CLEANUP_SCHEDULE="weekly"
CLEANUP_TIME="02:00"

# Logging
ENABLE_DETAILED_LOGGING="true"
LOG_RETENTION_DAYS="90"
EOF
    
    echo "Cleanup configuration created at /etc/roundfleet/mobile_cleanup_config.conf"
}

execute_automated_cleanup() {
    echo "[$timestamp] Executing automated mobile account cleanup" >> "$log_file"
    
    # Check if cleanup is enabled
    if [ "$CLEANUP_ENABLED" != "true" ]; then
        echo "[$timestamp] Automated cleanup is disabled" >> "$log_file"
        echo "Automated cleanup is disabled in configuration."
        return
    fi
    
    # Display cleanup configuration
    echo "======================================="
    echo "Roundfleet Automated Mobile Account Cleanup"
    echo "======================================="
    echo "Organization: $ORGANIZATION_NAME"
    echo "Cleanup inactive accounts older than: $CLEANUP_INACTIVE_DAYS days"
    echo "Preserve admin accounts: $PRESERVE_ADMIN_ACCOUNTS"
    echo "Create backup: $CREATE_BACKUP"
    echo "Skip logged in users: $SKIP_LOGGED_IN_USERS"
    echo ""
    
    # Require confirmation if enabled
    if [ "$REQUIRE_CONFIRMATION" = "true" ]; then
        read -p "Do you want to proceed with automated cleanup? (y/N): " confirm
        if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
            echo "[$timestamp] Automated cleanup cancelled by user" >> "$log_file"
            echo "Automated cleanup cancelled."
            return
        fi
    fi
    
    # Find accounts to cleanup
    local accounts_to_cleanup=()
    local current_timestamp=$(date +%s)
    local cutoff_timestamp=$((current_timestamp - (CLEANUP_INACTIVE_DAYS * 24 * 60 * 60)))
    
    echo "Scanning for mobile accounts to cleanup..."
    
    for username in $(dscl . -list /Users | grep -v '^_'); do
        auth_authority=$(dscl . -read "/Users/$username" AuthenticationAuthority 2>/dev/null | grep "LocalCachedUser")
        
        if [ -n "$auth_authority" ]; then
            local should_cleanup=true
            
            # Check if user is admin (if preservation is enabled)
            if [ "$PRESERVE_ADMIN_ACCOUNTS" = "true" ]; then
                if dscl . -read "/Groups/admin" GroupMembership 2>/dev/null | grep -q "$username"; then
                    echo "Skipping admin account: $username"
                    echo "[$timestamp] Skipped admin account: $username" >> "$log_file"
                    should_cleanup=false
                fi
            fi
            
            # Check if user is logged in (if skip is enabled)
            if [ "$SKIP_LOGGED_IN_USERS" = "true" ] && who | grep -q "^$username "; then
                echo "Skipping logged in user: $username"
                echo "[$timestamp] Skipped logged in user: $username" >> "$log_file"
                should_cleanup=false
            fi
            
            # Check last login date
            if [ "$should_cleanup" = true ]; then
                local last_login=$(last -1 "$username" 2>/dev/null | head -1 | awk '{print $3, $4, $5, $6}')
                
                if [ -n "$last_login" ]; then
                    local last_login_timestamp=$(date -j -f "%a %b %d %H:%M:%S %Y" "$last_login" +%s 2>/dev/null)
                    
                    if [ -n "$last_login_timestamp" ] && [ "$last_login_timestamp" -lt "$cutoff_timestamp" ]; then
                        accounts_to_cleanup+=("$username")
                        echo "Account marked for cleanup: $username (last login: $last_login)"
                    fi
                else
                    # No login record - consider for cleanup
                    accounts_to_cleanup+=("$username")
                    echo "Account marked for cleanup: $username (no login record)"
                fi
            fi
        fi
    done
    
    if [ ${#accounts_to_cleanup[@]} -eq 0 ]; then
        echo "No mobile accounts found that meet cleanup criteria."
        echo "[$timestamp] No mobile accounts found for cleanup" >> "$log_file"
        return
    fi
    
    echo ""
    echo "Found ${#accounts_to_cleanup[@]} mobile accounts for cleanup:"
    for account in "${accounts_to_cleanup[@]}"; do
        echo "  - $account"
    done
    
    # Create backup if enabled
    if [ "$CREATE_BACKUP" = "true" ]; then
        create_automated_backup "${accounts_to_cleanup[@]}"
    fi
    
    # Cleanup accounts
    local success_count=0
    local failure_count=0
    
    echo ""
    echo "Starting automated cleanup..."
    
    for username in "${accounts_to_cleanup[@]}"; do
        echo "Processing: $username"
        
        # Delete user from directory services
        if dscl . -delete "/Users/$username" 2>/dev/null; then
            echo "  Deleted user record from directory services"
            
            # Handle home directory based on configuration
            local home_dir=$(dscl . -read "/Users/$username" NFSHomeDirectory 2>/dev/null | cut -d: -f2 | xargs)
            
            if [ -d "$home_dir" ]; then
                if [ "$PRESERVE_HOME_DATA" = "true" ]; then
                    echo "  Preserved home directory: $home_dir"
                else
                    if rm -rf "$home_dir" 2>/dev/null; then
                        echo "  Removed home directory: $home_dir"
                    else
                        echo "  Warning: Failed to remove home directory: $home_dir"
                    fi
                fi
            fi
            
            echo "  Successfully cleaned up account: $username"
            echo "[$timestamp] Successfully cleaned up account: $username" >> "$log_file"
            ((success_count++))
        else
            echo "  Failed to cleanup account: $username"
            echo "[$timestamp] Failed to cleanup account: $username" >> "$log_file"
            ((failure_count++))
        fi
    done
    
    # Generate cleanup summary
    echo ""
    echo "======================================="
    echo "Automated Cleanup Summary"
    echo "======================================="
    echo "Total accounts processed: ${#accounts_to_cleanup[@]}"
    echo "Successfully cleaned up: $success_count"
    echo "Failed to cleanup: $failure_count"
    echo "Cleanup completed at: $(date)"
    
    echo "[$timestamp] Automated cleanup completed - Success: $success_count, Failed: $failure_count" >> "$log_file"
    
    # Send notification if enabled
    if [ "$SEND_NOTIFICATIONS" = "true" ]; then
        send_cleanup_notification "$success_count" "$failure_count"
    fi
    
    echo ""
    echo "Note: Please restart the device for changes to take full effect."
}

create_automated_backup() {
    local accounts=("$@")
    local backup_dir="/var/backups/roundfleet/automated_cleanup"
    local backup_file="$backup_dir/cleanup_backup_$(date +%Y%m%d_%H%M%S).txt"
    
    mkdir -p "$backup_dir"
    
    echo "Creating backup of accounts to be cleaned up..."
    
    cat > "$backup_file" << EOF
Roundfleet Automated Cleanup Backup
Generated: $(date)
Device: $(scutil --get ComputerName)
Organization: $ORGANIZATION_NAME
Cleanup Criteria: Inactive for $CLEANUP_INACTIVE_DAYS days

Accounts to be cleaned up:
EOF
    
    for username in "${accounts[@]}"; do
        echo "" >> "$backup_file"
        echo "Username: $username" >> "$backup_file"
        dscl . -read "/Users/$username" >> "$backup_file" 2>/dev/null
        echo "---" >> "$backup_file"
    done
    
    echo "Backup created: $backup_file"
    echo "[$timestamp] Automated cleanup backup created: $backup_file" >> "$log_file"
}

send_cleanup_notification() {
    local success_count=$1
    local failure_count=$2
    
    local notification_subject="Roundfleet Mobile Account Cleanup Report"
    local notification_body="Automated mobile account cleanup completed.

Device: $(scutil --get ComputerName)
Organization: $ORGANIZATION_NAME
Cleanup Date: $(date)

Results:
- Successfully cleaned up: $success_count accounts
- Failed to cleanup: $failure_count accounts
- Total processed: $((success_count + failure_count)) accounts

For detailed logs, check: /var/log/roundfleet_automated_cleanup.log

Contact: $IT_CONTACT"
    
    # Use osascript to display notification (for local notifications)
    osascript -e "display notification \"Cleanup completed: $success_count success, $failure_count failed\" with title \"Roundfleet Mobile Account Cleanup\""
    
    echo "[$timestamp] Cleanup notification sent" >> "$log_file"
}

# Execute automated cleanup
automated_mobile_cleanup

Troubleshooting and Best Practices

Common Issues and Solutions

  1. Permission Errors: Always run scripts as root using sudo
  2. Logged-in Users: Check for active sessions before deletion
  3. Directory Services: Verify mobile account identification using LocalCachedUser attribute
  4. Home Directory Protection: Create backups before removing home directories
  5. Network Accounts: Ensure network connectivity for directory service operations

Best Practices

  • Test First: Always test scripts in controlled environments
  • Create Backups: Maintain backups of user data before deletion
  • Log Operations: Keep detailed logs of all account operations
  • User Communication: Notify users before account cleanup
  • Schedule Maintenance: Perform cleanup during maintenance windows

Conclusion

Mobile account management is crucial for maintaining clean and secure macOS environments. These scripts provide comprehensive solutions for deleting mobile accounts, from simple cleanup to enterprise-grade automation. Always ensure proper testing and backup procedures before implementing in production environments.

Delete Files by Size on macOS

Learn how to find and delete large files on Mac devices based on size criteria. This helps free up storage space and improve device performance when storage is running low.

List Large Files

Find and list files larger than a specified size:

#!/bin/bash

# Get current user context
CURRENT_USER=$(stat -f "%Su" /dev/console)
CURRENT_USER_UID=$(id -u "$CURRENT_USER")

# Configuration
SEARCH_PATH="/Users/$CURRENT_USER/Desktop"
SIZE_LIMIT="100"  # Size in kilobytes

echo "Searching for files larger than ${SIZE_LIMIT}KB in: $SEARCH_PATH"

# List large files
launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" \
    find "$SEARCH_PATH" -type f -size +${SIZE_LIMIT}k -print

Delete Large Files

Find and delete files larger than specified size:

#!/bin/bash

# Get current user context
CURRENT_USER=$(stat -f "%Su" /dev/console)
CURRENT_USER_UID=$(id -u "$CURRENT_USER")

# Configuration
SEARCH_PATH="/Users/$CURRENT_USER/Downloads"
SIZE_LIMIT="50"  # Size in kilobytes

echo "âš ī¸  WARNING: This will permanently delete files larger than ${SIZE_LIMIT}KB"
echo "Searching in: $SEARCH_PATH"

# List and delete large files
launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" \
    find "$SEARCH_PATH" -type f -size +${SIZE_LIMIT}k -print -delete

echo "✅ Large files deleted successfully"

Enhanced File Cleanup Script

Script with safety checks and detailed reporting:

#!/bin/bash

# Function to cleanup large files safely
cleanup_large_files() {
    local search_path="$1"
    local size_limit="$2"
    local dry_run="${3:-false}"
    
    # Get current user context
    local current_user=$(stat -f "%Su" /dev/console)
    local current_user_uid=$(id -u "$current_user")
    
    if [[ ! -d "$search_path" ]]; then
        echo "❌ Error: Directory not found: $search_path"
        return 1
    fi
    
    echo "=== Large Files Cleanup ==="
    echo "📁 Path: $search_path"
    echo "📏 Size limit: ${size_limit}KB"
    echo "👤 User: $current_user"
    echo "🔍 Dry run: $dry_run"
    echo "=========================="
    
    # Find large files
    local files_command="find '$search_path' -type f -size +${size_limit}k"
    
    if [[ "$dry_run" == "true" ]]; then
        echo "📋 Files that would be deleted:"
        launchctl asuser $current_user_uid sudo -iu "$current_user" \
            bash -c "$files_command -ls"
        
        local count=$(launchctl asuser $current_user_uid sudo -iu "$current_user" \
            bash -c "$files_command | wc -l")
        echo "📊 Total files found: $count"
    else
        echo "đŸ—‘ī¸  Deleting large files..."
        launchctl asuser $current_user_uid sudo -iu "$current_user" \
            bash -c "$files_command -print -delete"
        echo "✅ Cleanup completed"
    fi
}

# Configuration
SEARCH_PATH="/Users/$(stat -f "%Su" /dev/console)/Downloads"
SIZE_LIMIT="100"
DRY_RUN="true"  # Set to "false" to actually delete files

# Run cleanup
cleanup_large_files "$SEARCH_PATH" "$SIZE_LIMIT" "$DRY_RUN"

Enterprise Storage Management

Comprehensive storage cleanup for enterprise environments:

#!/bin/bash

# Enterprise storage cleanup configuration
CLEANUP_LOCATIONS=(
    "/Users/*/Downloads:50"
    "/Users/*/Desktop:100"
    "/Users/*/Documents:200"
    "/tmp:10"
)

# Function to format file size
format_size() {
    local size=$1
    if [[ $size -gt 1048576 ]]; then
        echo "$(( size / 1048576 ))GB"
    elif [[ $size -gt 1024 ]]; then
        echo "$(( size / 1024 ))MB"
    else
        echo "${size}KB"
    fi
}

# Function to get directory size
get_directory_size() {
    local dir="$1"
    if [[ -d "$dir" ]]; then
        du -sk "$dir" 2>/dev/null | cut -f1
    else
        echo "0"
    fi
}

# Enterprise cleanup execution
echo "đŸĸ Roundfleet Enterprise Storage Cleanup"
echo "======================================"
echo "Generated: $(date)"
echo "Device: $(hostname)"

total_freed=0
current_user=$(stat -f "%Su" /dev/console)
current_user_uid=$(id -u "$current_user")

for location_config in "${CLEANUP_LOCATIONS[@]}"; do
    IFS=':' read -r location_pattern size_limit <<< "$location_config"
    
    echo ""
    echo "📁 Processing: $location_pattern (>${size_limit}KB)"
    
    # Expand pattern for user directories
    for location in $location_pattern; do
        if [[ -d "$location" ]]; then
            echo "  🔍 Scanning: $location"
            
            # Get before size
            before_size=$(get_directory_size "$location")
            
            # Find and delete large files
            deleted_files=$(launchctl asuser $current_user_uid sudo -iu "$current_user" \
                find "$location" -type f -size +${size_limit}k -print -delete 2>/dev/null | wc -l)
            
            # Get after size
            after_size=$(get_directory_size "$location")
            freed=$((before_size - after_size))
            total_freed=$((total_freed + freed))
            
            if [[ $deleted_files -gt 0 ]]; then
                echo "  ✅ Deleted: $deleted_files files"
                echo "  💾 Freed: $(format_size $freed)"
            else
                echo "  â„šī¸  No large files found"
            fi
        fi
    done
done

echo ""
echo "======================================"
echo "📊 Summary:"
echo "  Total space freed: $(format_size $total_freed)"
echo "  Cleanup completed: $(date)"

if [[ $total_freed -gt 0 ]]; then
    echo "✅ Storage cleanup successful"
else
    echo "â„šī¸  No cleanup needed - storage usage is optimal"
fi

Safe Cleanup with Backup Option

Script with optional backup before deletion:

#!/bin/bash

# Function to backup large files before deletion
backup_and_delete() {
    local search_path="$1"
    local size_limit="$2"
    local backup_enabled="${3:-false}"
    
    local current_user=$(stat -f "%Su" /dev/console)
    local current_user_uid=$(id -u "$current_user")
    local backup_dir="/tmp/roundfleet_backup_$(date +%Y%m%d_%H%M%S)"
    
    echo "🔄 Processing: $search_path"
    
    if [[ "$backup_enabled" == "true" ]]; then
        echo "đŸ“Ļ Creating backup directory: $backup_dir"
        mkdir -p "$backup_dir"
        
        # Find and backup large files
        launchctl asuser $current_user_uid sudo -iu "$current_user" \
            find "$search_path" -type f -size +${size_limit}k -exec cp {} "$backup_dir/" \;
        
        echo "✅ Files backed up to: $backup_dir"
    fi
    
    # Delete large files
    local deleted_count=$(launchctl asuser $current_user_uid sudo -iu "$current_user" \
        find "$search_path" -type f -size +${size_limit}k -print -delete | wc -l)
    
    echo "đŸ—‘ī¸  Deleted $deleted_count large files"
    
    if [[ "$backup_enabled" == "true" && $deleted_count -gt 0 ]]; then
        echo "💡 Backup location: $backup_dir"
        echo "⏰ Backup will be auto-removed in 7 days"
        
        # Schedule backup cleanup (requires launchd or cron)
        echo "find '$backup_dir' -type f -mtime +7 -delete" > /tmp/cleanup_backup.sh
        chmod +x /tmp/cleanup_backup.sh
    fi
}

# Configuration
SEARCH_PATH="/Users/$(stat -f "%Su" /dev/console)/Downloads"
SIZE_LIMIT="100"
BACKUP_ENABLED="true"

# Execute safe cleanup
backup_and_delete "$SEARCH_PATH" "$SIZE_LIMIT" "$BACKUP_ENABLED"

Usage with Roundfleet

  1. Configure search path and size limit in the script
  2. Choose between dry-run and actual deletion modes
  3. Consider enabling backup option for safety
  4. Deploy through Roundfleet's remote script execution
  5. Monitor results and freed space in action history

Size Units and Examples

UnitDescriptionExample Use Case
+50kFiles larger than 50KBSmall document cleanup
+10MFiles larger than 10MBMedia file cleanup
+100MFiles larger than 100MBLarge file cleanup
+1GFiles larger than 1GBArchive cleanup

Common Cleanup Targets

DirectoryTypical Size LimitPurpose
Downloads50MBRemove large downloads
Desktop100MBClean desktop files
Documents200MBArchive old documents
Temp folders10MBSystem cleanup

Safety Considerations

âš ī¸ CRITICAL WARNING: Files deleted with these scripts are permanently removed and cannot be recovered from Trash.

  • Test first: Always run with dry-run mode enabled initially
  • Backup important data: Consider backup option for valuable files
  • Verify paths: Double-check search directories before execution
  • User context: Scripts run in current user context for security

Troubleshooting

Permission denied: Ensure proper user context with launchctl asuser Directory not found: Verify search paths exist before running No files found: Check size limits and directory contents


Note: Always validate scripts on test systems before bulk deployment. Permanent file deletion requires careful consideration and backup planning.