Tutorial

Novas atualizações e melhorias para a Macfleet.

Aviso importante

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

File and Folder Creation Management on macOS

Efficiently manage file and folder creation operations across your MacFleet deployment with enterprise-grade template management, permission control, and comprehensive audit capabilities. This tutorial transforms basic touch and mkdir commands into robust filesystem provisioning solutions.

Understanding Enterprise File Creation Operations

Enterprise file creation requires more than basic filesystem operations, demanding:

  • Template management for standardized file and folder structures
  • Permission control to enforce security policies
  • Content validation for created files and directories
  • Audit logging for compliance tracking
  • Automated provisioning for user onboarding
  • Policy enforcement for naming conventions and structure

Core Creation Operations

Basic File Creation

#!/bin/bash

# Simple file creation with validation
create_file() {
    local file_path="$1"
    local content="${2:-}"
    
    # Validate parent directory exists
    local parent_dir=$(dirname "$file_path")
    if [[ ! -d "$parent_dir" ]]; then
        echo "Error: Parent directory '$parent_dir' does not exist"
        return 1
    fi
    
    # Create file
    if touch "$file_path"; then
        # Add content if provided
        if [[ -n "$content" ]]; then
            echo "$content" > "$file_path"
        fi
        echo "Successfully created file '$file_path'"
        return 0
    else
        echo "Failed to create file '$file_path'"
        return 1
    fi
}

# Usage example
# create_file "/Users/admin/document.txt" "Initial content"

Basic Directory Creation

#!/bin/bash

# Directory creation with validation
create_directory() {
    local dir_path="$1"
    local permissions="${2:-755}"
    
    # Create directory with parents if needed
    if mkdir -p "$dir_path"; then
        # Set permissions
        chmod "$permissions" "$dir_path"
        echo "Successfully created directory '$dir_path'"
        return 0
    else
        echo "Failed to create directory '$dir_path'"
        return 1
    fi
}

# Usage example
# create_directory "/Users/admin/project" "755"

Enterprise Creation Management System

#!/bin/bash

# MacFleet Enterprise File Creation Management System
# Comprehensive file and folder creation with enterprise features

# Configuration
SCRIPT_NAME="MacFleet Creation Manager"
VERSION="1.0.0"
LOG_FILE="/var/log/macfleet_creation_operations.log"
TEMPLATE_DIR="/etc/macfleet/templates"
POLICY_DIR="/etc/macfleet/policies"
TEMP_DIR="/tmp/macfleet_creation"
DEFAULT_FILE_PERMISSIONS="644"
DEFAULT_DIR_PERMISSIONS="755"
RESTRICTED_PATHS=("/System" "/usr/bin" "/usr/sbin" "/private/var" "/Library/LaunchDaemons")
ALLOWED_EXTENSIONS=(".txt" ".md" ".pdf" ".docx" ".xlsx" ".pptx" ".csv" ".json" ".xml" ".log")
MAX_FILENAME_LENGTH=255
MAX_PATH_DEPTH=20
BUSINESS_HOURS_START=9
BUSINESS_HOURS_END=17

# Create necessary directories
mkdir -p "$TEMP_DIR"
mkdir -p "$TEMPLATE_DIR"
mkdir -p "$POLICY_DIR"
mkdir -p "$(dirname "$LOG_FILE")"

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

# Check if current time is within business hours
is_business_hours() {
    local current_hour=$(date +%H)
    if [[ $current_hour -ge $BUSINESS_HOURS_START && $current_hour -lt $BUSINESS_HOURS_END ]]; then
        return 0
    else
        return 1
    fi
}

# Validate file extension
is_allowed_extension() {
    local file="$1"
    local extension="${file##*.}"
    extension=".$extension"
    
    for allowed in "${ALLOWED_EXTENSIONS[@]}"; do
        if [[ "$extension" == "$allowed" ]]; then
            return 0
        fi
    done
    return 1
}

# Check if path is restricted
is_restricted_path() {
    local path="$1"
    for restricted in "${RESTRICTED_PATHS[@]}"; do
        if [[ "$path" == "$restricted"* ]]; then
            return 0
        fi
    done
    return 1
}

