Tutorial

Novas atualizações e melhorias para a Macfleet.

Aviso importante

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

Time Zone Management on macOS

Manage time zones and date/time settings across your MacFleet with enterprise-grade automation, geographic compliance policies, and comprehensive monitoring capabilities.

Understanding Enterprise Time Zone Management

Enterprise time zone management requires more than basic time setting, demanding:

  • Automated geographic compliance with regional time zone policies
  • Centralized time synchronization with enterprise NTP servers
  • Policy enforcement for business hours and operational compliance
  • Real-time monitoring of time drift and synchronization status
  • Audit logging for compliance and security requirements
  • Integration capabilities with existing infrastructure and directory services

Core Time Zone Management Process

Basic Commands

  1. Set Time Zone - sudo systemsetup -settimezone <timezone>
  2. List Time Zones - sudo systemsetup -listtimezones
  3. Enable Network Time - /usr/sbin/systemsetup -setusingnetworktime on
  4. Set Time Server - /usr/sbin/systemsetup -setnetworktimeserver time.apple.com

Core Configuration Examples

# Basic time zone setting
sudo systemsetup -settimezone Pacific/Ponape

# Enable automatic time synchronization
/usr/sbin/systemsetup -setusingnetworktime on -setnetworktimeserver time.apple.com

# List available time zones
sudo systemsetup -listtimezones

Enterprise Time Zone Management System

#!/bin/bash

# MacFleet Enterprise Time Zone Management System
# Comprehensive time zone and date/time management with enterprise controls and monitoring

# Configuration
SCRIPT_NAME="MacFleet Time Zone Manager"
VERSION="1.0.0"
LOG_FILE="/var/log/macfleet_timezone.log"
AUDIT_LOG="/var/log/macfleet_timezone_audit.log"
CONFIG_DIR="/etc/macfleet/timezone"
POLICIES_DIR="/etc/macfleet/timezone/policies"
BACKUP_DIR="/var/backups/timezone"
TEMP_DIR="/tmp/macfleet_timezone"
TIME_DRIFT_THRESHOLD=30  # seconds
SYNC_CHECK_INTERVAL=300  # 5 minutes
ORGANIZATION_NAME="MacFleet Enterprise"
DEPLOYMENT_MODE="enterprise"
ENABLE_COMPLIANCE_CHECKING=true
ENABLE_GEOGRAPHIC_POLICIES=true
AUTO_TIME_SYNC=true

# Enterprise Time Servers (in priority order)
declare -a ENTERPRISE_TIME_SERVERS=(
    "time.company.com"          # Primary enterprise NTP server
    "time2.company.com"         # Secondary enterprise NTP server
    "time.apple.com"            # Apple's time server (fallback)
    "pool.ntp.org"              # Public NTP pool (fallback)
    "time.nist.gov"             # NIST time server (fallback)
)

# Geographic Policy Mapping
declare -A GEOGRAPHIC_POLICIES=(
    ["US_EAST"]="America/New_York"
    ["US_CENTRAL"]="America/Chicago"
    ["US_MOUNTAIN"]="America/Denver"
    ["US_PACIFIC"]="America/Los_Angeles"
    ["US_ALASKA"]="America/Anchorage"
    ["US_HAWAII"]="Pacific/Honolulu"
    ["EU_LONDON"]="Europe/London"
    ["EU_PARIS"]="Europe/Paris"
    ["EU_BERLIN"]="Europe/Berlin"
    ["EU_ZURICH"]="Europe/Zurich"
    ["ASIA_TOKYO"]="Asia/Tokyo"
    ["ASIA_SINGAPORE"]="Asia/Singapore"
    ["ASIA_HONG_KONG"]="Asia/Hong_Kong"
    ["AUSTRALIA_SYDNEY"]="Australia/Sydney"
)

# Business Hours Policies
declare -A BUSINESS_HOURS_POLICIES=(
    ["standard"]="09:00-17:00"
    ["extended"]="08:00-18:00"
    ["24x7"]="00:00-23:59"
    ["custom"]="configurable"
)

# Compliance Requirements
declare -A COMPLIANCE_STANDARDS=(
    ["SOX"]="strict_time_audit"
    ["HIPAA"]="synchronized_logging"
    ["PCI_DSS"]="secure_time_sync"
    ["ISO27001"]="time_source_validation"
)

