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.

Application Language Management on macOS

Manage application-specific language settings across your MacFleet devices using command-line tools. This tutorial covers language discovery, individual app configuration, bulk management, and enterprise-wide language policy enforcement for international deployments.

Understanding macOS Language Management

macOS allows setting different languages for individual applications without changing the system language:

Language Configuration Levels

  • System Language - Overall macOS interface language
  • Application Language - Per-app language override
  • Regional Settings - Date, time, number, currency formats
  • Keyboard Input - Input method and layout preferences

Language Management Tools

  • defaults - Modify application preferences and language settings
  • languagesetup - Display available system languages
  • locale - Show current locale information
  • System Preferences - GUI language management interface

Language Discovery and Analysis

Discover Available Languages

#!/bin/bash

# Display all languages supported by the device
echo "🌍 Discovering available languages on device..."

# Get system supported languages
echo "=== System Supported Languages ==="
languagesetup

echo -e "\n=== Current Locale Information ==="
locale

echo -e "\n=== Available Language Codes ==="
ls /System/Library/CoreServices/SystemUIServer.app/Contents/Resources/*.lproj | \
    sed 's/.*\/\(.*\)\.lproj/\1/' | sort

echo "✅ Language discovery completed successfully"

Get Current System Language

#!/bin/bash

# Display current system and application language settings
echo "🔍 Analyzing current language configuration..."

# System language
echo "System Language: $(defaults read -g AppleLanguages | head -1 | tr -d '[:space:],"()')"

# Regional settings
echo "Region: $(defaults read -g AppleLocale)"

# Current user
CURRENT_USER=$(stat -f%Su /dev/console)
echo "Current User: $CURRENT_USER"

# Input sources
echo -e "\nInput Sources:"
defaults read com.apple.HIToolbox AppleEnabledInputSources | grep -E 'InputSourceKind|KeyboardLayout Name'

echo "✅ Language analysis completed"

Individual Application Language Management

Set Application Language

#!/bin/bash

# Set language for a specific application
APP_NAME="$1"
LANGUAGE_CODE="$2"

if [[ -z "$APP_NAME" || -z "$LANGUAGE_CODE" ]]; then
    echo "❌ Usage: $0 <AppName> <LanguageCode>"
    echo "Example: $0 Calendar de"
    echo "Example: $0 Safari fr"
    exit 1
fi

# Get current user
CURRENT_USER=$(stat -f%Su /dev/console)
echo "🌐 Setting language for $APP_NAME to $LANGUAGE_CODE"

# Validate language code
if ! languagesetup | grep -q "$LANGUAGE_CODE"; then
    echo "⚠️ Warning: Language code '$LANGUAGE_CODE' may not be supported"
fi

# Set application language
if sudo su "$CURRENT_USER" -c "defaults write -app '$APP_NAME' AppleLanguages -array '$LANGUAGE_CODE'"; then
    echo "✅ Language set successfully for $APP_NAME"
    echo "ℹ️ Restart $APP_NAME to see changes"
else
    echo "❌ Failed to set language for $APP_NAME"
    exit 1
fi

Verify Application Language

#!/bin/bash

# Verify current language setting for an application
APP_NAME="$1"

if [[ -z "$APP_NAME" ]]; then
    echo "❌ Usage: $0 <AppName>"
    echo "Example: $0 Calendar"
    exit 1
fi

CURRENT_USER=$(stat -f%Su /dev/console)
echo "🔍 Checking language setting for $APP_NAME..."

# Read current language setting
CURRENT_LANG=$(sudo su "$CURRENT_USER" -c "defaults read -app '$APP_NAME' AppleLanguages 2>/dev/null" | head -1 | tr -d '[:space:],"()')

if [[ -n "$CURRENT_LANG" ]]; then
    echo "Current language for $APP_NAME: $CURRENT_LANG"
else
    echo "No specific language set for $APP_NAME (using system default)"
fi

Reset Application Language

#!/bin/bash

# Reset application language to system default
APP_NAME="$1"

if [[ -z "$APP_NAME" ]]; then
    echo "❌ Usage: $0 <AppName>"
    exit 1
fi

CURRENT_USER=$(stat -f%Su /dev/console)
echo "🔄 Resetting language for $APP_NAME to system default..."

# Delete application-specific language setting
if sudo su "$CURRENT_USER" -c "defaults delete -app '$APP_NAME' AppleLanguages 2>/dev/null"; then
    echo "✅ Language reset successfully for $APP_NAME"
else
    echo "ℹ️ No custom language setting found for $APP_NAME"
fi

Bulk Language Management

Set Multiple Applications

#!/bin/bash

# Set language for multiple applications
LANGUAGE_CODE="$1"
shift
APPS=("$@")

if [[ -z "$LANGUAGE_CODE" || ${#APPS[@]} -eq 0 ]]; then
    echo "❌ Usage: $0 <LanguageCode> <App1> <App2> <App3>..."
    echo "Example: $0 fr Safari Calendar Mail"
    exit 1
fi

CURRENT_USER=$(stat -f%Su /dev/console)
echo "🌐 Setting language '$LANGUAGE_CODE' for ${#APPS[@]} applications..."

SUCCESS_COUNT=0
FAILED_APPS=()

for app in "${APPS[@]}"; do
    echo "Processing: $app"
    
    if sudo su "$CURRENT_USER" -c "defaults write -app '$app' AppleLanguages -array '$LANGUAGE_CODE'" 2>/dev/null; then
        echo "  ✅ Success: $app"
        ((SUCCESS_COUNT++))
    else
        echo "  ❌ Failed: $app"
        FAILED_APPS+=("$app")
    fi
done

echo -e "\n📊 Summary:"
echo "Successfully configured: $SUCCESS_COUNT applications"
echo "Failed: ${#FAILED_APPS[@]} applications"

if [[ ${#FAILED_APPS[@]} -gt 0 ]]; then
    echo "Failed applications: ${FAILED_APPS[*]}"
fi

Common Applications Language Setup

#!/bin/bash

# Set language for common macOS applications
LANGUAGE_CODE="$1"

if [[ -z "$LANGUAGE_CODE" ]]; then
    echo "❌ Usage: $0 <LanguageCode>"
    echo "Available codes: en, fr, de, es, it, ja, ko, zh-Hans, zh-Hant, etc."
    exit 1
fi

CURRENT_USER=$(stat -f%Su /dev/console)
echo "🌍 Configuring common applications for language: $LANGUAGE_CODE"

# Define common applications
COMMON_APPS=(
    "Safari"
    "Mail"
    "Calendar"
    "Contacts"
    "Notes"
    "Reminders"
    "Pages"
    "Numbers"
    "Keynote"
    "TextEdit"
    "Preview"
    "Finder"
    "System Preferences"
)

SUCCESS_COUNT=0
CONFIGURED_APPS=()

echo "Configuring ${#COMMON_APPS[@]} common applications..."

for app in "${COMMON_APPS[@]}"; do
    echo -n "  $app: "
    
    if sudo su "$CURRENT_USER" -c "defaults write -app '$app' AppleLanguages -array '$LANGUAGE_CODE'" 2>/dev/null; then
        echo "✅"
        CONFIGURED_APPS+=("$app")
        ((SUCCESS_COUNT++))
    else
        echo "❌"
    fi
done

echo -e "\n📊 Configuration Summary:"
echo "Successfully configured: $SUCCESS_COUNT applications"
echo "Applications configured: ${CONFIGURED_APPS[*]}"

Enterprise Language Management Script

#!/bin/bash

# MacFleet Application Language Management Tool
# Comprehensive language management for enterprise environments

# Configuration
LOG_FILE="/var/log/macfleet_language.log"
BACKUP_DIR="/var/backups/macfleet/language"
REPORT_DIR="/var/reports/macfleet/language"
CONFIG_FILE="/etc/macfleet/language_policy.conf"

# Default language policy settings
DEFAULT_LANGUAGE="en"
ENFORCE_LANGUAGE_POLICY=false
ALLOWED_LANGUAGES=("en" "fr" "de" "es" "it" "ja" "ko" "zh-Hans" "zh-Hant")
RESTRICTED_APPS=()

# 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")"; do
        if [[ ! -d "$dir" ]]; then
            sudo mkdir -p "$dir"
            log_action "Created directory: $dir"
        fi
    done
}

# Get current user
get_current_user() {
    stat -f%Su /dev/console
}

# Discover available languages
discover_languages() {
    echo "🌍 Discovering available languages..."
    
    {
        echo "=== System Language Discovery ==="
        echo "Date: $(date)"
        echo "Device: $(hostname)"
        echo ""
        
        echo "=== Available Languages ==="
        languagesetup
        echo ""
        
        echo "=== Current System Settings ==="
        echo "System Language: $(defaults read -g AppleLanguages | head -1 | tr -d '[:space:],"()')"
        echo "Region: $(defaults read -g AppleLocale)"
        echo "Currency: $(defaults read -g AppleCurrencies | head -1 | tr -d '[:space:],"()')"
        echo ""
        
        echo "=== Language Resource Directories ==="
        find /System/Library/CoreServices -name "*.lproj" -type d | head -20
        
    } > "$REPORT_DIR/language_discovery_$(date +%Y%m%d_%H%M%S).txt"
    
    log_action "Language discovery completed"
}

# Backup current language settings
backup_language_settings() {
    local backup_file="$BACKUP_DIR/language_backup_$(date +%Y%m%d_%H%M%S).txt"
    local current_user=$(get_current_user)
    
    echo "💾 Backing up current language settings..."
    
    {
        echo "=== MacFleet Language Settings Backup ==="
        echo "Date: $(date)"
        echo "User: $current_user"
        echo "Device: $(hostname)"
        echo ""
        
        echo "=== System Language Settings ==="
        echo "AppleLanguages: $(defaults read -g AppleLanguages 2>/dev/null || echo 'Not set')"
        echo "AppleLocale: $(defaults read -g AppleLocale 2>/dev/null || echo 'Not set')"
        echo ""
        
        echo "=== Application-Specific Languages ==="
        
        # Get list of applications with custom language settings
        local apps_with_custom_lang=()
        
        # Check common applications
        local check_apps=(
            "Safari" "Mail" "Calendar" "Contacts" "Notes" "Reminders"
            "Pages" "Numbers" "Keynote" "TextEdit" "Preview" "Finder"
            "System Preferences" "Photos" "Music" "TV" "Books"
        )
        
        for app in "${check_apps[@]}"; do
            local app_lang
            app_lang=$(sudo su "$current_user" -c "defaults read -app '$app' AppleLanguages 2>/dev/null" | head -1 | tr -d '[:space:],"()')
            if [[ -n "$app_lang" ]]; then
                echo "$app: $app_lang"
                apps_with_custom_lang+=("$app")
            fi
        done
        
        if [[ ${#apps_with_custom_lang[@]} -eq 0 ]]; then
            echo "No applications with custom language settings found"
        fi
        
    } > "$backup_file"
    
    echo "✅ Backup saved to: $backup_file"
    log_action "Language settings backed up to: $backup_file"
}

# Generate language audit report
generate_language_report() {
    local report_file="$REPORT_DIR/language_audit_$(date +%Y%m%d_%H%M%S).txt"
    local current_user=$(get_current_user)
    
    echo "📊 Generating language audit report..."
    
    {
        echo "MacFleet Language Audit Report"
        echo "Generated: $(date)"
        echo "Device: $(hostname)"
        echo "User: $current_user"
        echo "================================="
        echo ""
        
        echo "=== System Language Configuration ==="
        local sys_lang=$(defaults read -g AppleLanguages | head -1 | tr -d '[:space:],"()')
        echo "Primary Language: $sys_lang"
        echo "Region: $(defaults read -g AppleLocale)"
        echo "Currency: $(defaults read -g AppleCurrencies | head -1 | tr -d '[:space:],"()')"
        echo ""
        
        echo "=== Available Languages ==="
        languagesetup | grep -v "Language setup tool" | head -20
        echo ""
        
        echo "=== Application Language Audit ==="
        local total_apps=0
        local custom_lang_apps=0
        
        # Audit common applications
        local audit_apps=(
            "Safari" "Mail" "Calendar" "Contacts" "Notes" "Reminders"
            "Pages" "Numbers" "Keynote" "TextEdit" "Preview" "Finder"
            "System Preferences" "Photos" "Music" "TV" "Books" "Maps"
            "FaceTime" "Messages" "Calculator" "Clock mini" "Dictionary"
        )
        
        for app in "${audit_apps[@]}"; do
            ((total_apps++))
            local app_lang
            app_lang=$(sudo su "$current_user" -c "defaults read -app '$app' AppleLanguages 2>/dev/null" | head -1 | tr -d '[:space:],"()')
            
            if [[ -n "$app_lang" ]]; then
                echo "$app: $app_lang (custom)"
                ((custom_lang_apps++))
            else
                echo "$app: $sys_lang (system default)"
            fi
        done
        
        echo ""
        echo "=== Summary ==="
        echo "Total applications audited: $total_apps"
        echo "Applications with custom language: $custom_lang_apps"
        echo "Applications using system default: $((total_apps - custom_lang_apps))"
        
        # Check for compliance
        if [[ "$ENFORCE_LANGUAGE_POLICY" == "true" ]]; then
            echo ""
            echo "=== Policy Compliance ==="
            echo "Language policy enforcement: ENABLED"
            echo "Default required language: $DEFAULT_LANGUAGE"
            echo "Allowed languages: ${ALLOWED_LANGUAGES[*]}"
            
            local non_compliant_apps=()
            for app in "${audit_apps[@]}"; do
                local app_lang
                app_lang=$(sudo su "$current_user" -c "defaults read -app '$app' AppleLanguages 2>/dev/null" | head -1 | tr -d '[:space:],"()')
                
                if [[ -n "$app_lang" ]]; then
                    # Check if language is in allowed list
                    local is_allowed=false
                    for allowed_lang in "${ALLOWED_LANGUAGES[@]}"; do
                        if [[ "$app_lang" == "$allowed_lang" ]]; then
                            is_allowed=true
                            break
                        fi
                    done
                    
                    if [[ "$is_allowed" == "false" ]]; then
                        non_compliant_apps+=("$app:$app_lang")
                    fi
                fi
            done
            
            if [[ ${#non_compliant_apps[@]} -gt 0 ]]; then
                echo "Non-compliant applications:"
                for app_info in "${non_compliant_apps[@]}"; do
                    echo "  - ${app_info//:/ (language: }")"
                done
            else
                echo "All applications are compliant with language policy"
            fi
        fi
        
    } > "$report_file"
    
    echo "📊 Report saved to: $report_file"
    log_action "Language audit report generated: $report_file"
}

# Enforce language policy
enforce_language_policy() {
    local target_language="${1:-$DEFAULT_LANGUAGE}"
    local current_user=$(get_current_user)
    
    echo "🔒 Enforcing language policy: $target_language"
    log_action "Language policy enforcement started: $target_language"
    
    # Validate target language
    local is_allowed=false
    for allowed_lang in "${ALLOWED_LANGUAGES[@]}"; do
        if [[ "$target_language" == "$allowed_lang" ]]; then
            is_allowed=true
            break
        fi
    done
    
    if [[ "$is_allowed" == "false" ]]; then
        echo "❌ Language '$target_language' is not in the allowed languages list"
        echo "Allowed languages: ${ALLOWED_LANGUAGES[*]}"
        return 1
    fi
    
    # Applications to enforce policy on
    local enforce_apps=(
        "Safari" "Mail" "Calendar" "Contacts" "Notes" "Reminders"
        "Pages" "Numbers" "Keynote" "TextEdit" "Preview"
        "System Preferences" "Photos" "Music" "TV" "Books"
    )
    
    local success_count=0
    local failed_apps=()
    
    for app in "${enforce_apps[@]}"; do
        # Skip restricted apps
        local is_restricted=false
        for restricted_app in "${RESTRICTED_APPS[@]}"; do
            if [[ "$app" == "$restricted_app" ]]; then
                is_restricted=true
                break
            fi
        done
        
        if [[ "$is_restricted" == "true" ]]; then
            echo "  Skipping restricted app: $app"
            continue
        fi
        
        echo -n "  Configuring $app: "
        
        if sudo su "$current_user" -c "defaults write -app '$app' AppleLanguages -array '$target_language'" 2>/dev/null; then
            echo ""
            ((success_count++))
        else
            echo ""
            failed_apps+=("$app")
        fi
    done
    
    echo -e "\n📊 Policy Enforcement Summary:"
    echo "Successfully configured: $success_count applications"
    echo "Failed: ${#failed_apps[@]} applications"
    
    if [[ ${#failed_apps[@]} -gt 0 ]]; then
        echo "Failed applications: ${failed_apps[*]}"
    fi
    
    log_action "Language policy enforcement completed: $success_count successes, ${#failed_apps[@]} failures"
}

# Restore language settings from backup
restore_language_settings() {
    local backup_file="$1"
    local current_user=$(get_current_user)
    
    if [[ ! -f "$backup_file" ]]; then
        echo "❌ Backup file not found: $backup_file"
        return 1
    fi
    
    echo "🔄 Restoring language settings from backup..."
    log_action "Language settings restoration started from: $backup_file"
    
    # Parse backup file and restore settings
    local in_app_section=false
    local restored_count=0
    
    while IFS= read -r line; do
        if [[ "$line" == "=== Application-Specific Languages ===" ]]; then
            in_app_section=true
            continue
        fi
        
        if [[ "$in_app_section" == "true" && "$line" =~ ^([^:]+):[[:space:]]*(.+)$ ]]; then
            local app_name="${BASH_REMATCH[1]}"
            local app_lang="${BASH_REMATCH[2]}"
            
            if [[ "$app_lang" != "Not set" ]]; then
                echo -n "  Restoring $app_name to $app_lang: "
                
                if sudo su "$current_user" -c "defaults write -app '$app_name' AppleLanguages -array '$app_lang'" 2>/dev/null; then
                    echo ""
                    ((restored_count++))
                else
                    echo ""
                fi
            fi
        fi
    done < "$backup_file"
    
    echo -e "\n✅ Restoration completed: $restored_count applications restored"
    log_action "Language settings restoration completed: $restored_count applications"
}

# Main execution function
main() {
    local action="${1:-help}"
    local target="${2:-}"
    local apps_or_backup=("${@:3}")
    
    log_action "=== MacFleet Language Management Started ==="
    
    setup_directories
    
    case "$action" in
        "discover"|"languages")
            discover_languages
            ;;
        "audit"|"report")
            generate_language_report
            ;;
        "backup")
            backup_language_settings
            ;;
        "restore")
            if [[ -n "$target" ]]; then
                restore_language_settings "$target"
            else
                echo "❌ Please specify backup file to restore from"
                echo "Usage: $0 restore <backup_file>"
            fi
            ;;
        "set")
            if [[ -n "$target" && ${#apps_or_backup[@]} -gt 0 ]]; then
                # Set language for specific apps
                local language_code="$target"
                local apps=("${apps_or_backup[@]}")
                local current_user=$(get_current_user)
                
                echo "🌐 Setting language '$language_code' for specified applications..."
                
                local success_count=0
                for app in "${apps[@]}"; do
                    echo -n "  $app: "
                    if sudo su "$current_user" -c "defaults write -app '$app' AppleLanguages -array '$language_code'" 2>/dev/null; then
                        echo ""
                        ((success_count++))
                    else
                        echo ""
                    fi
                done
                
                echo "✅ Configured $success_count applications"
            else
                echo "❌ Usage: $0 set <language_code> <app1> <app2> ..."
                echo "Example: $0 set fr Safari Mail Calendar"
            fi
            ;;
        "enforce")
            local target_lang="${target:-$DEFAULT_LANGUAGE}"
            enforce_language_policy "$target_lang"
            ;;
        "reset")
            if [[ -n "$target" ]]; then
                local current_user=$(get_current_user)
                echo "🔄 Resetting language for $target to system default..."
                
                if sudo su "$current_user" -c "defaults delete -app '$target' AppleLanguages" 2>/dev/null; then
                    echo "✅ Language reset for $target"
                else
                    echo "ℹ️ No custom language setting found for $target"
                fi
            else
                echo "❌ Usage: $0 reset <app_name>"
            fi
            ;;
        "check")
            if [[ -n "$target" ]]; then
                local current_user=$(get_current_user)
                local app_lang
                app_lang=$(sudo su "$current_user" -c "defaults read -app '$target' AppleLanguages 2>/dev/null" | head -1 | tr -d '[:space:],"()')
                
                if [[ -n "$app_lang" ]]; then
                    echo "Language for $target: $app_lang"
                else
                    echo "No custom language set for $target (using system default)"
                fi
            else
                echo "❌ Usage: $0 check <app_name>"
            fi
            ;;
        "help"|*)
            echo "MacFleet Application Language Management Tool"
            echo "Usage: $0 [action] [options]"
            echo ""
            echo "Actions:"
            echo "  discover              - Discover available languages on device"
            echo "  audit                 - Generate language audit report"
            echo "  backup                - Backup current language settings"
            echo "  restore <file>        - Restore language settings from backup"
            echo "  set <lang> <apps...>  - Set language for specific applications"
            echo "  enforce [language]    - Enforce language policy across applications"
            echo "  reset <app>           - Reset application to system default language"
            echo "  check <app>           - Check current language setting for application"
            echo "  help                  - Show this help message"
            echo ""
            echo "Language Codes:"
            echo "  en        - English"
            echo "  fr        - French"
            echo "  de        - German"
            echo "  es        - Spanish"
            echo "  it        - Italian"
            echo "  ja        - Japanese"
            echo "  ko        - Korean"
            echo "  zh-Hans   - Chinese (Simplified)"
            echo "  zh-Hant   - Chinese (Traditional)"
            ;;
    esac
    
    log_action "=== MacFleet Language Management Completed ==="
}

# Execute main function
main "$@"

Language Code Reference

Common Language Codes

LanguageCodeRegion
EnglishenInternational
FrenchfrFrance
GermandeGermany
SpanishesSpain
ItalianitItaly
PortugueseptPortugal
Portuguese (Brazil)pt-BRBrazil
JapanesejaJapan
KoreankoKorea
Chinese (Simplified)zh-HansChina
Chinese (Traditional)zh-HantTaiwan/Hong Kong
RussianruRussia
ArabicarMiddle East
DutchnlNetherlands
SwedishsvSweden
NorwegiannoNorway
DanishdaDenmark
FinnishfiFinland

Regional Variants

# Common regional language codes
en-US    # English (United States)
en-GB    # English (United Kingdom)
en-CA    # English (Canada)
en-AU    # English (Australia)
fr-FR    # French (France)
fr-CA    # French (Canada)
de-DE    # German (Germany)
de-CH    # German (Switzerland)
es-ES    # Spanish (Spain)
es-MX    # Spanish (Mexico)

Application-Specific Examples

Popular macOS Applications

# Set French for productivity apps
./language_manager.sh set fr "Pages" "Numbers" "Keynote"

# Set German for communication apps
./language_manager.sh set de "Mail" "Messages" "FaceTime"

# Set Japanese for creative apps
./language_manager.sh set ja "Photos" "GarageBand" "iMovie"

# Set Spanish for system apps
./language_manager.sh set es "Calendar" "Contacts" "Reminders"

Enterprise Application Setup

# Configure Microsoft Office
defaults write -app "Microsoft Word" AppleLanguages -array "fr"
defaults write -app "Microsoft Excel" AppleLanguages -array "fr"
defaults write -app "Microsoft PowerPoint" AppleLanguages -array "fr"

# Configure Adobe Creative Suite
defaults write -app "Adobe Photoshop 2024" AppleLanguages -array "de"
defaults write -app "Adobe Illustrator 2024" AppleLanguages -array "de"
defaults write -app "Adobe InDesign 2024" AppleLanguages -array "de"

Language Policy Management

Enterprise Language Enforcement

# Create organization language policy
ORGANIZATION_LANGUAGE="en"
DEPARTMENT_LANGUAGES=("en" "fr" "de")  # Allowed languages

# Enforce across all standard applications
for app in Safari Mail Calendar Contacts Notes; do
    defaults write -app "$app" AppleLanguages -array "$ORGANIZATION_LANGUAGE"
done

Compliance Checking

# Check compliance with language policy
check_language_compliance() {
    local required_lang="$1"
    local non_compliant_apps=()
    
    for app in Safari Mail Calendar Contacts Notes Reminders; do
        local current_lang=$(defaults read -app "$app" AppleLanguages 2>/dev/null | head -1 | tr -d '[:space:],"()')
        
        if [[ -n "$current_lang" && "$current_lang" != "$required_lang" ]]; then
            non_compliant_apps+=("$app:$current_lang")
        fi
    done
    
    if [[ ${#non_compliant_apps[@]} -gt 0 ]]; then
        echo "⚠️ Non-compliant applications found:"
        printf '%s\n' "${non_compliant_apps[@]}"
        return 1
    else
        echo "✅ All applications comply with language policy"
        return 0
    fi
}

Troubleshooting

Common Issues

# Check if application exists
app_exists() {
    local app_name="$1"
    if mdfind "kMDItemKind == 'Application'" | grep -q "$app_name.app"; then
        return 0
    else
        echo "❌ Application '$app_name' not found"
        return 1
    fi
}

# Force application restart
restart_application() {
    local app_name="$1"
    echo "🔄 Restarting $app_name..."
    
    # Kill application if running
    pkill -f "$app_name" 2>/dev/null
    
    # Wait and relaunch
    sleep 2
    open -a "$app_name" 2>/dev/null
}

Language Setting Verification

# Verify language change took effect
verify_language_change() {
    local app_name="$1"
    local expected_lang="$2"
    
    local actual_lang=$(defaults read -app "$app_name" AppleLanguages 2>/dev/null | head -1 | tr -d '[:space:],"()')
    
    if [[ "$actual_lang" == "$expected_lang" ]]; then
        echo "✅ $app_name language verified: $expected_lang"
        return 0
    else
        echo "❌ $app_name language mismatch. Expected: $expected_lang, Actual: $actual_lang"
        return 1
    fi
}

Important Notes

  • Application Restart Required - Most applications need to be restarted to apply language changes
  • System vs App Languages - App-specific settings override system language
  • User Context - Language settings apply to the current user only
  • Backup Before Changes - Always backup current settings before bulk modifications
  • Test Individual Apps - Verify language changes work for specific applications
  • Regional Considerations - Some apps may require specific regional language codes

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.