# Validate naming conventions
validate_naming_convention() {
    local name="$1"
    local type="$2"  # "file" or "directory"
    
    # Check length
    if [[ ${#name} -gt $MAX_FILENAME_LENGTH ]]; then
        log_operation "ERROR" "Name too long (${#name} > $MAX_FILENAME_LENGTH): $name"
        return 1
    fi
    
    # Check for invalid characters
    if [[ "$name" =~ [^a-zA-Z0-9._-] ]]; then
        log_operation "WARNING" "Name contains special characters: $name"
    fi
    
    # Check for reserved names
    local reserved_names=("CON" "PRN" "AUX" "NUL" "COM1" "COM2" "LPT1" "LPT2")
    local base_name=$(basename "$name" | tr '[:lower:]' '[:upper:]')
    
    for reserved in "${reserved_names[@]}"; do
        if [[ "$base_name" == "$reserved" ]]; then
            log_operation "ERROR" "Reserved name not allowed: $name"
            return 1
        fi
    done
    
    return 0
}

# Check path depth
validate_path_depth() {
    local path="$1"
    local depth=$(echo "$path" | tr '/' '\n' | wc -l)
    
    if [[ $depth -gt $MAX_PATH_DEPTH ]]; then
        log_operation "ERROR" "Path depth too deep ($depth > $MAX_PATH_DEPTH): $path"
        return 1
    fi
    
    return 0
}

# Load file template
load_file_template() {
    local template_name="$1"
    local template_file="$TEMPLATE_DIR/$template_name.template"
    
    if [[ -f "$template_file" ]]; then
        cat "$template_file"
        return 0
    else
        log_operation "WARNING" "Template not found: $template_name"
        return 1
    fi
}

# Apply variable substitution to template
apply_template_variables() {
    local content="$1"
    local variables="$2"  # JSON string with variables
    
    # Basic variable substitution
    content=$(echo "$content" | sed "s/{{DATE}}/$(date '+%Y-%m-%d')/g")
    content=$(echo "$content" | sed "s/{{TIME}}/$(date '+%H:%M:%S')/g")
    content=$(echo "$content" | sed "s/{{USER}}/$(whoami)/g")
    content=$(echo "$content" | sed "s/{{HOSTNAME}}/$(hostname)/g")
    
    # Custom variables from JSON (simplified)
    if [[ -n "$variables" ]]; then
        # This would be enhanced with proper JSON parsing in production
        log_operation "INFO" "Applying custom template variables"
    fi
    
    echo "$content"
}

# Create directory structure from template
create_structure_from_template() {
    local template_name="$1"
    local base_path="$2"
    local variables="${3:-}"
    
    local structure_file="$TEMPLATE_DIR/structures/$template_name.json"
    
    if [[ ! -f "$structure_file" ]]; then
        log_operation "ERROR" "Structure template not found: $template_name"
        return 1
    fi
    
    log_operation "INFO" "Creating structure from template: $template_name at $base_path"
    
    # This would parse JSON structure and create directories/files
    # Simplified implementation for demonstration
    mkdir -p "$base_path"
    
    return 0
}

# Enhanced file creation with enterprise features
enterprise_create_file() {
    local file_path="$1"
    local template_name="${2:-}"
    local permissions="${3:-$DEFAULT_FILE_PERMISSIONS}"
    local variables="${4:-}"
    
    local operation_id=$(date +%s)
    log_operation "INFO" "Starting file creation operation [$operation_id]: $file_path"
    
    # Pre-flight validations
    local filename=$(basename "$file_path")
    local parent_dir=$(dirname "$file_path")
    
    # Validate naming conventions
    if ! validate_naming_convention "$filename" "file"; then
        log_operation "ERROR" "Naming convention validation failed: $filename"
        return 1
    fi
    
    # Validate path depth
    if ! validate_path_depth "$file_path"; then
        return 1
    fi
    
    # Check if path is restricted
    if is_restricted_path "$file_path"; then
        log_operation "SECURITY" "Blocked creation in restricted path: $file_path"
        return 1
    fi
    
    # Validate file extension
    if ! is_allowed_extension "$file_path"; then
        log_operation "SECURITY" "Blocked file with unauthorized extension: $file_path"
        return 1
    fi
    
    # Check if file already exists
    if [[ -f "$file_path" ]]; then
        log_operation "WARNING" "File already exists: $file_path"
        return 1
    fi
    
    # Create parent directory if it doesn't exist
    if [[ ! -d "$parent_dir" ]]; then
        if ! mkdir -p "$parent_dir"; then
            log_operation "ERROR" "Failed to create parent directory: $parent_dir"
            return 1
        fi
        log_operation "INFO" "Created parent directory: $parent_dir"
    fi
    
    # Load template content if specified
    local content=""
    if [[ -n "$template_name" ]]; then
        content=$(load_file_template "$template_name")
        if [[ $? -eq 0 ]]; then
            content=$(apply_template_variables "$content" "$variables")
            log_operation "INFO" "Applied template: $template_name"
        else
            log_operation "WARNING" "Failed to load template, creating empty file"
        fi
    fi
    
    # Create the file
    if touch "$file_path"; then
        # Add content if available
        if [[ -n "$content" ]]; then
            echo "$content" > "$file_path"
        fi
        
        # Set permissions
        chmod "$permissions" "$file_path"
        
        # Set ownership (if running as root)
        if [[ $EUID -eq 0 ]]; then
            local target_user=$(stat -f "%Su" "$parent_dir")
            local target_group=$(stat -f "%Sg" "$parent_dir")
            chown "$target_user:$target_group" "$file_path"
        fi
        
        log_operation "SUCCESS" "File created successfully [$operation_id]: $file_path"
        log_operation "AUDIT" "File created: $file_path (permissions: $permissions)"
        
        return 0
    else
        log_operation "ERROR" "Failed to create file [$operation_id]: $file_path"
        return 1
    fi
}

# Enhanced directory creation with enterprise features
enterprise_create_directory() {
    local dir_path="$1"
    local template_name="${2:-}"
    local permissions="${3:-$DEFAULT_DIR_PERMISSIONS}"
    local create_parents="${4:-true}"
    
    local operation_id=$(date +%s)
    log_operation "INFO" "Starting directory creation operation [$operation_id]: $dir_path"
    
    # Pre-flight validations
    local dirname=$(basename "$dir_path")
    
    # Validate naming conventions
    if ! validate_naming_convention "$dirname" "directory"; then
        log_operation "ERROR" "Naming convention validation failed: $dirname"
        return 1
    fi
    
    # Validate path depth
    if ! validate_path_depth "$dir_path"; then
        return 1
    fi
    
    # Check if path is restricted
    if is_restricted_path "$dir_path"; then
        log_operation "SECURITY" "Blocked creation in restricted path: $dir_path"
        return 1
    fi
    
    # Check if directory already exists
    if [[ -d "$dir_path" ]]; then
        log_operation "WARNING" "Directory already exists: $dir_path"
        return 1
    fi
    
    # Create the directory
    local mkdir_options=""
    if [[ "$create_parents" == "true" ]]; then
        mkdir_options="-p"
    fi
    
    if mkdir $mkdir_options "$dir_path"; then
        # Set permissions
        chmod "$permissions" "$dir_path"
        
        # Set ownership (if running as root)
        if [[ $EUID -eq 0 ]]; then
            local parent_dir=$(dirname "$dir_path")
            if [[ -d "$parent_dir" ]]; then
                local target_user=$(stat -f "%Su" "$parent_dir")
                local target_group=$(stat -f "%Sg" "$parent_dir")
                chown "$target_user:$target_group" "$dir_path"
            fi
        fi
        
        # Apply template structure if specified
        if [[ -n "$template_name" ]]; then
            create_structure_from_template "$template_name" "$dir_path"
        fi
        
        log_operation "SUCCESS" "Directory created successfully [$operation_id]: $dir_path"
        log_operation "AUDIT" "Directory created: $dir_path (permissions: $permissions)"
        
        return 0
    else
        log_operation "ERROR" "Failed to create directory [$operation_id]: $dir_path"
        return 1
    fi
}

# Bulk creation operations
bulk_create_operation() {
    local operation_type="$1"  # "file" or "directory"
    local items_file="$2"      # File containing creation specifications
    local template_name="${3:-}"
    
    if [[ ! -f "$items_file" ]]; then
        log_operation "ERROR" "Items file not found: $items_file"
        return 1
    fi
    
    local total_items=$(grep -v '^#\|^$' "$items_file" | wc -l)
    local current_item=0
    local success_count=0
    local failure_count=0
    
    log_operation "INFO" "Starting bulk creation operation - Total items: $total_items"
    
    while IFS='|' read -r path permissions variables; do
        # Skip empty lines and comments
        [[ -z "$path" || "$path" =~ ^#.* ]] && continue
        
        ((current_item++))
        
        # Trim whitespace
        path=$(echo "$path" | xargs)
        permissions=$(echo "$permissions" | xargs)
        variables=$(echo "$variables" | xargs)
        
        echo "Processing [$current_item/$total_items]: $(basename "$path")"
        
        case "$operation_type" in
            "file")
                if enterprise_create_file "$path" "$template_name" "$permissions" "$variables"; then
                    ((success_count++))
                else
                    ((failure_count++))
                fi
                ;;
            "directory")
                if enterprise_create_directory "$path" "$template_name" "$permissions"; then
                    ((success_count++))
                else
                    ((failure_count++))
                fi
                ;;
        esac
        
        # Progress update
        local progress=$((current_item * 100 / total_items))
        echo "Progress: $progress% ($success_count successful, $failure_count failed)"
        
    done < "$items_file"
    
    log_operation "SUCCESS" "Bulk creation completed - Success: $success_count, Failed: $failure_count"
    return $failure_count
}

# User onboarding automation
create_user_workspace() {
    local username="$1"
    local user_type="${2:-standard}"  # standard, admin, developer
    local base_path="/Users/$username"
    
    log_operation "INFO" "Creating workspace for user: $username (type: $user_type)"
    
    # Create user directories
    local directories=(
        "$base_path/Documents"
        "$base_path/Desktop"
        "$base_path/Downloads"
        "$base_path/Pictures"
        "$base_path/Movies"
        "$base_path/Music"
    )
    
    # Add type-specific directories
    case "$user_type" in
        "developer")
            directories+=("$base_path/Projects" "$base_path/Scripts" "$base_path/Tools")
            ;;
        "admin")
            directories+=("$base_path/Admin" "$base_path/Logs" "$base_path/Configs")
            ;;
    esac
    
    # Create directories
    for dir in "${directories[@]}"; do
        if enterprise_create_directory "$dir" "" "755"; then
            log_operation "INFO" "Created user directory: $dir"
        fi
    done
    
    # Create default files
    local files=(
        "$base_path/Desktop/Welcome.txt|welcome|644"
        "$base_path/Documents/README.txt|readme|644"
    )
    
    for file_spec in "${files[@]}"; do
        IFS='|' read -r file_path template perms <<< "$file_spec"
        if enterprise_create_file "$file_path" "$template" "$perms"; then
            log_operation "INFO" "Created user file: $file_path"
        fi
    done
    
    log_operation "SUCCESS" "User workspace created for: $username"
}

# Generate creation report
generate_creation_report() {
    local report_file="/tmp/macfleet_creation_report_$(date +%Y%m%d_%H%M%S).txt"
    
    {
        echo "MacFleet Creation Operations Report"
        echo "Generated: $(date)"
        echo "Hostname: $(hostname)"
        echo "User: $(whoami)"
        echo "================================="
        echo ""
        
        echo "Recent Creation Operations (Last 24 hours):"
        if [[ -f "$LOG_FILE" ]]; then
            local yesterday=$(date -v-1d '+%Y-%m-%d')
            grep "$yesterday\|$(date '+%Y-%m-%d')" "$LOG_FILE" | grep -E "(AUDIT|SUCCESS)" | tail -50
        else
            echo "No log file found"
        fi
        
        echo ""
        echo "Creation Statistics:"
        if [[ -f "$LOG_FILE" ]]; then
            echo "Total Operations: $(grep -c "creation operation" "$LOG_FILE" 2>/dev/null || echo "0")"
            echo "Files Created: $(grep -c "File created:" "$LOG_FILE" 2>/dev/null || echo "0")"
            echo "Directories Created: $(grep -c "Directory created:" "$LOG_FILE" 2>/dev/null || echo "0")"
            echo "Failed Operations: $(grep -c "ERROR.*Failed to create" "$LOG_FILE" 2>/dev/null || echo "0")"
        fi
        
        echo ""
        echo "Template Usage:"
        if [[ -d "$TEMPLATE_DIR" ]]; then
            echo "Available Templates:"
            find "$TEMPLATE_DIR" -name "*.template" -exec basename {} .template \; | sort
        fi
        
        echo ""
        echo "System Information:"
        echo "Available Space:"
        df -h | grep -E "^/dev/"
        
    } > "$report_file"
    
    echo "Creation operations report saved to: $report_file"
    log_operation "INFO" "Creation report generated: $report_file"
}

# Template management
manage_templates() {
    local action="$1"
    local template_name="$2"
    local template_content="$3"
    
    case "$action" in
        "create")
            if [[ -z "$template_name" || -z "$template_content" ]]; then
                echo "Usage: manage_templates create <name> <content>"
                return 1
            fi
            
            local template_file="$TEMPLATE_DIR/$template_name.template"
            echo "$template_content" > "$template_file"
            log_operation "INFO" "Template created: $template_name"
            ;;
        "list")
            echo "Available Templates:"
            find "$TEMPLATE_DIR" -name "*.template" -exec basename {} .template \;
            ;;
        "show")
            if [[ -z "$template_name" ]]; then
                echo "Usage: manage_templates show <name>"
                return 1
            fi
            
            local template_file="$TEMPLATE_DIR/$template_name.template"
            if [[ -f "$template_file" ]]; then
                cat "$template_file"
            else
                echo "Template not found: $template_name"
                return 1
            fi
            ;;
        "delete")
            if [[ -z "$template_name" ]]; then
                echo "Usage: manage_templates delete <name>"
                return 1
            fi
            
            local template_file="$TEMPLATE_DIR/$template_name.template"
            if [[ -f "$template_file" ]]; then
                rm "$template_file"
                log_operation "INFO" "Template deleted: $template_name"
            else
                echo "Template not found: $template_name"
                return 1
            fi
            ;;
    esac
}