# Create necessary directories
mkdir -p "$CONFIG_DIR"
mkdir -p "$POLICIES_DIR"
mkdir -p "$BACKUP_DIR"
mkdir -p "$TEMP_DIR"
mkdir -p "$(dirname "$LOG_FILE")"
mkdir -p "$(dirname "$AUDIT_LOG")"

# Set secure permissions
chmod 755 "$CONFIG_DIR"
chmod 750 "$POLICIES_DIR"
chmod 750 "$BACKUP_DIR"
chmod 700 "$TEMP_DIR"

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

log_security_event() {
    local event_type="$1"
    local details="$2"
    local severity="$3"
    local admin_user=$(whoami)
    
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    local source_ip=$(who am i | awk '{print $5}' | tr -d '()')
    echo "SECURITY|$timestamp|$event_type|$severity|$admin_user|$source_ip|$details" >> "$AUDIT_LOG"
}

# Get current time zone information
get_current_timezone() {
    local current_tz=$(systemsetup -gettimezone 2>/dev/null | awk -F': ' '{print $2}')
    local current_time=$(date '+%Y-%m-%d %H:%M:%S %Z')
    local utc_time=$(date -u '+%Y-%m-%d %H:%M:%S UTC')
    local time_server=$(systemsetup -getnetworktimeserver 2>/dev/null | awk -F': ' '{print $2}')
    local network_time_status=$(systemsetup -getusingnetworktime 2>/dev/null | awk -F': ' '{print $2}')
    
    echo "=== Current Time Zone Information ==="
    echo "Time Zone: $current_tz"
    echo "Local Time: $current_time"
    echo "UTC Time: $utc_time"
    echo "Time Server: $time_server"
    echo "Network Time Sync: $network_time_status"
    echo ""
}

# List available time zones with geographic grouping
list_available_timezones() {
    local filter_region="${1:-all}"
    local format="${2:-grouped}"
    
    echo "=== Available Time Zones ==="
    echo "Filter: $filter_region"
    echo "Format: $format"
    echo ""
    
    if [[ "$format" == "grouped" ]]; then
        # Group by region
        echo "Americas:"
        systemsetup -listtimezones 2>/dev/null | grep "America/" | sort | head -20
        echo ""
        
        echo "Europe:"
        systemsetup -listtimezones 2>/dev/null | grep "Europe/" | sort | head -20
        echo ""
        
        echo "Asia:"
        systemsetup -listtimezones 2>/dev/null | grep "Asia/" | sort | head -20
        echo ""
        
        echo "Pacific:"
        systemsetup -listtimezones 2>/dev/null | grep "Pacific/" | sort | head -20
        echo ""
        
        echo "Other:"
        systemsetup -listtimezones 2>/dev/null | grep -v -E "America/|Europe/|Asia/|Pacific/" | sort | head -10
    else
        # Simple list
        case "$filter_region" in
            "americas"|"america")
                systemsetup -listtimezones 2>/dev/null | grep "America/" | sort
                ;;
            "europe")
                systemsetup -listtimezones 2>/dev/null | grep "Europe/" | sort
                ;;
            "asia")
                systemsetup -listtimezones 2>/dev/null | grep "Asia/" | sort
                ;;
            "pacific")
                systemsetup -listtimezones 2>/dev/null | grep "Pacific/" | sort
                ;;
            *)
                systemsetup -listtimezones 2>/dev/null | sort
                ;;
        esac
    fi
}

# Validate time zone
validate_timezone() {
    local timezone="$1"
    
    if [[ -z "$timezone" ]]; then
        echo "Error: Time zone cannot be empty"
        return 1
    fi
    
    # Check if timezone exists in system list
    if systemsetup -listtimezones 2>/dev/null | grep -q "^$timezone$"; then
        echo "✅ Time zone '$timezone' is valid"
        return 0
    else
        echo "❌ Time zone '$timezone' is not valid"
        echo "Use 'list-timezones' command to see available options"
        return 1
    fi
}

# Set time zone with enterprise validation
set_enterprise_timezone() {
    local timezone="$1"
    local policy="${2:-standard}"
    local force="${3:-false}"
    local admin_user=$(whoami)
    
    log_security_event "TIMEZONE_CHANGE_ATTEMPT" "timezone=$timezone,policy=$policy" "INFO"
    
    echo "=== Enterprise Time Zone Configuration ==="
    echo "Target Time Zone: $timezone"
    echo "Policy: $policy"
    echo "Administrator: $admin_user"
    echo "Force Mode: $force"
    echo ""
    
    # Validate time zone
    if ! validate_timezone "$timezone"; then
        log_operation "ERROR" "Invalid time zone specified: $timezone"
        return 1
    fi
    
    # Check current time zone
    local current_tz=$(systemsetup -gettimezone 2>/dev/null | awk -F': ' '{print $2}')
    
    if [[ "$current_tz" == "$timezone" && "$force" != "true" ]]; then
        echo "✅ Time zone is already set to $timezone"
        log_operation "INFO" "Time zone unchanged: $timezone"
        return 0
    fi
    
    # Backup current configuration
    local backup_file="$BACKUP_DIR/timezone_$(date +%Y%m%d_%H%M%S).conf"
    {
        echo "# MacFleet Time Zone Backup"
        echo "PREVIOUS_TIMEZONE=$current_tz"
        echo "PREVIOUS_TIME_SERVER=$(systemsetup -getnetworktimeserver 2>/dev/null | awk -F': ' '{print $2}')"
        echo "PREVIOUS_NETWORK_TIME=$(systemsetup -getusingnetworktime 2>/dev/null | awk -F': ' '{print $2}')"
        echo "BACKUP_TIMESTAMP=$(date)"
        echo "CHANGED_BY=$admin_user"
    } > "$backup_file"
    
    log_operation "INFO" "Configuration backed up to: $backup_file"
    
    # Apply time zone change
    echo "Setting time zone to: $timezone"
    
    if sudo systemsetup -settimezone "$timezone" 2>/dev/null; then
        echo "✅ Time zone set successfully"
        log_operation "INFO" "Time zone changed from '$current_tz' to '$timezone'"
        log_security_event "TIMEZONE_CHANGED" "from=$current_tz,to=$timezone,policy=$policy" "INFO"
        
        # Configure network time synchronization
        configure_time_sync "$policy"
        
        # Verify the change
        sleep 2
        local new_tz=$(systemsetup -gettimezone 2>/dev/null | awk -F': ' '{print $2}')
        
        if [[ "$new_tz" == "$timezone" ]]; then
            echo "✅ Time zone verification successful"
            
            # Display updated time information
            get_current_timezone
            
            return 0
        else
            echo "❌ Time zone verification failed"
            log_operation "ERROR" "Time zone verification failed: expected '$timezone', got '$new_tz'"
            return 1
        fi
    else
        echo "❌ Failed to set time zone"
        log_operation "ERROR" "Failed to set time zone to: $timezone"
        log_security_event "TIMEZONE_CHANGE_FAILED" "timezone=$timezone,error=systemsetup_failed" "ERROR"
        return 1
    fi
}

# Configure time synchronization
configure_time_sync() {
    local policy="${1:-standard}"
    local admin_user=$(whoami)
    
    echo "=== Configuring Time Synchronization ==="
    echo "Policy: $policy"
    echo ""
    
    # Determine time server based on policy
    local time_server
    case "$policy" in
        "enterprise")
            time_server="${ENTERPRISE_TIME_SERVERS[0]}"
            ;;
        "secure")
            time_server="${ENTERPRISE_TIME_SERVERS[1]}"
            ;;
        "standard")
            time_server="time.apple.com"
            ;;
        "public")
            time_server="pool.ntp.org"
            ;;
        *)
            time_server="time.apple.com"
            ;;
    esac
    
    echo "Setting time server to: $time_server"
    
    # Enable network time and set server
    if sudo systemsetup -setusingnetworktime on -setnetworktimeserver "$time_server" 2>/dev/null; then
        echo "✅ Time synchronization configured successfully"
        log_operation "INFO" "Time sync configured: server=$time_server, policy=$policy"
        
        # Test time server connectivity
        test_time_server_connectivity "$time_server"
        
        return 0
    else
        echo "❌ Failed to configure time synchronization"
        log_operation "ERROR" "Failed to configure time sync: server=$time_server"
        
        # Try fallback servers
        echo "Attempting fallback time servers..."
        for fallback_server in "${ENTERPRISE_TIME_SERVERS[@]}"; do
            if [[ "$fallback_server" != "$time_server" ]]; then
                echo "Trying fallback server: $fallback_server"
                
                if sudo systemsetup -setusingnetworktime on -setnetworktimeserver "$fallback_server" 2>/dev/null; then
                    echo "✅ Fallback time server configured: $fallback_server"
                    log_operation "INFO" "Fallback time sync configured: $fallback_server"
                    return 0
                fi
            fi
        done
        
        echo "❌ All time server configurations failed"
        log_operation "ERROR" "All time server configurations failed"
        return 1
    fi
}