# Main creation management function
main() {
    local action="${1:-help}"
    
    case "$action" in
        "create-file")
            local file_path="$2"
            local template_name="$3"
            local permissions="${4:-$DEFAULT_FILE_PERMISSIONS}"
            local variables="$5"
            
            if [[ -z "$file_path" ]]; then
                echo "Usage: $0 create-file <file_path> [template_name] [permissions] [variables]"
                exit 1
            fi
            
            enterprise_create_file "$file_path" "$template_name" "$permissions" "$variables"
            ;;
        "create-directory")
            local dir_path="$2"
            local template_name="$3"
            local permissions="${4:-$DEFAULT_DIR_PERMISSIONS}"
            local create_parents="${5:-true}"
            
            if [[ -z "$dir_path" ]]; then
                echo "Usage: $0 create-directory <dir_path> [template_name] [permissions] [create_parents]"
                exit 1
            fi
            
            enterprise_create_directory "$dir_path" "$template_name" "$permissions" "$create_parents"
            ;;
        "bulk-files")
            local items_file="$2"
            local template_name="$3"
            
            if [[ -z "$items_file" ]]; then
                echo "Usage: $0 bulk-files <items_file> [template_name]"
                exit 1
            fi
            
            bulk_create_operation "file" "$items_file" "$template_name"
            ;;
        "bulk-directories")
            local items_file="$2"
            local template_name="$3"
            
            if [[ -z "$items_file" ]]; then
                echo "Usage: $0 bulk-directories <items_file> [template_name]"
                exit 1
            fi
            
            bulk_create_operation "directory" "$items_file" "$template_name"
            ;;
        "user-workspace")
            local username="$2"
            local user_type="${3:-standard}"
            
            if [[ -z "$username" ]]; then
                echo "Usage: $0 user-workspace <username> [user_type]"
                exit 1
            fi
            
            create_user_workspace "$username" "$user_type"
            ;;
        "template")
            local template_action="$2"
            local template_name="$3"
            local template_content="$4"
            
            manage_templates "$template_action" "$template_name" "$template_content"
            ;;
        "report")
            generate_creation_report
            ;;
        "help"|*)
            echo "$SCRIPT_NAME v$VERSION"
            echo "Enterprise File and Folder Creation Management"
            echo ""
            echo "Usage: $0 <action> [options]"
            echo ""
            echo "Actions:"
            echo "  create-file <path> [template] [permissions] [variables]     - Create single file"
            echo "  create-directory <path> [template] [permissions] [parents] - Create directory"
            echo "  bulk-files <items_file> [template]                         - Create multiple files"
            echo "  bulk-directories <items_file> [template]                   - Create multiple directories"
            echo "  user-workspace <username> [user_type]                      - Create user workspace"
            echo "  template <action> [name] [content]                         - Manage templates"
            echo "  report                                                      - Generate operations report"
            echo "  help                                                        - Show this help message"
            echo ""
            echo "Template Actions:"
            echo "  create <name> <content>  - Create new template"
            echo "  list                     - List available templates"
            echo "  show <name>              - Show template content"
            echo "  delete <name>            - Delete template"
            echo ""
            echo "User Types:"
            echo "  standard    - Basic user workspace"
            echo "  developer   - Developer workspace with project directories"
            echo "  admin       - Administrative workspace with system directories"
            echo ""
            echo "Features:"
            echo "  • Template-based file and directory creation"
            echo "  • Permission and ownership management"
            echo "  • Naming convention validation"
            echo "  • Path depth and security validation"
            echo "  • Bulk operations with progress monitoring"
            echo "  • User workspace automation"
            echo "  • Comprehensive audit logging"
            ;;
    esac
}

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