# Test time server connectivity
test_time_server_connectivity() {
    local time_server="$1"
    local timeout=10
    
    echo "Testing connectivity to time server: $time_server"
    
    # Test basic connectivity
    if timeout "$timeout" ping -c 3 "$time_server" &>/dev/null; then
        echo "✅ Time server is reachable"
        
        # Test NTP specific connectivity (if ntpdate is available)
        if command -v ntpdate &>/dev/null; then
            if timeout "$timeout" ntpdate -q "$time_server" &>/dev/null; then
                echo "✅ NTP service is responding"
                return 0
            else
                echo "⚠️  Time server reachable but NTP may not be responding"
                return 1
            fi
        else
            echo "✅ Basic connectivity confirmed (ntpdate not available for NTP test)"
            return 0
        fi
    else
        echo "❌ Time server is not reachable"
        log_operation "WARNING" "Time server connectivity failed: $time_server"
        return 1
    fi
}

# Monitor time drift and synchronization
monitor_time_sync() {
    local check_type="${1:-basic}"
    local admin_user=$(whoami)
    
    echo "=== Time Synchronization Monitoring ==="
    echo "Check Type: $check_type"
    echo "Monitor: $admin_user"
    echo ""
    
    local sync_status="HEALTHY"
    local issues=()
    
    # Check if network time is enabled
    local network_time_status=$(systemsetup -getusingnetworktime 2>/dev/null | awk -F': ' '{print $2}')
    
    if [[ "$network_time_status" == "On" ]]; then
        echo "✅ Network time synchronization is enabled"
    else
        echo "❌ Network time synchronization is disabled"
        sync_status="CRITICAL"
        issues+=("Network time sync disabled")
    fi
    
    # Check time server configuration
    local time_server=$(systemsetup -getnetworktimeserver 2>/dev/null | awk -F': ' '{print $2}')
    echo "Time Server: $time_server"
    
    # Test time server connectivity
    if ! test_time_server_connectivity "$time_server"; then
        sync_status="WARNING"
        issues+=("Time server connectivity issues")
    fi
    
    # Check time drift (if ntpdate is available)
    if command -v ntpdate &>/dev/null; then
        echo ""
        echo "Checking time drift..."
        
        local drift_output=$(ntpdate -q "$time_server" 2>/dev/null | tail -1)
        
        if [[ -n "$drift_output" ]]; then
            # Extract drift value (simplified parsing)
            local drift_seconds=$(echo "$drift_output" | grep -o "offset [+-][0-9.]*" | awk '{print $2}' | tr -d '+')
            
            if [[ -n "$drift_seconds" ]]; then
                local drift_abs=$(echo "$drift_seconds" | tr -d '-')
                
                echo "Time drift: ${drift_seconds}s"
                
                if (( $(echo "$drift_abs > $TIME_DRIFT_THRESHOLD" | bc -l) )); then
                    echo "⚠️  Time drift exceeds threshold (${TIME_DRIFT_THRESHOLD}s)"
                    sync_status="WARNING"
                    issues+=("Time drift: ${drift_seconds}s")
                else
                    echo "✅ Time drift within acceptable range"
                fi
            fi
        fi
    else
        echo "ntpdate not available for drift checking"
    fi
    
    # Advanced checks
    if [[ "$check_type" == "comprehensive" ]]; then
        echo ""
        echo "Running comprehensive time monitoring..."
        
        # Check system clock vs hardware clock
        if command -v hwclock &>/dev/null; then
            local sys_time=$(date +%s)
            local hw_time=$(sudo hwclock --show | date -f - +%s 2>/dev/null || echo "0")
            
            if [[ "$hw_time" != "0" ]]; then
                local clock_diff=$((sys_time - hw_time))
                local clock_diff_abs=${clock_diff#-}
                
                echo "System/Hardware clock difference: ${clock_diff}s"
                
                if [[ $clock_diff_abs -gt 30 ]]; then
                    sync_status="WARNING"
                    issues+=("System/Hardware clock drift: ${clock_diff}s")
                fi
            fi
        fi
        
        # Check for chronyd or ntpd processes
        if pgrep -x "chronyd" &>/dev/null || pgrep -x "ntpd" &>/dev/null; then
            echo "✅ Time daemon is running"
        else
            echo "⚠️  No time daemon detected"
        fi
    fi
    
    # Generate monitoring report
    echo ""
    echo "=== Time Sync Status Report ==="
    echo "Overall Status: $sync_status"
    echo "Timestamp: $(date)"
    
    if [[ ${#issues[@]} -gt 0 ]]; then
        echo "Issues Found:"
        printf '  - %s\n' "${issues[@]}"
    else
        echo "✅ All time synchronization systems operational"
    fi
    
    # Log monitoring results
    log_operation "INFO" "Time sync monitoring completed: $sync_status (${#issues[@]} issues)"
    log_security_event "TIME_SYNC_CHECK" "status=$sync_status,issues=${#issues[@]}" "INFO"
    
    # Return appropriate exit code
    case "$sync_status" in
        "HEALTHY") return 0 ;;
        "WARNING") return 1 ;;
        "CRITICAL") return 2 ;;
        *) return 3 ;;
    esac
}

# Apply geographic policy
apply_geographic_policy() {
    local policy_name="$1"
    local admin_user=$(whoami)
    
    log_security_event "GEOGRAPHIC_POLICY_APPLY" "policy=$policy_name" "INFO"
    
    echo "=== Applying Geographic Policy ==="
    echo "Policy: $policy_name"
    echo "Administrator: $admin_user"
    echo ""
    
    # Check if policy exists
    if [[ -z "${GEOGRAPHIC_POLICIES[$policy_name]}" ]]; then
        echo "❌ Unknown geographic policy: $policy_name"
        echo ""
        echo "Available policies:"
        for policy in "${!GEOGRAPHIC_POLICIES[@]}"; do
            echo "  $policy -> ${GEOGRAPHIC_POLICIES[$policy]}"
        done
        return 1
    fi
    
    local target_timezone="${GEOGRAPHIC_POLICIES[$policy_name]}"
    
    echo "Target time zone: $target_timezone"
    echo "Policy mapping: $policy_name -> $target_timezone"
    echo ""
    
    # Apply the time zone change
    set_enterprise_timezone "$target_timezone" "geographic_policy"
}

# Generate time zone compliance report
generate_timezone_report() {
    local report_type="${1:-summary}"
    local admin_user=$(whoami)
    local report_file="/var/reports/timezone_report_$(date +%Y%m%d_%H%M%S).txt"
    
    mkdir -p "$(dirname "$report_file")"
    
    log_security_event "REPORT_GENERATION" "type=$report_type" "INFO"
    
    {
        echo "MacFleet Time Zone Management Report"
        echo "==================================="
        echo "Report Type: $report_type"
        echo "Generated: $(date)"
        echo "Generated By: $admin_user"
        echo "Hostname: $(hostname)"
        echo ""
        
        case "$report_type" in
            "summary")
                echo "== Time Zone Summary =="
                get_current_timezone
                
                echo "Geographic Policies Available:"
                for policy in "${!GEOGRAPHIC_POLICIES[@]}"; do
                    echo "  $policy: ${GEOGRAPHIC_POLICIES[$policy]}"
                done
                ;;
            "compliance")
                echo "== Compliance Assessment =="
                
                # Check compliance requirements
                local current_tz=$(systemsetup -gettimezone 2>/dev/null | awk -F': ' '{print $2}')
                local network_time=$(systemsetup -getusingnetworktime 2>/dev/null | awk -F': ' '{print $2}')
                local time_server=$(systemsetup -getnetworktimeserver 2>/dev/null | awk -F': ' '{print $2}')
                
                echo "Current Configuration:"
                echo "  Time Zone: $current_tz"
                echo "  Network Time Sync: $network_time"
                echo "  Time Server: $time_server"
                echo ""
                
                echo "Compliance Standards:"
                for standard in "${!COMPLIANCE_STANDARDS[@]}"; do
                    echo "  $standard: ${COMPLIANCE_STANDARDS[$standard]}"
                done
                ;;
            "audit")
                echo "== Audit Information =="
                if [[ -f "$AUDIT_LOG" ]]; then
                    echo "Recent time zone events (last 20):"
                    tail -20 "$AUDIT_LOG"
                else
                    echo "No audit log available"
                fi
                ;;
        esac
        
        echo ""
        echo "== System Time Information =="
        echo "Local Time: $(date)"
        echo "UTC Time: $(date -u)"
        echo "Uptime: $(uptime)"
        
    } > "$report_file"
    
    echo "Time zone report generated: $report_file"
    log_operation "INFO" "Time zone report generated: $report_file"
}