Quick Reference Commands

Single File Operations

# Create empty file
./creation_manager.sh create-file "/Users/admin/document.txt"

# Create file from template
./creation_manager.sh create-file "/Users/admin/report.txt" "report_template"

# Create file with specific permissions
./creation_manager.sh create-file "/Users/admin/script.sh" "" "755"

# Create file with template variables
./creation_manager.sh create-file "/Users/admin/config.json" "config_template" "644" '{"project":"MyApp"}'

Directory Operations

# Create directory
./creation_manager.sh create-directory "/Users/admin/project"

# Create directory with specific permissions
./creation_manager.sh create-directory "/Users/admin/secure" "" "700"

# Create directory structure from template
./creation_manager.sh create-directory "/Users/admin/webapp" "webapp_structure"

Bulk Operations

# Create bulk files specification
cat > /tmp/files_to_create.txt << EOF
/Users/admin/doc1.txt|644|
/Users/admin/doc2.txt|644|
/Users/admin/config.json|600|{"env":"prod"}
EOF

# Execute bulk file creation
./creation_manager.sh bulk-files "/tmp/files_to_create.txt" "default_template"

# Create bulk directories specification
cat > /tmp/dirs_to_create.txt << EOF
/Users/admin/projects|755|
/Users/admin/scripts|755|
/Users/admin/logs|750|
EOF