# Set business hours policy
set_business_hours_policy() {
    local policy_name="$1"
    local custom_hours="$2"
    
    echo "=== Business Hours Policy Configuration ==="
    echo "Policy: $policy_name"
    
    if [[ "$policy_name" == "custom" && -n "$custom_hours" ]]; then
        echo "Custom Hours: $custom_hours"
        BUSINESS_HOURS_POLICIES["custom"]="$custom_hours"
    fi
    
    local hours="${BUSINESS_HOURS_POLICIES[$policy_name]}"
    
    if [[ -z "$hours" ]]; then
        echo "❌ Unknown business hours policy: $policy_name"
        echo ""
        echo "Available policies:"
        for policy in "${!BUSINESS_HOURS_POLICIES[@]}"; do
            echo "  $policy: ${BUSINESS_HOURS_POLICIES[$policy]}"
        done
        return 1
    fi
    
    echo "Business Hours: $hours"
    
    # Save policy to configuration file
    local policy_file="$POLICIES_DIR/business_hours.conf"
    {
        echo "# MacFleet Business Hours Policy"
        echo "POLICY_NAME=$policy_name"
        echo "BUSINESS_HOURS=$hours"
        echo "CONFIGURED_BY=$(whoami)"
        echo "CONFIGURED_DATE=$(date)"
    } > "$policy_file"
    
    echo "✅ Business hours policy configured"
    log_operation "INFO" "Business hours policy set: $policy_name ($hours)"
}

# Main time zone management function
main() {
    local action="${1:-help}"
    
    case "$action" in
        "status"|"current")
            get_current_timezone
            ;;
        "list-timezones")
            local filter_region="$2"
            local format="${3:-grouped}"
            
            list_available_timezones "$filter_region" "$format"
            ;;
        "set")
            local timezone="$2"
            local policy="${3:-standard}"
            local force="$4"
            
            if [[ -z "$timezone" ]]; then
                echo "Usage: $0 set <timezone> [policy] [force]"
                echo "Example: $0 set America/New_York enterprise"
                return 1
            fi
            
            set_enterprise_timezone "$timezone" "$policy" "$force"
            ;;
        "validate")
            local timezone="$2"
            
            if [[ -z "$timezone" ]]; then
                echo "Usage: $0 validate <timezone>"
                return 1
            fi
            
            validate_timezone "$timezone"
            ;;
        "sync")
            local policy="${2:-standard}"
            
            configure_time_sync "$policy"
            ;;
        "monitor")
            local check_type="${2:-basic}"
            
            monitor_time_sync "$check_type"
            ;;
        "apply-policy")
            local policy_name="$2"
            
            if [[ -z "$policy_name" ]]; then
                echo "Usage: $0 apply-policy <policy_name>"
                echo ""
                echo "Available geographic policies:"
                for policy in "${!GEOGRAPHIC_POLICIES[@]}"; do
                    echo "  $policy"
                done
                return 1
            fi
            
            apply_geographic_policy "$policy_name"
            ;;
        "business-hours")
            local policy_name="$2"
            local custom_hours="$3"
            
            if [[ -z "$policy_name" ]]; then
                echo "Usage: $0 business-hours <policy> [custom_hours]"
                echo ""
                echo "Available policies:"
                for policy in "${!BUSINESS_HOURS_POLICIES[@]}"; do
                    echo "  $policy"
                done
                return 1
            fi
            
            set_business_hours_policy "$policy_name" "$custom_hours"
            ;;
        "report")
            local report_type="${2:-summary}"
            
            generate_timezone_report "$report_type"
            ;;
        "help"|*)
            echo "$SCRIPT_NAME v$VERSION"
            echo "Enterprise Time Zone and Date/Time Management"
            echo ""
            echo "Usage: $0 <action> [options]"
            echo ""
            echo "Actions:"
            echo "  status                                  - Show current time zone information"
            echo "  list-timezones [region] [format]        - List available time zones"
            echo "  set <timezone> [policy] [force]         - Set time zone with policy"
            echo "  validate <timezone>                     - Validate time zone format"
            echo "  sync [policy]                           - Configure time synchronization"
            echo "  monitor [type]                          - Monitor time synchronization"
            echo "  apply-policy <policy>                   - Apply geographic policy"
            echo "  business-hours <policy> [custom]        - Configure business hours"
            echo "  report [type]                           - Generate time zone reports"
            echo "  help                                    - Show this help message"
            echo ""
            echo "Geographic Policies:"
            for policy in "${!GEOGRAPHIC_POLICIES[@]}"; do
                echo "  $policy"
            done
            echo ""
            echo "Time Sync Policies:"
            echo "  enterprise  - Use primary enterprise NTP server"
            echo "  secure      - Use secondary enterprise NTP server"
            echo "  standard    - Use Apple's time server (default)"
            echo "  public      - Use public NTP pool"
            echo ""
            echo "Business Hours Policies:"
            for policy in "${!BUSINESS_HOURS_POLICIES[@]}"; do
                echo "  $policy: ${BUSINESS_HOURS_POLICIES[$policy]}"
            done
            echo ""
            echo "Monitor Types:"
            echo "  basic       - Basic time sync status check"
            echo "  comprehensive - Extended monitoring and diagnostics"
            echo ""
            echo "Report Types:"
            echo "  summary     - Time zone overview (default)"
            echo "  compliance  - Compliance assessment"
            echo "  audit       - Audit trail and events"
            echo ""
            echo "Examples:"
            echo "  $0 set America/New_York enterprise      - Set Eastern time with enterprise policy"
            echo "  $0 apply-policy US_PACIFIC              - Apply US Pacific policy"
            echo "  $0 monitor comprehensive                - Full monitoring check"
            echo "  $0 business-hours extended              - Set extended business hours"
            echo ""
            echo "Features:"
            echo "  • Enterprise-grade time zone management"
            echo "  • Geographic policy automation"
            echo "  • Advanced time synchronization with fallback servers"
            echo "  • Real-time monitoring and drift detection"
            echo "  • Comprehensive audit logging and compliance"
            echo "  • Business hours policy enforcement"
            echo "  • Integration with MacFleet infrastructure"
            ;;
    esac
}

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

Quick Reference Commands

Basic Time Zone Operations

# Check current time zone status
./timezone_manager.sh status

# List available time zones
./timezone_manager.sh list-timezones

# Set time zone with enterprise policy
./timezone_manager.sh set America/New_York enterprise

# Validate time zone before setting
./timezone_manager.sh validate Europe/London

Geographic Policy Management

# Apply predefined geographic policies
./timezone_manager.sh apply-policy US_EAST
./timezone_manager.sh apply-policy EU_LONDON
./timezone_manager.sh apply-policy ASIA_TOKYO

# List all available geographic policies
./timezone_manager.sh apply-policy

Time Synchronization

# Configure time synchronization with different policies
./timezone_manager.sh sync enterprise    # Use enterprise NTP servers
./timezone_manager.sh sync standard      # Use Apple's time server
./timezone_manager.sh sync public        # Use public NTP pool

# Monitor time synchronization health
./timezone_manager.sh monitor basic
./timezone_manager.sh monitor comprehensive

Business Hours and Compliance

# Set business hours policies
./timezone_manager.sh business-hours standard     # 09:00-17:00
./timezone_manager.sh business-hours extended     # 08:00-18:00
./timezone_manager.sh business-hours 24x7         # 24/7 operations
./timezone_manager.sh business-hours custom "06:00-22:00"

# Generate compliance reports
./timezone_manager.sh report compliance
./timezone_manager.sh report audit

Integration Examples

JAMF Pro Integration

#!/bin/bash

# JAMF Pro script for time zone management
# Parameters: $4 = geographic_policy, $5 = sync_policy, $6 = business_hours