# Execute bulk directory creation
./creation_manager.sh bulk-directories "/tmp/dirs_to_create.txt"

Template Management

# Create a new template
./creation_manager.sh template create "readme" "# {{PROJECT_NAME}}

Created by: {{USER}}
Date: {{DATE}}
Time: {{TIME}}

## Description
This is a README file for the project.
"

# List available templates
./creation_manager.sh template list

# Show template content
./creation_manager.sh template show "readme"

# Delete template
./creation_manager.sh template delete "old_template"

User Workspace Creation

# Create standard user workspace
./creation_manager.sh user-workspace "john.doe" "standard"

# Create developer workspace
./creation_manager.sh user-workspace "jane.smith" "developer"

# Create admin workspace
./creation_manager.sh user-workspace "admin.user" "admin"

Integration Examples

JAMF Pro Integration

#!/bin/bash

# JAMF Pro script for enterprise file creation
# Parameters: $4 = operation_type, $5 = path, $6 = template_name, $7 = permissions

OPERATION_TYPE="$4"
PATH="$5"
TEMPLATE_NAME="$6"
PERMISSIONS="$7"

# Download creation manager if not present
if [[ ! -f "/usr/local/bin/macfleet_creation_manager.sh" ]]; then
    curl -o "/usr/local/bin/macfleet_creation_manager.sh" "https://scripts.macfleet.com/creation_manager.sh"
    chmod +x "/usr/local/bin/macfleet_creation_manager.sh"
fi

# Execute creation operation
case "$OPERATION_TYPE" in
    "file")
        /usr/local/bin/macfleet_creation_manager.sh create-file "$PATH" "$TEMPLATE_NAME" "$PERMISSIONS"
        ;;
    "directory")
        /usr/local/bin/macfleet_creation_manager.sh create-directory "$PATH" "$TEMPLATE_NAME" "$PERMISSIONS"
        ;;
    "workspace")
        local username=$(basename "$PATH")
        /usr/local/bin/macfleet_creation_manager.sh user-workspace "$username" "$TEMPLATE_NAME"
        ;;
    *)
        echo "Invalid operation type: $OPERATION_TYPE"
        exit 1
        ;;
esac

# Generate report
/usr/local/bin/macfleet_creation_manager.sh report

exit $?

Configuration Profile for Creation Policies

<?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>PayloadContent</key>
    <array>
        <dict>
            <key>PayloadType</key>
            <string>com.macfleet.creation.policy</string>
            <key>PayloadIdentifier</key>
            <string>com.macfleet.creation.policy.main</string>
            <key>PayloadDisplayName</key>
            <string>MacFleet Creation Policy</string>
            <key>AllowedExtensions</key>
            <array>
                <string>.txt</string>
                <string>.md</string>
                <string>.pdf</string>
                <string>.docx</string>
            </array>
            <key>DefaultFilePermissions</key>
            <string>644</string>
            <key>DefaultDirectoryPermissions</key>
            <string>755</string>
            <key>MaxFilenameLength</key>
            <integer>255</integer>
            <key>MaxPathDepth</key>
            <integer>20</integer>
            <key>EnforceNamingConventions</key>
            <true/>
        </dict>
    </array>