GEOGRAPHIC_POLICY="$4"
SYNC_POLICY="$5"
BUSINESS_HOURS="$6"

# Download time zone manager if not present
if [[ ! -f "/usr/local/bin/macfleet_timezone_manager.sh" ]]; then
    curl -o "/usr/local/bin/macfleet_timezone_manager.sh" \
         "https://scripts.macfleet.com/timezone_manager.sh"
    chmod +x "/usr/local/bin/macfleet_timezone_manager.sh"
fi

# Apply geographic policy
if [[ -n "$GEOGRAPHIC_POLICY" ]]; then
    /usr/local/bin/macfleet_timezone_manager.sh apply-policy "$GEOGRAPHIC_POLICY"
fi

# Configure time synchronization
if [[ -n "$SYNC_POLICY" ]]; then
    /usr/local/bin/macfleet_timezone_manager.sh sync "$SYNC_POLICY"
fi

# Set business hours
if [[ -n "$BUSINESS_HOURS" ]]; then
    /usr/local/bin/macfleet_timezone_manager.sh business-hours "$BUSINESS_HOURS"
fi

# Report status back to JAMF
echo "Time zone configuration completed successfully"

Automated Monitoring Script

#!/bin/bash

# Continuous time zone monitoring for enterprise compliance
monitor_timezone_continuous() {
    local monitoring_interval=300  # 5 minutes
    local alert_threshold=3
    local consecutive_failures=0
    
    while true; do
        # Run time sync monitoring
        if /usr/local/bin/macfleet_timezone_manager.sh monitor basic &>/dev/null; then
            consecutive_failures=0
            echo "$(date): Time zone monitoring passed"
        else
            consecutive_failures=$((consecutive_failures + 1))
            echo "$(date): Time zone monitoring failed ($consecutive_failures)"
            
            # Alert after consecutive failures
            if [[ $consecutive_failures -ge $alert_threshold ]]; then
                send_time_alert "Time synchronization issues detected" "CRITICAL"
                consecutive_failures=0
            fi
        fi
        
        sleep "$monitoring_interval"
    done
}

Advanced Features

Geographic Compliance Automation

# Automatic time zone detection based on IP geolocation
auto_detect_timezone() {
    local detected_country=$(curl -s "http://ip-api.com/line?fields=countryCode")
    local detected_timezone
    
    case "$detected_country" in
        "US")
            # Use more sophisticated detection for US
            detected_timezone=$(curl -s "http://ip-api.com/line?fields=timezone")
            ;;
        "GB")
            detected_timezone="Europe/London"
            ;;
        "DE")
            detected_timezone="Europe/Berlin"
            ;;
        "JP")
            detected_timezone="Asia/Tokyo"
            ;;
        *)
            detected_timezone="UTC"
            ;;
    esac
    
    echo "Detected time zone: $detected_timezone"
    
    # Apply detected time zone with validation
    if validate_timezone "$detected_timezone"; then
        set_enterprise_timezone "$detected_timezone" "auto_detected"
    fi
}

Compliance Auditing

# Enhanced compliance checking
enhanced_compliance_check() {
    local compliance_standard="$1"
    
    echo "=== Enhanced Compliance Check ==="
    echo "Standard: $compliance_standard"
    
    case "$compliance_standard" in
        "SOX")
            # Sarbanes-Oxley requires accurate time stamping
            check_time_accuracy_strict
            verify_audit_trail_integrity
            ;;
        "HIPAA")
            # HIPAA requires synchronized logging
            check_synchronized_logging
            verify_time_source_security
            ;;
        "PCI_DSS")
            # PCI DSS requires secure time synchronization
            check_secure_time_sync
            verify_ntp_security
            ;;
    esac
}

Best Practices

  1. Use enterprise NTP servers for consistent time synchronization
  2. Implement geographic policies for multi-location organizations
  3. Monitor time drift continuously with automated alerting
  4. Maintain audit trails for compliance requirements
  5. Test time server connectivity before deployment
  6. Use backup time servers for redundancy
  7. Coordinate with network teams for NTP server access
  8. Document time zone policies for business operations

This enterprise time zone management system provides comprehensive time and date control with automated geographic compliance, policy enforcement, and enterprise-grade monitoring capabilities for effective MacFleet time 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.