</dict>
</plist>

Template Examples

Project Structure Template

{
  "name": "webapp_structure",
  "type": "directory_structure",
  "structure": {
    "src": {
      "type": "directory",
      "permissions": "755",
      "files": {
        "index.js": {
          "template": "javascript_main",
          "permissions": "644"
        },
        "package.json": {
          "template": "package_json",
          "permissions": "644"
        }
      },
      "subdirectories": {
        "components": {
          "type": "directory",
          "permissions": "755"
        },
        "utils": {
          "type": "directory",
          "permissions": "755"
        }
      }
    },
    "docs": {
      "type": "directory",
      "permissions": "755",
      "files": {
        "README.md": {
          "template": "readme",
          "permissions": "644"
        }
      }
    }
  }
}

File Templates

# Create default templates
./creation_manager.sh template create "readme" "# {{PROJECT_NAME}}

## Overview
This project was created on {{DATE}} by {{USER}}.

## Getting Started
1. Read this documentation
2. Review the code structure
3. Start development

## Contact
For questions, contact {{USER}}@company.com
"

./creation_manager.sh template create "gitignore" "# Logs
logs
*.log
npm-debug.log*

# Runtime data
pids
*.pid
*.seed

# Directory for instrumented libs
lib-cov

# Coverage directory
coverage

# Dependency directories
node_modules/

# Optional npm cache directory
.npm

# Optional REPL history
.node_repl_history
"

./creation_manager.sh template create "config_json" "{
  \"name\": \"{{PROJECT_NAME}}\",
  \"version\": \"1.0.0\",
  \"description\": \"Project created on {{DATE}}\",
  \"author\": \"{{USER}}\",
  \"created\": \"{{DATE}} {{TIME}}\",
  \"environment\": \"development\"
}
"

Security and Compliance Features

Permission Management

# Set secure permissions for sensitive files
create_secure_file() {
    local file_path="$1"
    local content="$2"
    
    # Create file with restrictive permissions
    enterprise_create_file "$file_path" "" "600"
    
    # Add content securely
    echo "$content" > "$file_path"
    
    # Ensure only owner can access
    chmod 600 "$file_path"
}

Compliance Reporting

# Generate compliance report for auditors
generate_compliance_report() {
    local report_file="/var/reports/creation_compliance_$(date +%Y%m%d).csv"
    
    echo "Timestamp,User,Type,Path,Permissions,Template,Status" > "$report_file"
    
    # Parse log file for creation operations
    grep "AUDIT.*created:" "$LOG_FILE" | while read line; do
        # Extract relevant information and format as CSV
        echo "$line" | awk -F' - ' '{print $1","$2}' >> "$report_file"
    done
    
    echo "Compliance report generated: $report_file"
}

Troubleshooting

Common Issues and Solutions

IssueCauseSolution
Permission deniedInsufficient privilegesCheck parent directory permissions
File already existsDuplicate creation attemptUse unique names or check existence first
Invalid charactersSpecial characters in nameUse alphanumeric characters only
Path too deepExceeds maximum depthReduce directory nesting
Template not foundMissing template fileCreate template or use different name

Log Analysis

# View recent creation operations
tail -f /var/log/macfleet_creation_operations.log

# Search for failed operations
grep "ERROR" /var/log/macfleet_creation_operations.log

# Count operations by type
grep -c "File created" /var/log/macfleet_creation_operations.log
grep -c "Directory created" /var/log/macfleet_creation_operations.log

Best Practices

  1. Use templates consistently for standardized structures
  2. Set appropriate permissions based on file sensitivity
  3. Validate naming conventions before creation
  4. Monitor creation logs regularly for policy violations
  5. Test templates thoroughly before fleet deployment
  6. Use bulk operations for efficiency at scale
  7. Implement user workspace automation for onboarding
  8. Regular template updates to maintain standards

This enterprise creation management system provides comprehensive template management, security validation, and automation capabilities while maintaining the simplicity of basic file and directory creation operations for effective fleet management.

Tutorial

Novas atualizações e melhorias para a Macfleet.

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

Runner do GitHub Actions

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

Pré-requisitos

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

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

Passo 1: Criar uma Conta de Usuário Dedicada

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

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

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

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

Mude para a nova conta de usuário:

su gh-runner

Passo 2: Instalar Software Necessário

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

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

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

Passo 3: Configurar o Runner do GitHub Actions

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

Runner do GitHub Actions

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

Runner do GitHub Actions

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

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

Runner do GitHub Actions

Passo 4: Configurar Sudoers (Opcional)

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

sudo visudo

Adicione a seguinte linha:

gh-runner ALL=(ALL) NOPASSWD: ALL

Passo 5: Usar o Runner em Fluxos de Trabalho

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

name: Fluxo de trabalho de exemplo

on:
  workflow_dispatch:

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

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

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

Melhores Práticas

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

Solução de Problemas

Problemas comuns e soluções:

  1. Runner não conectando:

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

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

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

Conclusão

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

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

Aplicativo Nativo

Aplicativo nativo do Macfleet

Guia de Instalação do Macfleet

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

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

🍎 macOS

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

🪟 Windows

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

🐧 Linux

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

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