Tutorial

New updates and improvements to Macfleet.

Remote Management and Secure Access Control on macOS

Implement comprehensive remote management and secure access control across your MacFleet devices. This tutorial covers Apple Remote Desktop configuration, multi-protocol remote access management, security policy enforcement, compliance frameworks, and automated fleet-wide deployment for enterprise environments.

Understanding macOS Remote Management

macOS provides multiple remote management protocols and services:

  • Apple Remote Desktop (ARD) - Native macOS remote desktop solution with comprehensive management features
  • SSH (Secure Shell) - Command-line remote access with strong encryption
  • VNC (Virtual Network Computing) - Cross-platform remote desktop protocol
  • Screen Sharing - Built-in macOS screen sharing functionality
  • Remote Login - Terminal-based remote access
  • Apple Configurator - Device configuration and management tool

Basic Remote Management Configuration

Enable Apple Remote Desktop

#!/bin/bash

# Enable Apple Remote Desktop with basic configuration
enable_remote_desktop() {
    echo "=== Enabling Apple Remote Desktop ==="
    
    local kickstart_path="/System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart"
    
    if [[ ! -f "$kickstart_path" ]]; then
        echo "❌ ARD Agent not found on this system"
        return 1
    fi
    
    # Activate Remote Management
    if sudo "$kickstart_path" -activate; then
        echo "✅ Apple Remote Desktop activated successfully"
    else
        echo "❌ Failed to activate Apple Remote Desktop"
        return 1
    fi
    
    # Configure basic settings
    sudo "$kickstart_path" -configure -allowAccessFor -allUsers -privs -all
    
    # Restart ARD Agent
    sudo "$kickstart_path" -restart -agent
    
    echo "✅ Apple Remote Desktop configuration completed"
    return 0
}

# Execute function
enable_remote_desktop

Disable Remote Management

#!/bin/bash

# Disable Apple Remote Desktop
disable_remote_desktop() {
    echo "=== Disabling Apple Remote Desktop ==="
    
    local kickstart_path="/System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart"
    
    if [[ ! -f "$kickstart_path" ]]; then
        echo "❌ ARD Agent not found on this system"
        return 1
    fi
    
    # Deactivate Remote Management
    if sudo "$kickstart_path" -deactivate; then
        echo "✅ Apple Remote Desktop deactivated successfully"
    else
        echo "❌ Failed to deactivate Apple Remote Desktop"
        return 1
    fi
    
    return 0
}

# Execute function
disable_remote_desktop

Configure User-Specific Access

#!/bin/bash

# Configure Remote Management for specific users
configure_user_access() {
    local target_users="$1"
    local privileges="$2"
    
    echo "=== Configuring User-Specific Remote Access ==="
    
    local kickstart_path="/System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart"
    
    if [[ -z "$target_users" ]]; then
        echo "❌ Target users required"
        echo "Usage: configure_user_access 'user1,user2' 'privileges'"
        return 1
    fi
    
    # Activate with specified users
    sudo "$kickstart_path" -activate -configure -allowAccessFor -specifiedUsers
    
    # Configure user privileges
    IFS=',' read -ra USERS <<< "$target_users"
    for user in "${USERS[@]}"; do
        if id "$user" &>/dev/null; then
            sudo "$kickstart_path" -configure -users "$user" -access -on -privs -all
            echo "✅ Configured access for user: $user"
        else
            echo "⚠️  User not found: $user"
        fi
    done
    
    return 0
}

# Usage example
# configure_user_access "admin,support" "all"

Enterprise Remote Management System

#!/bin/bash

# MacFleet Enterprise Remote Management System
# Comprehensive remote access control, security compliance, and fleet management

# Configuration
LOG_FILE="/var/log/macfleet_remote_management.log"
CONFIG_DIR="/etc/macfleet/remote_management"
POLICIES_DIR="$CONFIG_DIR/policies"
REPORTS_DIR="$CONFIG_DIR/reports"
COMPLIANCE_DIR="$CONFIG_DIR/compliance"
SECURITY_DIR="$CONFIG_DIR/security"
SESSION_DIR="$CONFIG_DIR/sessions"

# Remote access protocols
declare -A REMOTE_PROTOCOLS=(
    ["ard"]="Apple Remote Desktop"
    ["ssh"]="Secure Shell"
    ["vnc"]="Virtual Network Computing"
    ["screen_sharing"]="macOS Screen Sharing"
    ["remote_login"]="Terminal Remote Login"
)

# Security compliance frameworks
declare -A COMPLIANCE_FRAMEWORKS=(
    ["nist"]="access_control,encryption_in_transit,session_management,audit_trails"
    ["iso27001"]="secure_remote_access,access_control,monitoring,documentation"
    ["cis"]="secure_protocols,authentication,session_limits,logging"
    ["sox"]="financial_access_control,audit_requirements,change_management"
    ["hipaa"]="minimum_necessary,access_controls,audit_logs,encryption"
    ["pci_dss"]="secure_protocols,access_control,monitoring,encryption"
)

# Access privilege levels
declare -A PRIVILEGE_LEVELS=(
    ["view_only"]="observe,report"
    ["control"]="observe,control,interact"
    ["manage"]="observe,control,interact,copy_files,restart"
    ["admin"]="observe,control,interact,copy_files,restart,change_settings"
    ["full"]="all_privileges"
)

# Security policies
declare -A SECURITY_POLICIES=(
    ["strict"]="mfa_required,encryption_mandatory,session_timeout_15min,audit_all"
    ["standard"]="password_auth,encryption_preferred,session_timeout_30min,audit_admin"
    ["relaxed"]="basic_auth,session_timeout_60min,audit_changes"
    ["compliance"]="enterprise_auth,full_encryption,session_timeout_10min,comprehensive_audit"
)

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

# Setup directories
setup_directories() {
    for dir in "$CONFIG_DIR" "$POLICIES_DIR" "$REPORTS_DIR" "$COMPLIANCE_DIR" "$SECURITY_DIR" "$SESSION_DIR"; do
        if [[ ! -d "$dir" ]]; then
            mkdir -p "$dir"
            log_action "Created directory: $dir"
        fi
    done
}

# Check current remote management status
check_remote_management_status() {
    echo "=== Remote Management Status Check ==="
    
    local status_report="$REPORTS_DIR/remote_status_$(date '+%Y%m%d_%H%M%S').json"
    
    cat > "$status_report" << EOF
{
    "status_metadata": {
        "timestamp": "$(date -Iseconds)",
        "hostname": "$(hostname)",
        "os_version": "$(sw_vers -productVersion)"
    },
    "remote_services": {
EOF

    local first=true
    
    # Check Apple Remote Desktop
    local ard_status="disabled"
    if ps aux | grep -q "ARDAgent" && ! echo "$!" | grep -q "grep"; then
        ard_status="enabled"
    fi
    
    cat >> "$status_report" << EOF
        "apple_remote_desktop": {
            "status": "$ard_status",
            "process_running": $(pgrep -q ARDAgent && echo "true" || echo "false"),
            "port": "5900"
        },
EOF

    # Check SSH
    local ssh_status="disabled"
    if sudo systemsetup -getremotelogin | grep -q "On"; then
        ssh_status="enabled"
    fi
    
    cat >> "$status_report" << EOF
        "ssh": {
            "status": "$ssh_status",
            "port": "22",
            "service_running": $(launchctl list | grep -q "com.openssh.sshd" && echo "true" || echo "false")
        },
EOF

    # Check VNC/Screen Sharing
    local vnc_status="disabled"
    if launchctl list | grep -q "com.apple.screensharing"; then
        vnc_status="enabled"
    fi
    
    cat >> "$status_report" << EOF
        "screen_sharing": {
            "status": "$vnc_status",
            "port": "5900",
            "service_running": $(launchctl list | grep -q "com.apple.screensharing" && echo "true" || echo "false")
        }
    },
    "security_assessment": $(assess_remote_security),
    "active_sessions": $(get_active_remote_sessions)
}
EOF

    log_action "✅ Remote management status check completed: $status_report"
    echo "$status_report"
}

# Assess remote access security
assess_remote_security() {
    local security_score=0
    local total_checks=10
    
    # Check encryption
    if sudo systemsetup -getremotelogin | grep -q "On"; then
        security_score=$((security_score + 2))  # SSH is encrypted
    fi
    
    # Check firewall status
    if sudo /usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate | grep -q "enabled"; then
        security_score=$((security_score + 2))
    fi
    
    # Check for password complexity
    if pwpolicy -getaccountpolicies 2>/dev/null | grep -q "minLength"; then
        security_score=$((security_score + 1))
    fi
    
    # Check for failed login attempts
    local failed_attempts
    failed_attempts=$(grep "authentication failure" /var/log/auth.log 2>/dev/null | wc -l || echo 0)
    if [[ $failed_attempts -lt 10 ]]; then
        security_score=$((security_score + 1))
    fi
    
    # Check for active monitoring
    if [[ -f "$LOG_FILE" ]]; then
        security_score=$((security_score + 1))
    fi
    
    # Additional security checks
    security_score=$((security_score + 3))  # Placeholder for additional checks
    
    local security_percentage
    security_percentage=$(awk "BEGIN {printf \"%.0f\", ($security_score/$total_checks)*100}")
    
    local risk_level="low"
    if [[ $security_percentage -lt 60 ]]; then
        risk_level="high"
    elif [[ $security_percentage -lt 80 ]]; then
        risk_level="medium"
    fi
    
    echo "{\"score\": $security_score, \"percentage\": $security_percentage, \"risk_level\": \"$risk_level\"}"
}

# Get active remote sessions
get_active_remote_sessions() {
    local sessions='['
    local first=true
    
    # Check for SSH sessions
    local ssh_sessions
    ssh_sessions=$(who | grep "pts/" || echo "")
    
    while IFS= read -r session; do
        if [[ -n "$session" ]]; then
            if [[ "$first" == true ]]; then
                first=false
            else
                sessions+=','
            fi
            
            local user
            user=$(echo "$session" | awk '{print $1}')
            local terminal
            terminal=$(echo "$session" | awk '{print $2}')
            local login_time
            login_time=$(echo "$session" | awk '{print $3, $4}')
            local remote_host
            remote_host=$(echo "$session" | awk '{print $5}' | tr -d '()')
            
            sessions+="{\"type\": \"ssh\", \"user\": \"$user\", \"terminal\": \"$terminal\", \"login_time\": \"$login_time\", \"remote_host\": \"$remote_host\"}"
        fi
    done <<< "$ssh_sessions"
    
    # Check for VNC/ARD sessions
    local vnc_sessions
    vnc_sessions=$(netstat -an | grep ":5900" | grep "ESTABLISHED" || echo "")
    
    while IFS= read -r connection; do
        if [[ -n "$connection" ]]; then
            if [[ "$first" == true ]]; then
                first=false
            else
                sessions+=','
            fi
            
            local remote_ip
            remote_ip=$(echo "$connection" | awk '{print $5}' | cut -d: -f1)
            
            sessions+="{\"type\": \"vnc_ard\", \"remote_ip\": \"$remote_ip\", \"port\": \"5900\"}"
        fi
    done <<< "$vnc_sessions"
    
    sessions+=']'
    echo "$sessions"
}

# Configure enterprise remote access
configure_enterprise_remote_access() {
    local access_policy="$1"
    local target_protocols="$2"
    local user_groups="$3"
    
    log_action "Configuring enterprise remote access with policy: $access_policy"
    
    # Parse policy configuration
    local policy_config="${SECURITY_POLICIES[$access_policy]}"
    if [[ -z "$policy_config" ]]; then
        log_action "❌ Unknown security policy: $access_policy"
        return 1
    fi
    
    # Configure each specified protocol
    IFS=',' read -ra PROTOCOLS <<< "$target_protocols"
    for protocol in "${PROTOCOLS[@]}"; do
        case "$protocol" in
            "ard")
                configure_ard_enterprise "$access_policy" "$user_groups"
                ;;
            "ssh")
                configure_ssh_enterprise "$access_policy" "$user_groups"
                ;;
            "vnc")
                configure_vnc_enterprise "$access_policy" "$user_groups"
                ;;
            "screen_sharing")
                configure_screen_sharing_enterprise "$access_policy" "$user_groups"
                ;;
            *)
                log_action "⚠️  Unknown protocol: $protocol"
                ;;
        esac
    done
    
    # Apply security policy settings
    apply_security_policy_settings "$access_policy"
    
    log_action "✅ Enterprise remote access configuration completed"
}

# Configure Apple Remote Desktop for enterprise
configure_ard_enterprise() {
    local policy="$1"
    local user_groups="$2"
    
    echo "🖥️  Configuring Apple Remote Desktop for enterprise"
    
    local kickstart_path="/System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart"
    
    # Activate ARD
    sudo "$kickstart_path" -activate -restart
    
    # Configure based on policy
    case "$policy" in
        "strict"|"compliance")
            # Restricted access with specific users only
            sudo "$kickstart_path" -configure -allowAccessFor -specifiedUsers
            sudo "$kickstart_path" -configure -privs -observe -control -interact
            ;;
        "standard")
            # Standard configuration
            sudo "$kickstart_path" -configure -allowAccessFor -specifiedUsers
            sudo "$kickstart_path" -configure -privs -observe -control
            ;;
        "relaxed")
            # More permissive configuration
            sudo "$kickstart_path" -configure -allowAccessFor -allUsers
            sudo "$kickstart_path" -configure -privs -all
            ;;
    esac
    
    # Configure specific users if provided
    if [[ -n "$user_groups" ]]; then
        IFS=',' read -ra GROUPS <<< "$user_groups"
        for group in "${GROUPS[@]}"; do
            # Add users from group to ARD access
            local group_users
            group_users=$(dscl . -read "/Groups/$group" GroupMembership 2>/dev/null | cut -d: -f2)
            
            for user in $group_users; do
                if id "$user" &>/dev/null; then
                    sudo "$kickstart_path" -configure -users "$user" -access -on
                    log_action "Added ARD access for user: $user"
                fi
            done
        done
    fi
    
    # Create ARD configuration backup
    local ard_config="$SECURITY_DIR/ard_config_$(date '+%Y%m%d_%H%M%S').conf"
    cat > "$ard_config" << EOF
# Apple Remote Desktop Configuration
# Policy: $policy
# Configured: $(date)

POLICY="$policy"
USER_GROUPS="$user_groups"
CONFIGURATION_DATE="$(date -Iseconds)"
ARD_STATUS="enabled"
ACCESS_CONTROL="specified_users"
EOF

    log_action "✅ ARD enterprise configuration completed"
}

# Configure SSH for enterprise
configure_ssh_enterprise() {
    local policy="$1"
    local user_groups="$2"
    
    echo "🔐 Configuring SSH for enterprise"
    
    # Enable SSH (Remote Login)
    sudo systemsetup -setremotelogin on
    
    # Configure SSH security based on policy
    local sshd_config="/etc/ssh/sshd_config"
    local custom_config="$SECURITY_DIR/ssh_custom_config"
    
    case "$policy" in
        "strict"|"compliance")
            cat > "$custom_config" << EOF
# Enterprise SSH Configuration - Strict Policy
Protocol 2
PermitRootLogin no
PasswordAuthentication yes
PubkeyAuthentication yes
MaxAuthTries 3
ClientAliveInterval 300
ClientAliveCountMax 2
MaxSessions 5
LoginGraceTime 60
PermitEmptyPasswords no
ChallengeResponseAuthentication no
UsePAM yes
EOF
            ;;
        "standard")
            cat > "$custom_config" << EOF
# Enterprise SSH Configuration - Standard Policy
Protocol 2
PermitRootLogin no
PasswordAuthentication yes
PubkeyAuthentication yes
MaxAuthTries 5
ClientAliveInterval 600
ClientAliveCountMax 3
MaxSessions 10
LoginGraceTime 120
PermitEmptyPasswords no
EOF
            ;;
        "relaxed")
            cat > "$custom_config" << EOF
# Enterprise SSH Configuration - Relaxed Policy
Protocol 2
PermitRootLogin no
PasswordAuthentication yes
PubkeyAuthentication yes
MaxAuthTries 10
ClientAliveInterval 900
MaxSessions 20
EOF
            ;;
    esac
    
    # Backup original config and apply custom configuration
    if [[ -f "$sshd_config" ]]; then
        sudo cp "$sshd_config" "$sshd_config.backup.$(date '+%Y%m%d_%H%M%S')"
    fi
    
    # Apply custom SSH configuration
    sudo cp "$custom_config" "/etc/ssh/sshd_config.d/macfleet_enterprise.conf"
    
    # Restart SSH service
    sudo launchctl unload /System/Library/LaunchDaemons/ssh.plist 2>/dev/null
    sudo launchctl load /System/Library/LaunchDaemons/ssh.plist
    
    log_action "✅ SSH enterprise configuration completed"
}

# Monitor remote access sessions
monitor_remote_sessions() {
    log_action "Starting remote session monitoring"
    
    local monitoring_report="$SESSION_DIR/session_monitoring_$(date '+%Y%m%d_%H%M%S').json"
    
    cat > "$monitoring_report" << EOF
{
    "monitoring_metadata": {
        "timestamp": "$(date -Iseconds)",
        "hostname": "$(hostname)",
        "monitoring_period": "real_time"
    },
    "active_sessions": $(get_active_remote_sessions),
    "session_analytics": {
        "total_active_sessions": $(get_active_remote_sessions | jq '. | length'),
        "protocols_in_use": $(get_protocols_in_use),
        "unique_remote_hosts": $(get_unique_remote_hosts),
        "session_duration_analysis": $(analyze_session_durations)
    },
    "security_events": $(detect_security_events)
}
EOF

    log_action "✅ Remote session monitoring completed: $monitoring_report"
    echo "$monitoring_report"
}

# Detect security events
detect_security_events() {
    local events='['
    local first=true
    
    # Check for failed login attempts
    local failed_logins
    failed_logins=$(grep "authentication failure" /var/log/auth.log 2>/dev/null | tail -10)
    
    while IFS= read -r event; do
        if [[ -n "$event" ]]; then
            if [[ "$first" == true ]]; then
                first=false
            else
                events+=','
            fi
            
            local timestamp
            timestamp=$(echo "$event" | awk '{print $1, $2, $3}')
            local user
            user=$(echo "$event" | grep -o "user=[^ ]*" | cut -d= -f2 || echo "unknown")
            
            events+="{\"type\": \"failed_login\", \"timestamp\": \"$timestamp\", \"user\": \"$user\", \"severity\": \"medium\"}"
        fi
    done <<< "$failed_logins"
    
    # Check for unusual connection patterns
    local unusual_connections
    unusual_connections=$(netstat -an | grep ":22\|:5900" | grep "ESTABLISHED" | wc -l)
    
    if [[ $unusual_connections -gt 10 ]]; then
        if [[ "$first" == true ]]; then
            first=false
        else
            events+=','
        fi
        
        events+="{\"type\": \"high_connection_count\", \"count\": $unusual_connections, \"severity\": \"high\"}"
    fi
    
    events+=']'
    echo "$events"
}

# Generate compliance report
generate_compliance_report() {
    local framework="$1"
    
    log_action "Generating remote access compliance report for: $framework"
    
    local compliance_report="$COMPLIANCE_DIR/remote_compliance_${framework}_$(date '+%Y%m%d_%H%M%S').json"
    
    cat > "$compliance_report" << EOF
{
    "compliance_metadata": {
        "timestamp": "$(date -Iseconds)",
        "framework": "$framework",
        "hostname": "$(hostname)",
        "generator": "MacFleet Remote Management Compliance"
    },
    "framework_requirements": $(get_framework_requirements "$framework"),
    "compliance_assessment": {
        "overall_score": $(calculate_compliance_score "$framework"),
        "protocol_compliance": $(assess_protocol_compliance "$framework"),
        "security_compliance": $(assess_security_compliance "$framework"),
        "access_control_compliance": $(assess_access_control_compliance "$framework")
    },
    "recommendations": $(generate_compliance_recommendations "$framework"),
    "remediation_actions": $(generate_remediation_actions "$framework")
}
EOF

    log_action "✅ Compliance report generated: $compliance_report"
    echo "$compliance_report"
}

# Calculate compliance score
calculate_compliance_score() {
    local framework="$1"
    
    local total_score=0
    local check_count=0
    
    # Basic compliance checks
    check_count=$((check_count + 1))
    if sudo /usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate | grep -q "enabled"; then
        total_score=$((total_score + 20))
    fi
    
    check_count=$((check_count + 1))
    if [[ -f "$LOG_FILE" ]]; then
        total_score=$((total_score + 20))
    fi
    
    check_count=$((check_count + 1))
    if sudo systemsetup -getremotelogin | grep -q "On"; then
        total_score=$((total_score + 15))  # SSH encryption
    fi
    
    check_count=$((check_count + 1))
    if [[ -d "$SECURITY_DIR" ]]; then
        total_score=$((total_score + 15))
    fi
    
    # Framework-specific checks
    case "$framework" in
        "nist"|"iso27001")
            check_count=$((check_count + 1))
            if [[ -f "$SECURITY_DIR/ard_config"* ]]; then
                total_score=$((total_score + 15))
            fi
            
            check_count=$((check_count + 1))
            if [[ -f "/etc/ssh/sshd_config.d/macfleet_enterprise.conf" ]]; then
                total_score=$((total_score + 15))
            fi
            ;;
    esac
    
    local final_score
    final_score=$(awk "BEGIN {printf \"%.0f\", ($total_score/$check_count)}")
    
    echo "$final_score"
}

# Apply automated security policies
apply_automated_security_policies() {
    local policy_type="$1"
    
    log_action "Applying automated security policies: $policy_type"
    
    case "$policy_type" in
        "session_timeout")
            configure_session_timeouts
            ;;
        "failed_login_protection")
            configure_failed_login_protection
            ;;
        "encryption_enforcement")
            enforce_encryption_policies
            ;;
        "access_logging")
            configure_comprehensive_logging
            ;;
        *)
            log_action "⚠️  Unknown policy type: $policy_type"
            return 1
            ;;
    esac
    
    log_action "✅ Automated security policies applied"
}

# Configure session timeouts
configure_session_timeouts() {
    echo "⏰ Configuring session timeouts"
    
    # SSH session timeouts (already configured in SSH enterprise setup)
    # ARD session timeout configuration
    local timeout_config="$SECURITY_DIR/session_timeouts.conf"
    
    cat > "$timeout_config" << EOF
# Session Timeout Configuration
SSH_CLIENT_ALIVE_INTERVAL=300
SSH_CLIENT_ALIVE_COUNT_MAX=2
ARD_SESSION_TIMEOUT=1800
VNC_SESSION_TIMEOUT=1800
SCREEN_SHARING_TIMEOUT=1800
IDLE_DISCONNECT_TIME=900
EOF

    log_action "✅ Session timeouts configured"
}

# Main execution function
main() {
    local action="${1:-status}"
    local parameter="$2"
    local additional_param="$3"
    local extra_param="$4"
    
    log_action "=== MacFleet Remote Management Started ==="
    log_action "Action: $action"
    log_action "Parameter: ${parameter:-N/A}"
    
    setup_directories
    
    case "$action" in
        "enable")
            if [[ -z "$parameter" ]]; then
                enable_remote_desktop
            else
                configure_enterprise_remote_access "$parameter" "${additional_param:-ard}" "$extra_param"
            fi
            ;;
        "disable")
            disable_remote_desktop
            ;;
        "status")
            check_remote_management_status
            ;;
        "configure")
            if [[ -z "$parameter" || -z "$additional_param" ]]; then
                echo "Usage: $0 configure <policy> <protocols> [user_groups]"
                echo "Policies: ${!SECURITY_POLICIES[*]}"
                echo "Protocols: ${!REMOTE_PROTOCOLS[*]}"
                exit 1
            fi
            configure_enterprise_remote_access "$parameter" "$additional_param" "$extra_param"
            ;;
        "monitor")
            monitor_remote_sessions
            ;;
        "compliance")
            if [[ -z "$parameter" ]]; then
                echo "Available compliance frameworks:"
                for framework in "${!COMPLIANCE_FRAMEWORKS[@]}"; do
                    echo "  - $framework: ${COMPLIANCE_FRAMEWORKS[$framework]}"
                done
                echo ""
                echo "Usage: $0 compliance <framework>"
                exit 1
            fi
            generate_compliance_report "$parameter"
            ;;
        "users")
            if [[ -z "$parameter" || -z "$additional_param" ]]; then
                echo "Usage: $0 users <user_list> <privileges>"
                echo "Example: $0 users 'admin,support' 'control'"
                exit 1
            fi
            configure_user_access "$parameter" "$additional_param"
            ;;
        "security")
            if [[ -z "$parameter" ]]; then
                echo "Available security policies:"
                echo "  - session_timeout"
                echo "  - failed_login_protection"
                echo "  - encryption_enforcement"
                echo "  - access_logging"
                echo ""
                echo "Usage: $0 security <policy_type>"
                exit 1
            fi
            apply_automated_security_policies "$parameter"
            ;;
        *)
            echo "Usage: $0 {enable|disable|status|configure|monitor|compliance|users|security}"
            echo "  enable      - Enable basic remote management or configure enterprise policy"
            echo "  disable     - Disable remote management"
            echo "  status      - Check current remote management status"
            echo "  configure   - Configure enterprise remote access with policies"
            echo "  monitor     - Monitor active remote sessions"
            echo "  compliance  - Generate compliance report"
            echo "  users       - Configure user-specific access"
            echo "  security    - Apply automated security policies"
            exit 1
            ;;
    esac
    
    log_action "=== Remote management operation completed ==="
}

# Execute main function
main "$@"

Advanced Remote Management Features

Multi-Protocol Session Management

#!/bin/bash

# Comprehensive multi-protocol session management
manage_multi_protocol_sessions() {
    echo "=== Multi-Protocol Session Management ==="
    
    local session_config="$SESSION_DIR/protocol_management.json"
    
    cat > "$session_config" << EOF
{
    "protocol_management": {
        "apple_remote_desktop": {
            "port": 5900,
            "encryption": "AES-128",
            "authentication": "system_accounts",
            "max_concurrent_sessions": 5,
            "session_timeout": 1800
        },
        "ssh": {
            "port": 22,
            "encryption": "AES-256",
            "authentication": "key_based_preferred",
            "max_concurrent_sessions": 10,
            "session_timeout": 3600
        },
        "vnc": {
            "port": 5900,
            "encryption": "optional",
            "authentication": "vnc_password",
            "max_concurrent_sessions": 3,
            "session_timeout": 1800
        },
        "screen_sharing": {
            "port": 5900,
            "encryption": "built_in",
            "authentication": "system_accounts",
            "max_concurrent_sessions": 2,
            "session_timeout": 2700
        }
    },
    "security_policies": {
        "force_encryption": true,
        "require_mfa": false,
        "log_all_sessions": true,
        "geographic_restrictions": false,
        "time_based_access": false
    }
}
EOF

    echo "📊 Multi-protocol session management configured: $session_config"
}

# Advanced security monitoring
advanced_security_monitoring() {
    echo "🔍 Advanced Security Monitoring"
    
    local monitoring_script="$SECURITY_DIR/advanced_monitoring.sh"
    
    cat > "$monitoring_script" << 'EOF'
#!/bin/bash

# Advanced Remote Access Security Monitoring

while true; do
    # Monitor connection attempts
    CONNECTION_ATTEMPTS=$(netstat -an | grep -E ":22|:5900" | grep "SYN_RECV" | wc -l)
    
    if [[ $CONNECTION_ATTEMPTS -gt 20 ]]; then
        logger "MacFleet: High number of remote connection attempts detected: $CONNECTION_ATTEMPTS"
        # Send alert
        echo "High connection attempts: $CONNECTION_ATTEMPTS" | mail -s "MacFleet Security Alert" security@company.com
    fi
    
    # Monitor failed authentication attempts
    FAILED_AUTH=$(grep "authentication failure" /var/log/auth.log | grep "$(date '+%Y-%m-%d')" | wc -l)
    
    if [[ $FAILED_AUTH -gt 10 ]]; then
        logger "MacFleet: High number of authentication failures: $FAILED_AUTH"
    fi
    
    # Monitor unusual remote access patterns
    UNIQUE_IPS=$(netstat -an | grep -E ":22|:5900" | grep "ESTABLISHED" | awk '{print $5}' | cut -d: -f1 | sort -u | wc -l)
    
    if [[ $UNIQUE_IPS -gt 5 ]]; then
        logger "MacFleet: Multiple unique remote IPs detected: $UNIQUE_IPS"
    fi
    
    sleep 300  # Check every 5 minutes
done
EOF

    chmod +x "$monitoring_script"
    echo "🔐 Advanced security monitoring script created"
}

Zero Trust Remote Access

#!/bin/bash

# Implement Zero Trust remote access principles
implement_zero_trust_remote_access() {
    echo "🛡️  Implementing Zero Trust Remote Access"
    
    local zero_trust_config="$SECURITY_DIR/zero_trust_config.json"
    
    cat > "$zero_trust_config" << EOF
{
    "zero_trust_principles": {
        "verify_explicitly": {
            "device_verification": true,
            "user_verification": true,
            "location_verification": true,
            "behavior_analysis": true
        },
        "least_privilege_access": {
            "session_based_permissions": true,
            "time_limited_access": true,
            "resource_specific_access": true,
            "privilege_escalation_monitoring": true
        },
        "assume_breach": {
            "continuous_monitoring": true,
            "anomaly_detection": true,
            "session_recording": true,
            "immediate_response": true
        }
    },
    "implementation_controls": {
        "device_trust_score": "required",
        "user_risk_assessment": "continuous",
        "network_segmentation": "enabled",
        "encrypted_channels_only": true,
        "session_isolation": true
    }
}
EOF

    echo "🎯 Zero Trust remote access configuration created"
}

Security Best Practices

🔐 Access Control and Authentication

  • Multi-factor authentication with enterprise identity integration
  • Role-based access control with granular permission management
  • Device trust verification with certificate-based authentication
  • Session-based access control with time-limited permissions

🛡️ Network Security and Encryption

  • End-to-end encryption for all remote protocols (AES-256)
  • VPN integration with secure tunnel establishment
  • Network segmentation with micro-perimeter enforcement
  • Traffic analysis with anomaly detection and threat intelligence

📊 Monitoring and Compliance

  • Real-time session monitoring with comprehensive logging
  • Compliance framework support (NIST, ISO 27001, CIS, SOX, HIPAA, PCI DSS)
  • Automated security assessment with risk scoring and alerts
  • Forensic capabilities with detailed audit trails and session recordings

🚀 Enterprise Operations

  • Fleet-wide deployment with centralized policy management
  • Automated provisioning with identity lifecycle integration
  • High availability with load balancing and failover capabilities
  • Integration ecosystem with SIEM, IAM, and security tools

Important Notes

  • Apple Remote Desktop requires appropriate licensing for enterprise use
  • SSH key management essential for secure enterprise deployments
  • Network firewall configuration required to complement device-level security
  • Regular security assessments needed to maintain compliance posture
  • User training critical for secure remote access practices
  • Incident response procedures must be established for security events

Reducing Motion and Transparency on macOS Devices

macOS provides various accessibility options to enhance user experience, particularly for users who are sensitive to visual effects or require optimized performance. The Display section of the Accessibility settings allows users to modify display settings to suit their needs, including options to reduce motion and transparency. This comprehensive guide provides scripts and techniques to manage these settings across Mac fleets.

Understanding Motion and Transparency Settings

Reduce Motion

The "Reduce Motion" setting alters interface animations to make them simpler and more visually comfortable. When enabled, it replaces complex animations with simpler cross-fade effects, reducing potential discomfort for users sensitive to motion.

Benefits:

  • Reduces eye strain and motion sickness
  • Improves performance on older hardware
  • Creates a more predictable user interface
  • Helps users with vestibular disorders or motion sensitivity

Reduce Transparency

The "Reduce Transparency" setting changes semi-transparent elements in the user interface to solid ones, removing the blur and transparency effects throughout the system.

Benefits:

  • Improves readability and contrast
  • Reduces visual distractions
  • Better performance on systems with limited graphics capabilities
  • Helps users with visual impairments

Prerequisites

Before configuring motion and transparency settings, ensure you have:

  • Administrative privileges on the Mac
  • Terminal or SSH access
  • Understanding of user context requirements
  • Backup of current settings (recommended)

Basic Configuration Commands

Understanding the Configuration Process

macOS accessibility settings are stored in user preferences and require specific approaches:

  • User Context: Settings must be applied for the correct user
  • Preference Files: Settings are stored in com.apple.universalaccess.plist
  • System Integration: Changes affect the entire user interface
  • Real-time Application: Settings take effect immediately

Current User Detection

Most accessibility settings require user context. Here's how to detect the current user:

#!/bin/bash

# Get current console user
get_current_user() {
    local current_user=$(ls -l /dev/console | awk '{ print $3 }')
    echo "$current_user"
}

# Get user home directory
get_user_home() {
    local username=$1
    local user_home=$(eval echo ~$username)
    echo "$user_home"
}

# Example usage
current_user=$(get_current_user)
user_home=$(get_user_home "$current_user")

echo "Current user: $current_user"
echo "User home: $user_home"

Basic Motion and Transparency Reduction

Simple Enable Script

Basic script to enable both reduce motion and reduce transparency:

#!/bin/bash

# Enable reduce motion and reduce transparency
echo "Configuring accessibility settings..."

# Get current user
loggedInUser=$(ls -l /dev/console | awk '{ print $3 }')

if [ -z "$loggedInUser" ] || [ "$loggedInUser" = "root" ]; then
    echo "Error: No valid user session found"
    exit 1
fi

echo "Configuring settings for user: $loggedInUser"

# Enable reduce motion
if su -l "$loggedInUser" -c "defaults write com.apple.universalaccess reduceMotion -bool true"; then
    echo "✓ Reduce motion enabled"
else
    echo "✗ Failed to enable reduce motion"
    exit 1
fi

# Enable reduce transparency
if su -l "$loggedInUser" -c "defaults write com.apple.universalaccess reduceTransparency -bool true"; then
    echo "✓ Reduce transparency enabled"
else
    echo "✗ Failed to enable reduce transparency"
    exit 1
fi

echo "Accessibility settings configured successfully"

Advanced Configuration Script

More comprehensive script with validation and logging:

#!/bin/bash

# Advanced accessibility configuration script
LOG_FILE="/var/log/accessibility_settings.log"
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')

# Configuration options
REDUCE_MOTION=${1:-true}
REDUCE_TRANSPARENCY=${2:-true}

# Function to log messages
log_message() {
    echo "[$TIMESTAMP] $1" | tee -a "$LOG_FILE"
}

# Function to validate boolean input
validate_boolean() {
    local value=$1
    local setting_name=$2
    
    if [[ "$value" != "true" && "$value" != "false" ]]; then
        log_message "ERROR: Invalid value for $setting_name: $value (must be true or false)"
        return 1
    fi
    
    return 0
}

# Function to get current accessibility settings
get_current_settings() {
    local username=$1
    
    log_message "Getting current accessibility settings for user: $username"
    
    # Get reduce motion setting
    local motion_setting=$(su -l "$username" -c "defaults read com.apple.universalaccess reduceMotion 2>/dev/null")
    if [ -z "$motion_setting" ]; then
        motion_setting="Not set"
    fi
    
    # Get reduce transparency setting
    local transparency_setting=$(su -l "$username" -c "defaults read com.apple.universalaccess reduceTransparency 2>/dev/null")
    if [ -z "$transparency_setting" ]; then
        transparency_setting="Not set"
    fi
    
    echo "Current Accessibility Settings:"
    echo "  Reduce Motion: $motion_setting"
    echo "  Reduce Transparency: $transparency_setting"
    
    log_message "Current settings - Motion: $motion_setting, Transparency: $transparency_setting"
}

# Function to configure reduce motion
configure_reduce_motion() {
    local username=$1
    local enable_motion=$2
    
    log_message "Configuring reduce motion to: $enable_motion for user: $username"
    
    if su -l "$username" -c "defaults write com.apple.universalaccess reduceMotion -bool $enable_motion"; then
        log_message "SUCCESS: Reduce motion set to $enable_motion"
        return 0
    else
        log_message "ERROR: Failed to configure reduce motion"
        return 1
    fi
}

# Function to configure reduce transparency
configure_reduce_transparency() {
    local username=$1
    local enable_transparency=$2
    
    log_message "Configuring reduce transparency to: $enable_transparency for user: $username"
    
    if su -l "$username" -c "defaults write com.apple.universalaccess reduceTransparency -bool $enable_transparency"; then
        log_message "SUCCESS: Reduce transparency set to $enable_transparency"
        return 0
    else
        log_message "ERROR: Failed to configure reduce transparency"
        return 1
    fi
}

# Function to verify settings
verify_settings() {
    local username=$1
    local expected_motion=$2
    local expected_transparency=$3
    
    log_message "Verifying accessibility settings for user: $username"
    
    # Verify reduce motion
    local actual_motion=$(su -l "$username" -c "defaults read com.apple.universalaccess reduceMotion 2>/dev/null")
    if [ "$actual_motion" = "$expected_motion" ]; then
        log_message "VERIFIED: Reduce motion correctly set to $expected_motion"
    else
        log_message "WARNING: Reduce motion verification failed. Expected: $expected_motion, Actual: $actual_motion"
    fi
    
    # Verify reduce transparency
    local actual_transparency=$(su -l "$username" -c "defaults read com.apple.universalaccess reduceTransparency 2>/dev/null")
    if [ "$actual_transparency" = "$expected_transparency" ]; then
        log_message "VERIFIED: Reduce transparency correctly set to $expected_transparency"
    else
        log_message "WARNING: Reduce transparency verification failed. Expected: $expected_transparency, Actual: $actual_transparency"
    fi
}

# Main execution
log_message "Starting accessibility configuration"

# Validate inputs
if ! validate_boolean "$REDUCE_MOTION" "reduce motion"; then
    exit 1
fi

if ! validate_boolean "$REDUCE_TRANSPARENCY" "reduce transparency"; then
    exit 1
fi

# Get current user
loggedInUser=$(ls -l /dev/console | awk '{ print $3 }')

if [ -z "$loggedInUser" ] || [ "$loggedInUser" = "root" ]; then
    log_message "ERROR: No valid user session found"
    exit 1
fi

log_message "Current user: $loggedInUser"

# Show current settings
get_current_settings "$loggedInUser"

# Configure reduce motion
if ! configure_reduce_motion "$loggedInUser" "$REDUCE_MOTION"; then
    log_message "Failed to configure reduce motion"
    exit 1
fi

# Configure reduce transparency
if ! configure_reduce_transparency "$loggedInUser" "$REDUCE_TRANSPARENCY"; then
    log_message "Failed to configure reduce transparency"
    exit 1
fi

# Verify settings
verify_settings "$loggedInUser" "$REDUCE_MOTION" "$REDUCE_TRANSPARENCY"

log_message "Accessibility configuration completed successfully"
echo "Accessibility settings configured successfully"
echo "Settings will be applied immediately"

Individual Setting Management

Reduce Motion Only

Script to manage only the reduce motion setting:

#!/bin/bash

# Reduce motion configuration script
LOG_FILE="/var/log/accessibility_settings.log"
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')

# Configuration
ENABLE_REDUCE_MOTION=${1:-true}

# Function to log messages
log_message() {
    echo "[$TIMESTAMP] $1" | tee -a "$LOG_FILE"
}

# Function to get current reduce motion setting
get_reduce_motion_status() {
    local username=$1
    
    local motion_setting=$(su -l "$username" -c "defaults read com.apple.universalaccess reduceMotion 2>/dev/null")
    
    if [ -z "$motion_setting" ]; then
        echo "Not configured"
    else
        if [ "$motion_setting" = "1" ]; then
            echo "Enabled"
        else
            echo "Disabled"
        fi
    fi
}

# Function to configure reduce motion
set_reduce_motion() {
    local username=$1
    local enable=$2
    
    log_message "Setting reduce motion to: $enable for user: $username"
    
    # Get current status
    local current_status=$(get_reduce_motion_status "$username")
    log_message "Current reduce motion status: $current_status"
    
    # Apply setting
    if su -l "$username" -c "defaults write com.apple.universalaccess reduceMotion -bool $enable"; then
        log_message "SUCCESS: Reduce motion configured"
        
        # Verify setting
        local new_status=$(get_reduce_motion_status "$username")
        log_message "New reduce motion status: $new_status"
        
        return 0
    else
        log_message "ERROR: Failed to configure reduce motion"
        return 1
    fi
}

# Main execution
log_message "Starting reduce motion configuration"

# Validate input
if [[ "$ENABLE_REDUCE_MOTION" != "true" && "$ENABLE_REDUCE_MOTION" != "false" ]]; then
    log_message "ERROR: Invalid value: $ENABLE_REDUCE_MOTION (must be true or false)"
    exit 1
fi

# Get current user
loggedInUser=$(ls -l /dev/console | awk '{ print $3 }')

if [ -z "$loggedInUser" ] || [ "$loggedInUser" = "root" ]; then
    log_message "ERROR: No valid user session found"
    exit 1
fi

log_message "Current user: $loggedInUser"

# Configure reduce motion
if set_reduce_motion "$loggedInUser" "$ENABLE_REDUCE_MOTION"; then
    log_message "Reduce motion configuration completed successfully"
    echo "✓ Reduce motion configured successfully"
    
    # Show explanation based on setting
    if [ "$ENABLE_REDUCE_MOTION" = "true" ]; then
        echo ""
        echo "Reduce Motion is now ENABLED:"
        echo "  - Interface animations are simplified"
        echo "  - Cross-fade effects replace complex animations"
        echo "  - Reduces potential motion sickness"
        echo "  - Improves performance on older hardware"
    else
        echo ""
        echo "Reduce Motion is now DISABLED:"
        echo "  - Full interface animations are restored"
        echo "  - Complex visual effects are enabled"
        echo "  - Standard macOS visual experience"
    fi
else
    log_message "Reduce motion configuration failed"
    exit 1
fi

Reduce Transparency Only

Script to manage only the reduce transparency setting:

#!/bin/bash

# Reduce transparency configuration script
LOG_FILE="/var/log/accessibility_settings.log"
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')

# Configuration
ENABLE_REDUCE_TRANSPARENCY=${1:-true}

# Function to log messages
log_message() {
    echo "[$TIMESTAMP] $1" | tee -a "$LOG_FILE"
}

# Function to get current reduce transparency setting
get_reduce_transparency_status() {
    local username=$1
    
    local transparency_setting=$(su -l "$username" -c "defaults read com.apple.universalaccess reduceTransparency 2>/dev/null")
    
    if [ -z "$transparency_setting" ]; then
        echo "Not configured"
    else
        if [ "$transparency_setting" = "1" ]; then
            echo "Enabled"
        else
            echo "Disabled"
        fi
    fi
}

# Function to configure reduce transparency
set_reduce_transparency() {
    local username=$1
    local enable=$2
    
    log_message "Setting reduce transparency to: $enable for user: $username"
    
    # Get current status
    local current_status=$(get_reduce_transparency_status "$username")
    log_message "Current reduce transparency status: $current_status"
    
    # Apply setting
    if su -l "$username" -c "defaults write com.apple.universalaccess reduceTransparency -bool $enable"; then
        log_message "SUCCESS: Reduce transparency configured"
        
        # Verify setting
        local new_status=$(get_reduce_transparency_status "$username")
        log_message "New reduce transparency status: $new_status"
        
        return 0
    else
        log_message "ERROR: Failed to configure reduce transparency"
        return 1
    fi
}

# Main execution
log_message "Starting reduce transparency configuration"

# Validate input
if [[ "$ENABLE_REDUCE_TRANSPARENCY" != "true" && "$ENABLE_REDUCE_TRANSPARENCY" != "false" ]]; then
    log_message "ERROR: Invalid value: $ENABLE_REDUCE_TRANSPARENCY (must be true or false)"
    exit 1
fi

# Get current user
loggedInUser=$(ls -l /dev/console | awk '{ print $3 }')

if [ -z "$loggedInUser" ] || [ "$loggedInUser" = "root" ]; then
    log_message "ERROR: No valid user session found"
    exit 1
fi

log_message "Current user: $loggedInUser"

# Configure reduce transparency
if set_reduce_transparency "$loggedInUser" "$ENABLE_REDUCE_TRANSPARENCY"; then
    log_message "Reduce transparency configuration completed successfully"
    echo "✓ Reduce transparency configured successfully"
    
    # Show explanation based on setting
    if [ "$ENABLE_REDUCE_TRANSPARENCY" = "true" ]; then
        echo ""
        echo "Reduce Transparency is now ENABLED:"
        echo "  - Semi-transparent elements become solid"
        echo "  - Dock, menu bar, and sidebars are opaque"
        echo "  - Improved readability and contrast"
        echo "  - Better performance on older hardware"
    else
        echo ""
        echo "Reduce Transparency is now DISABLED:"
        echo "  - Semi-transparent elements are restored"
        echo "  - Blur and transparency effects are enabled"
        echo "  - Standard macOS visual experience"
    fi
else
    log_message "Reduce transparency configuration failed"
    exit 1
fi

Comprehensive Accessibility Management

All-in-One Accessibility Script

Script to manage multiple accessibility settings:

#!/bin/bash

# Comprehensive accessibility configuration script
LOG_FILE="/var/log/accessibility_settings.log"
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')

# Configuration options
REDUCE_MOTION=${1:-true}
REDUCE_TRANSPARENCY=${2:-true}
INCREASE_CONTRAST=${3:-false}
DIFFERENTIATE_WITHOUT_COLOR=${4:-false}

# Function to log messages
log_message() {
    echo "[$TIMESTAMP] $1" | tee -a "$LOG_FILE"
}

# Function to get all accessibility settings
get_all_accessibility_settings() {
    local username=$1
    
    log_message "Getting all accessibility settings for user: $username"
    
    # Get various accessibility settings
    local motion=$(su -l "$username" -c "defaults read com.apple.universalaccess reduceMotion 2>/dev/null" || echo "Not set")
    local transparency=$(su -l "$username" -c "defaults read com.apple.universalaccess reduceTransparency 2>/dev/null" || echo "Not set")
    local contrast=$(su -l "$username" -c "defaults read com.apple.universalaccess increaseContrast 2>/dev/null" || echo "Not set")
    local diff_color=$(su -l "$username" -c "defaults read com.apple.universalaccess differentiateWithoutColor 2>/dev/null" || echo "Not set")
    
    echo "Current Accessibility Settings:"
    echo "================================"
    echo "  Reduce Motion: $motion"
    echo "  Reduce Transparency: $transparency"
    echo "  Increase Contrast: $contrast"
    echo "  Differentiate Without Color: $diff_color"
    echo ""
    
    log_message "Current settings - Motion: $motion, Transparency: $transparency, Contrast: $contrast, Color: $diff_color"
}

# Function to configure all accessibility settings
configure_all_accessibility() {
    local username=$1
    local motion=$2
    local transparency=$3
    local contrast=$4
    local diff_color=$5
    
    log_message "Configuring all accessibility settings for user: $username"
    
    local success=0
    
    # Configure reduce motion
    if su -l "$username" -c "defaults write com.apple.universalaccess reduceMotion -bool $motion"; then
        log_message "SUCCESS: Reduce motion set to $motion"
    else
        log_message "ERROR: Failed to set reduce motion"
        success=1
    fi
    
    # Configure reduce transparency
    if su -l "$username" -c "defaults write com.apple.universalaccess reduceTransparency -bool $transparency"; then
        log_message "SUCCESS: Reduce transparency set to $transparency"
    else
        log_message "ERROR: Failed to set reduce transparency"
        success=1
    fi
    
    # Configure increase contrast
    if su -l "$username" -c "defaults write com.apple.universalaccess increaseContrast -bool $contrast"; then
        log_message "SUCCESS: Increase contrast set to $contrast"
    else
        log_message "ERROR: Failed to set increase contrast"
        success=1
    fi
    
    # Configure differentiate without color
    if su -l "$username" -c "defaults write com.apple.universalaccess differentiateWithoutColor -bool $diff_color"; then
        log_message "SUCCESS: Differentiate without color set to $diff_color"
    else
        log_message "ERROR: Failed to set differentiate without color"
        success=1
    fi
    
    return $success
}

# Function to create accessibility report
create_accessibility_report() {
    local username=$1
    local report_file="/tmp/accessibility_report_${username}.txt"
    
    log_message "Creating accessibility report for user: $username"
    
    {
        echo "Accessibility Configuration Report"
        echo "=================================="
        echo "User: $username"
        echo "Date: $(date)"
        echo ""
        echo "Configured Settings:"
        echo "  Reduce Motion: $REDUCE_MOTION"
        echo "  Reduce Transparency: $REDUCE_TRANSPARENCY"
        echo "  Increase Contrast: $INCREASE_CONTRAST"
        echo "  Differentiate Without Color: $DIFFERENTIATE_WITHOUT_COLOR"
        echo ""
        echo "Impact on User Experience:"
        echo "-------------------------"
        
        if [ "$REDUCE_MOTION" = "true" ]; then
            echo "• Reduced motion effects - smoother experience for motion-sensitive users"
        fi
        
        if [ "$REDUCE_TRANSPARENCY" = "true" ]; then
            echo "• Solid interface elements - improved readability and performance"
        fi
        
        if [ "$INCREASE_CONTRAST" = "true" ]; then
            echo "• Enhanced contrast - better visibility for users with visual impairments"
        fi
        
        if [ "$DIFFERENTIATE_WITHOUT_COLOR" = "true" ]; then
            echo "• Color-independent differentiation - accessibility for colorblind users"
        fi
        
        echo ""
        echo "System Performance:"
        echo "• Reduced GPU usage from disabled effects"
        echo "• Improved battery life on laptops"
        echo "• Better performance on older hardware"
        
    } > "$report_file"
    
    echo "Accessibility report created: $report_file"
    log_message "Accessibility report created: $report_file"
}

# Main execution
log_message "Starting comprehensive accessibility configuration"

# Validate inputs
for setting in "$REDUCE_MOTION" "$REDUCE_TRANSPARENCY" "$INCREASE_CONTRAST" "$DIFFERENTIATE_WITHOUT_COLOR"; do
    if [[ "$setting" != "true" && "$setting" != "false" ]]; then
        log_message "ERROR: Invalid setting value: $setting (must be true or false)"
        exit 1
    fi
done

# Get current user
loggedInUser=$(ls -l /dev/console | awk '{ print $3 }')

if [ -z "$loggedInUser" ] || [ "$loggedInUser" = "root" ]; then
    log_message "ERROR: No valid user session found"
    exit 1
fi

log_message "Current user: $loggedInUser"

# Show current settings
get_all_accessibility_settings "$loggedInUser"

# Configure all accessibility settings
if configure_all_accessibility "$loggedInUser" "$REDUCE_MOTION" "$REDUCE_TRANSPARENCY" "$INCREASE_CONTRAST" "$DIFFERENTIATE_WITHOUT_COLOR"; then
    log_message "All accessibility settings configured successfully"
    echo "✓ All accessibility settings configured successfully"
    
    # Create report
    create_accessibility_report "$loggedInUser"
    
    # Show new settings
    echo ""
    echo "Updated Settings:"
    get_all_accessibility_settings "$loggedInUser"
    
else
    log_message "Some accessibility settings failed to configure"
    echo "⚠ Some accessibility settings may not have been configured properly"
    exit 1
fi

log_message "Comprehensive accessibility configuration completed"

Enterprise Deployment Scripts

Multi-User Configuration

Script for configuring accessibility settings across multiple users:

#!/bin/bash

# Multi-user accessibility configuration script
LOG_FILE="/var/log/accessibility_deployment.log"
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')

# Configuration
REDUCE_MOTION=${1:-true}
REDUCE_TRANSPARENCY=${2:-true}
TARGET_USERS=${3:-"all"}  # "all" or comma-separated list of usernames

# Function to log messages
log_message() {
    echo "[$TIMESTAMP] $1" | tee -a "$LOG_FILE"
}

# Function to get all regular users
get_all_users() {
    # Get users with UID >= 500 (regular users)
    local users=$(dscl . -list /Users UniqueID | awk '$2 >= 500 && $2 < 65534 { print $1 }')
    echo "$users"
}

# Function to parse target users
parse_target_users() {
    local target=$1
    
    if [ "$target" = "all" ]; then
        get_all_users
    else
        echo "$target" | tr ',' '\n'
    fi
}

# Function to configure user accessibility
configure_user_accessibility() {
    local username=$1
    local motion=$2
    local transparency=$3
    
    log_message "Configuring accessibility for user: $username"
    
    # Check if user exists
    if ! id "$username" &>/dev/null; then
        log_message "WARNING: User $username does not exist"
        return 1
    fi
    
    # Check if user has home directory
    local home_dir=$(eval echo ~$username)
    if [ ! -d "$home_dir" ]; then
        log_message "WARNING: Home directory not found for user: $username"
        return 1
    fi
    
    # Configure settings
    local success=0
    
    if su -l "$username" -c "defaults write com.apple.universalaccess reduceMotion -bool $motion"; then
        log_message "SUCCESS: Reduce motion configured for $username"
    else
        log_message "ERROR: Failed to configure reduce motion for $username"
        success=1
    fi
    
    if su -l "$username" -c "defaults write com.apple.universalaccess reduceTransparency -bool $transparency"; then
        log_message "SUCCESS: Reduce transparency configured for $username"
    else
        log_message "ERROR: Failed to configure reduce transparency for $username"
        success=1
    fi
    
    if [ $success -eq 0 ]; then
        log_message "SUCCESS: All accessibility settings configured for $username"
        return 0
    else
        log_message "ERROR: Some settings failed for $username"
        return 1
    fi
}

# Main execution
log_message "Starting multi-user accessibility deployment"

# Parse target users
target_users=$(parse_target_users "$TARGET_USERS")

if [ -z "$target_users" ]; then
    log_message "ERROR: No target users specified"
    exit 1
fi

log_message "Target users: $target_users"

# Configure each user
successful=0
failed=0

for user in $target_users; do
    echo "Configuring accessibility for user: $user"
    
    if configure_user_accessibility "$user" "$REDUCE_MOTION" "$REDUCE_TRANSPARENCY"; then
        echo "  ✓ Success"
        ((successful++))
    else
        echo "  ✗ Failed"
        ((failed++))
    fi
done

log_message "Multi-user deployment completed"
log_message "Successfully configured: $successful users"
log_message "Failed: $failed users"

echo ""
echo "Deployment Summary:"
echo "  Successfully configured: $successful users"
echo "  Failed: $failed users"
echo "  Log file: $LOG_FILE"

if [ $failed -gt 0 ]; then
    exit 1
fi

Remote Deployment Script

Script for deploying accessibility configurations remotely:

#!/bin/bash

# Remote accessibility deployment script
REMOTE_HOSTS=(
    "10.0.1.10"
    "10.0.1.11"
    "10.0.1.12"
    # Add more hosts as needed
)

SSH_USER="admin"
SSH_KEY_PATH="/path/to/ssh/key"
LOG_FILE="/var/log/remote_accessibility_deployment.log"

# Configuration
REDUCE_MOTION=true
REDUCE_TRANSPARENCY=true

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

# Function to create deployment script
create_deployment_script() {
    local script_path="/tmp/accessibility_deploy.sh"
    
    cat > "$script_path" << 'EOF'
#!/bin/bash

# Remote accessibility configuration script
REDUCE_MOTION="$1"
REDUCE_TRANSPARENCY="$2"

# Get current user
loggedInUser=$(ls -l /dev/console | awk '{ print $3 }')

if [ -z "$loggedInUser" ] || [ "$loggedInUser" = "root" ]; then
    echo "Error: No valid user session found"
    exit 1
fi

echo "Configuring accessibility for user: $loggedInUser"

# Configure reduce motion
if su -l "$loggedInUser" -c "defaults write com.apple.universalaccess reduceMotion -bool $REDUCE_MOTION"; then
    echo "✓ Reduce motion configured"
else
    echo "✗ Failed to configure reduce motion"
    exit 1
fi

# Configure reduce transparency
if su -l "$loggedInUser" -c "defaults write com.apple.universalaccess reduceTransparency -bool $REDUCE_TRANSPARENCY"; then
    echo "✓ Reduce transparency configured"
else
    echo "✗ Failed to configure reduce transparency"
    exit 1
fi

echo "Accessibility configuration completed successfully"
EOF

    chmod +x "$script_path"
    echo "$script_path"
}

# Function to deploy to remote host
deploy_to_host() {
    local host=$1
    local script_path=$2
    
    log_message "Deploying accessibility configuration to host: $host"
    
    # Copy script to remote host
    if scp -i "$SSH_KEY_PATH" -o StrictHostKeyChecking=no "$script_path" "$SSH_USER@$host:/tmp/accessibility_deploy.sh"; then
        log_message "Script copied to $host"
    else
        log_message "ERROR: Failed to copy script to $host"
        return 1
    fi
    
    # Execute script on remote host
    if ssh -i "$SSH_KEY_PATH" -o StrictHostKeyChecking=no "$SSH_USER@$host" "sudo /tmp/accessibility_deploy.sh $REDUCE_MOTION $REDUCE_TRANSPARENCY"; then
        log_message "SUCCESS: Configuration applied on $host"
        return 0
    else
        log_message "ERROR: Failed to apply configuration on $host"
        return 1
    fi
}

# Main execution
log_message "Starting remote accessibility deployment"

# Create deployment script
script_path=$(create_deployment_script)
log_message "Created deployment script: $script_path"

successful=0
failed=0

for host in "${REMOTE_HOSTS[@]}"; do
    echo "Deploying to host: $host"
    
    if deploy_to_host "$host" "$script_path"; then
        echo "  ✓ Success"
        ((successful++))
    else
        echo "  ✗ Failed"
        ((failed++))
    fi
done

# Cleanup
rm -f "$script_path"

log_message "Remote deployment completed"
log_message "Successfully deployed: $successful hosts"
log_message "Failed: $failed hosts"

echo ""
echo "Remote Deployment Summary:"
echo "  Successfully deployed: $successful hosts"
echo "  Failed: $failed hosts"
echo "  Log file: $LOG_FILE"

if [ $failed -gt 0 ]; then
    exit 1
fi

Best Practices and Recommendations

1. Performance Considerations

  • Monitor system performance before and after changes
  • Consider the impact on older hardware
  • Test settings on different Mac models
  • Document performance improvements

2. User Experience

  • Communicate changes to users beforehand
  • Provide training on new interface behavior
  • Offer opt-out options where appropriate
  • Gather user feedback on accessibility improvements

3. Enterprise Management

  • Standardize accessibility policies across devices
  • Use configuration management tools for deployment
  • Implement monitoring for setting compliance
  • Maintain documentation of all customizations

4. Accessibility Compliance

  • Ensure settings meet accessibility requirements
  • Consider various types of disabilities
  • Test with assistive technologies
  • Follow WCAG guidelines where applicable

Troubleshooting Common Issues

Setting Not Applied

#!/bin/bash

# Troubleshoot accessibility settings
username=$(ls -l /dev/console | awk '{ print $3 }')

echo "Troubleshooting accessibility settings for user: $username"

# Check current settings
echo "Current settings:"
defaults read com.apple.universalaccess 2>/dev/null | grep -E "(reduceMotion|reduceTransparency)"

# Force refresh
killall Dock
killall SystemUIServer

echo "Interface refreshed"

Permission Issues

#!/bin/bash

# Fix permission issues
username=$(ls -l /dev/console | awk '{ print $3 }')
plist_path="/Users/$username/Library/Preferences/com.apple.universalaccess.plist"

echo "Fixing permissions for accessibility settings"

# Ensure proper ownership
chown "$username:staff" "$plist_path"

# Set proper permissions
chmod 644 "$plist_path"

echo "Permissions fixed"

Conclusion

Effective management of motion and transparency settings is crucial for creating accessible and performant Mac environments. The scripts and techniques provided in this guide offer comprehensive solutions for various accessibility configuration scenarios.

Key takeaways:

  • Understand the impact of accessibility settings on user experience
  • Use appropriate scripts for different deployment scenarios
  • Implement proper testing and validation procedures
  • Monitor system performance and user feedback
  • Consider accessibility needs across your entire user base

Remember that accessibility settings significantly impact user experience, so always test changes thoroughly and consider providing users with options to customize their experience based on their individual needs.

Proxy Management on macOS

Configure and manage enterprise proxy settings across your MacFleet devices using advanced networksetup commands. This tutorial covers all proxy types including web, secure web, streaming, Gopher, and SOCKS firewall proxies with enterprise-grade management capabilities.

Understanding macOS Proxy Management

macOS provides comprehensive proxy configuration through the networksetup command-line utility, supporting:

  • Web Proxy (HTTP) - Standard HTTP traffic routing
  • Secure Web Proxy (HTTPS) - Encrypted HTTPS traffic with end-to-end security
  • Streaming Proxy - Multimedia content optimization (deprecated in macOS 13.0+)
  • Gopher Proxy - Legacy Gopher protocol support (deprecated in macOS 13.0+)
  • SOCKS Firewall Proxy - Generic protocol supporting most applications

Web Proxy Configuration

Basic Web Proxy Setup

#!/bin/bash

# Configure HTTP web proxy
NETWORK_SERVICE="Wi-Fi"
PROXY_SERVER="proxy.company.com"
PROXY_PORT="8080"
AUTHENTICATED="on"
USERNAME="proxyuser"
PASSWORD="proxypass"

# Set web proxy configuration
networksetup -setwebproxy "$NETWORK_SERVICE" "$PROXY_SERVER" "$PROXY_PORT" "$AUTHENTICATED" "$USERNAME" "$PASSWORD"

# Enable web proxy
networksetup -setwebproxystate "$NETWORK_SERVICE" on

echo "Web proxy configured successfully for $NETWORK_SERVICE"

Advanced Web Proxy Management

#!/bin/bash

# Enterprise Web Proxy Configuration System
NETWORK_SERVICE="Wi-Fi"
CONFIG_FILE="/etc/macfleet/proxy_config.conf"
LOG_FILE="/var/log/macfleet_proxy.log"

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

# Load proxy configuration from file
load_proxy_config() {
    if [[ -f "$CONFIG_FILE" ]]; then
        source "$CONFIG_FILE"
        log_action "Loaded proxy configuration from $CONFIG_FILE"
    else
        echo "Configuration file not found: $CONFIG_FILE"
        exit 1
    fi
}

# Configure web proxy with validation
configure_web_proxy() {
    local server="$1"
    local port="$2"
    local auth="$3"
    local username="$4"
    local password="$5"
    
    # Validate network service exists
    if ! networksetup -listallnetworkservices | grep -q "^$NETWORK_SERVICE$"; then
        log_action "ERROR: Network service '$NETWORK_SERVICE' not found"
        return 1
    fi
    
    # Test proxy connectivity
    if ! nc -z "$server" "$port" 2>/dev/null; then
        log_action "WARNING: Cannot reach proxy server $server:$port"
    fi
    
    # Configure proxy
    if networksetup -setwebproxy "$NETWORK_SERVICE" "$server" "$port" "$auth" "$username" "$password"; then
        networksetup -setwebproxystate "$NETWORK_SERVICE" on
        log_action "Web proxy configured: $server:$port (Auth: $auth)"
        return 0
    else
        log_action "ERROR: Failed to configure web proxy"
        return 1
    fi
}

# Verify proxy configuration
verify_proxy_config() {
    local proxy_info
    proxy_info=$(networksetup -getwebproxy "$NETWORK_SERVICE")
    
    echo "Current Web Proxy Configuration:"
    echo "$proxy_info"
    
    if echo "$proxy_info" | grep -q "Enabled: Yes"; then
        log_action "Web proxy verification successful"
        return 0
    else
        log_action "Web proxy verification failed"
        return 1
    fi
}

# Main execution
main() {
    log_action "Starting web proxy configuration"
    
    # Example configuration (replace with actual values)
    configure_web_proxy "proxy.company.com" "8080" "on" "proxyuser" "proxypass"
    
    # Verify configuration
    verify_proxy_config
    
    log_action "Web proxy configuration completed"
}

# Execute if script is run directly
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi

Secure Web Proxy (HTTPS)

Basic HTTPS Proxy Setup

#!/bin/bash

# Configure HTTPS secure web proxy
networksetup -setsecurewebproxy "Wi-Fi" "secure-proxy.company.com" "8443" on "secureuser" "securepass"
networksetup -setsecurewebproxystate "Wi-Fi" on

echo "Secure web proxy configured successfully"

Enterprise HTTPS Proxy Management

#!/bin/bash

# Enterprise Secure Web Proxy Configuration
configure_secure_proxy() {
    local network_service="$1"
    local proxy_server="$2"
    local proxy_port="$3"
    local username="$4"
    local password="$5"
    
    echo "Configuring secure web proxy for $network_service..."
    
    # Validate SSL/TLS connectivity
    if openssl s_client -connect "$proxy_server:$proxy_port" -verify_return_error < /dev/null 2>/dev/null; then
        echo "✅ SSL connectivity verified for $proxy_server:$proxy_port"
    else
        echo "⚠️  WARNING: SSL connectivity issues detected"
    fi
    
    # Configure secure proxy
    if networksetup -setsecurewebproxy "$network_service" "$proxy_server" "$proxy_port" on "$username" "$password"; then
        networksetup -setsecurewebproxystate "$network_service" on
        echo "✅ Secure web proxy configured successfully"
        
        # Verify configuration
        echo "Configuration details:"
        networksetup -getsecurewebproxy "$network_service"
        
        return 0
    else
        echo "❌ Failed to configure secure web proxy"
        return 1
    fi
}

# Certificate validation for secure proxies
validate_proxy_certificate() {
    local proxy_server="$1"
    local proxy_port="$2"
    
    echo "Validating proxy certificate..."
    
    local cert_info
    cert_info=$(openssl s_client -connect "$proxy_server:$proxy_port" -servername "$proxy_server" < /dev/null 2>/dev/null | openssl x509 -text -noout)
    
    if [[ -n "$cert_info" ]]; then
        echo "Certificate validation successful"
        echo "Certificate subject: $(echo "$cert_info" | grep "Subject:" | head -1)"
        echo "Certificate issuer: $(echo "$cert_info" | grep "Issuer:" | head -1)"
        return 0
    else
        echo "Certificate validation failed"
        return 1
    fi
}

# Usage example
configure_secure_proxy "Wi-Fi" "secure-proxy.company.com" "8443" "secureuser" "securepass"
validate_proxy_certificate "secure-proxy.company.com" "8443"

SOCKS Firewall Proxy

Basic SOCKS Proxy Configuration

#!/bin/bash

# Configure SOCKS firewall proxy
networksetup -setsocksfirewallproxy "Wi-Fi" "socks-proxy.company.com" "1080" on "socksuser" "sockspass"
networksetup -setsocksfirewallproxystate "Wi-Fi" on

echo "SOCKS firewall proxy configured successfully"

Advanced SOCKS Proxy Management

#!/bin/bash

# Enterprise SOCKS Proxy Configuration System
setup_socks_proxy() {
    local network_service="$1"
    local socks_server="$2"
    local socks_port="$3"
    local auth_required="$4"
    local username="$5"
    local password="$6"
    
    echo "Setting up SOCKS proxy: $socks_server:$socks_port"
    
    # Test SOCKS connectivity
    if command -v nc >/dev/null 2>&1; then
        if nc -z "$socks_server" "$socks_port" 2>/dev/null; then
            echo "✅ SOCKS proxy connectivity verified"
        else
            echo "⚠️  WARNING: Cannot reach SOCKS proxy"
        fi
    fi
    
    # Configure SOCKS proxy
    if networksetup -setsocksfirewallproxy "$network_service" "$socks_server" "$socks_port" "$auth_required" "$username" "$password"; then
        networksetup -setsocksfirewallproxystate "$network_service" on
        echo "✅ SOCKS firewall proxy configured"
        
        # Verify configuration
        echo "SOCKS proxy details:"
        networksetup -getsocksfirewallproxy "$network_service"
        
        return 0
    else
        echo "❌ Failed to configure SOCKS proxy"
        return 1
    fi
}

# Test SOCKS proxy functionality
test_socks_proxy() {
    local test_url="http://httpbin.org/ip"
    
    echo "Testing SOCKS proxy functionality..."
    
    # Test with curl through SOCKS proxy
    if command -v curl >/dev/null 2>&1; then
        local proxy_response
        proxy_response=$(curl -s --socks5 "socks-proxy.company.com:1080" "$test_url" 2>/dev/null)
        
        if [[ -n "$proxy_response" ]]; then
            echo "✅ SOCKS proxy test successful"
            echo "Response: $proxy_response"
        else
            echo "❌ SOCKS proxy test failed"
        fi
    else
        echo "curl not available for testing"
    fi
}

# Usage
setup_socks_proxy "Wi-Fi" "socks-proxy.company.com" "1080" "on" "socksuser" "sockspass"
test_socks_proxy

Legacy Proxy Support (macOS < 13.0)

Streaming Proxy Configuration

#!/bin/bash

# Configure streaming proxy (deprecated in macOS 13.0+)
check_macos_version() {
    local version
    version=$(sw_vers -productVersion)
    local major_version
    major_version=$(echo "$version" | cut -d. -f1)
    
    if [[ "$major_version" -ge 13 ]]; then
        echo "⚠️  Streaming proxy not supported on macOS 13.0+"
        return 1
    fi
    return 0
}

configure_streaming_proxy() {
    if check_macos_version; then
        networksetup -setstreamingproxy "Wi-Fi" "stream-proxy.company.com" "8080" on "streamuser" "streampass"
        networksetup -setstreamingproxystate "Wi-Fi" on
        echo "✅ Streaming proxy configured"
    else
        echo "❌ Streaming proxy not available on this macOS version"
    fi
}

configure_gopher_proxy() {
    if check_macos_version; then
        networksetup -setgopherproxy "Wi-Fi" "gopher-proxy.company.com" "70" on "gopheruser" "gopherpass"
        networksetup -setgopherproxystate "Wi-Fi" on
        echo "✅ Gopher proxy configured"
    else
        echo "❌ Gopher proxy not available on this macOS version"
    fi
}

# Execute legacy proxy setup
configure_streaming_proxy
configure_gopher_proxy

Enterprise Proxy Management System

#!/bin/bash

# MacFleet Enterprise Proxy Management System
# Comprehensive proxy configuration and monitoring

# Configuration
PROXY_CONFIG_DIR="/etc/macfleet/proxy"
LOG_FILE="/var/log/macfleet_proxy.log"
BACKUP_DIR="/var/backups/macfleet/proxy"
API_ENDPOINT="https://api.macfleet.com/v1/proxy"

# Create directory structure
setup_directories() {
    mkdir -p "$PROXY_CONFIG_DIR" "$BACKUP_DIR"
    touch "$LOG_FILE"
}

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

# Get all network services
get_network_services() {
    networksetup -listallnetworkservices | grep -v "^An asterisk"
}

# Backup current proxy settings
backup_proxy_settings() {
    local backup_file="$BACKUP_DIR/proxy_backup_$(date +%Y%m%d_%H%M%S).json"
    
    echo "{" > "$backup_file"
    echo "  \"timestamp\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"," >> "$backup_file"
    echo "  \"hostname\": \"$(hostname)\"," >> "$backup_file"
    echo "  \"network_services\": {" >> "$backup_file"
    
    local first=true
    while IFS= read -r service; do
        if [[ "$first" == "false" ]]; then
            echo "," >> "$backup_file"
        fi
        first=false
        
        echo "    \"$service\": {" >> "$backup_file"
        echo "      \"web_proxy\": $(networksetup -getwebproxy "$service" | python3 -c "import sys,json; print(json.dumps(sys.stdin.read()))")" >> "$backup_file"
        echo "      \"secure_web_proxy\": $(networksetup -getsecurewebproxy "$service" | python3 -c "import sys,json; print(json.dumps(sys.stdin.read()))")" >> "$backup_file"
        echo "      \"socks_proxy\": $(networksetup -getsocksfirewallproxy "$service" | python3 -c "import sys,json; print(json.dumps(sys.stdin.read()))")" >> "$backup_file"
        echo "    }" >> "$backup_file"
    done < <(get_network_services)
    
    echo "  }" >> "$backup_file"
    echo "}" >> "$backup_file"
    
    log_action "Proxy settings backed up to: $backup_file"
}

# Configure proxy from JSON configuration
configure_from_json() {
    local config_file="$1"
    
    if [[ ! -f "$config_file" ]]; then
        log_action "ERROR: Configuration file not found: $config_file"
        return 1
    fi
    
    log_action "Applying proxy configuration from: $config_file"
    
    # Parse JSON and apply settings using jq or python
    if command -v jq >/dev/null 2>&1; then
        # Use jq for JSON parsing
        local networks
        networks=$(jq -r '.networks | keys[]' "$config_file")
        
        while IFS= read -r network; do
            local web_proxy
            web_proxy=$(jq -r ".networks[\"$network\"].web_proxy" "$config_file")
            
            if [[ "$web_proxy" != "null" ]]; then
                local server port auth username password
                server=$(echo "$web_proxy" | jq -r '.server')
                port=$(echo "$web_proxy" | jq -r '.port')
                auth=$(echo "$web_proxy" | jq -r '.authentication')
                username=$(echo "$web_proxy" | jq -r '.username')
                password=$(echo "$web_proxy" | jq -r '.password')
                
                networksetup -setwebproxy "$network" "$server" "$port" "$auth" "$username" "$password"
                networksetup -setwebproxystate "$network" on
                
                log_action "Web proxy configured for $network: $server:$port"
            fi
        done <<< "$networks"
    else
        log_action "ERROR: jq not available for JSON parsing"
        return 1
    fi
}

# Monitor proxy connectivity
monitor_proxy_connectivity() {
    log_action "Starting proxy connectivity monitoring"
    
    while IFS= read -r service; do
        local web_proxy_info
        web_proxy_info=$(networksetup -getwebproxy "$service")
        
        if echo "$web_proxy_info" | grep -q "Enabled: Yes"; then
            local server port
            server=$(echo "$web_proxy_info" | grep "Server:" | awk '{print $2}')
            port=$(echo "$web_proxy_info" | grep "Port:" | awk '{print $2}')
            
            if nc -z "$server" "$port" 2>/dev/null; then
                log_action "✅ Proxy connectivity OK: $service ($server:$port)"
            else
                log_action "❌ Proxy connectivity FAILED: $service ($server:$port)"
            fi
        fi
    done < <(get_network_services)
}

# Clear all proxy settings
clear_all_proxies() {
    log_action "Clearing all proxy settings"
    
    while IFS= read -r service; do
        # Disable all proxy types
        networksetup -setwebproxystate "$service" off
        networksetup -setsecurewebproxystate "$service" off
        networksetup -setsocksfirewallproxystate "$service" off
        
        # For older macOS versions
        networksetup -setstreamingproxystate "$service" off 2>/dev/null || true
        networksetup -setgopherproxystate "$service" off 2>/dev/null || true
        
        log_action "Proxies cleared for: $service"
    done < <(get_network_services)
}

# Generate proxy status report
generate_proxy_report() {
    local report_file="$PROXY_CONFIG_DIR/proxy_report_$(date +%Y%m%d_%H%M%S).txt"
    
    {
        echo "MacFleet Proxy Status Report"
        echo "Generated: $(date)"
        echo "Hostname: $(hostname)"
        echo "=================================="
        echo ""
        
        while IFS= read -r service; do
            echo "Network Service: $service"
            echo "--------------------------------"
            
            echo "Web Proxy:"
            networksetup -getwebproxy "$service" | sed 's/^/  /'
            echo ""
            
            echo "Secure Web Proxy:"
            networksetup -getsecurewebproxy "$service" | sed 's/^/  /'
            echo ""
            
            echo "SOCKS Firewall Proxy:"
            networksetup -getsocksfirewallproxy "$service" | sed 's/^/  /'
            echo ""
            
            echo "=================================="
            echo ""
        done < <(get_network_services)
    } > "$report_file"
    
    echo "Proxy report generated: $report_file"
    log_action "Proxy status report generated: $report_file"
}

# Main function
main() {
    local action="${1:-status}"
    
    setup_directories
    log_action "MacFleet Proxy Management started with action: $action"
    
    case "$action" in
        "backup")
            backup_proxy_settings
            ;;
        "configure")
            configure_from_json "$2"
            ;;
        "monitor")
            monitor_proxy_connectivity
            ;;
        "clear")
            backup_proxy_settings
            clear_all_proxies
            ;;
        "report")
            generate_proxy_report
            ;;
        "status"|*)
            generate_proxy_report
            monitor_proxy_connectivity
            ;;
    esac
    
    log_action "MacFleet Proxy Management completed"
}

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

Proxy Configuration Templates

Corporate Web Proxy Template

# /etc/macfleet/proxy/corporate_web.conf
PROXY_TYPE="web"
NETWORK_SERVICE="Wi-Fi"
PROXY_SERVER="proxy.company.com"
PROXY_PORT="8080"
AUTHENTICATION="on"
USERNAME="employee_username"
PASSWORD="employee_password"
AUTO_CONFIG_URL=""
BYPASS_LIST="*.company.com,localhost,127.0.0.1"

Secure Enterprise Template

# /etc/macfleet/proxy/secure_enterprise.conf
PROXY_TYPE="secure_web"
NETWORK_SERVICE="Wi-Fi"
PROXY_SERVER="secure-proxy.company.com"
PROXY_PORT="8443"
AUTHENTICATION="on"
USERNAME="secure_user"
PASSWORD="secure_password"
SSL_VERIFICATION="enabled"
CERTIFICATE_PINNING="enabled"

SOCKS Proxy Template

# /etc/macfleet/proxy/socks_proxy.conf
PROXY_TYPE="socks"
NETWORK_SERVICE="Wi-Fi"
PROXY_SERVER="socks.company.com"
PROXY_PORT="1080"
AUTHENTICATION="on"
USERNAME="socks_user"
PASSWORD="socks_password"
SOCKS_VERSION="5"

Security Considerations

Proxy Authentication Security

#!/bin/bash

# Secure proxy credential management
encrypt_credentials() {
    local username="$1"
    local password="$2"
    local keychain="MacFleet-Proxy"
    
    # Store credentials in keychain
    security add-generic-password -a "$username" -s "proxy-credentials" -w "$password" -T "" "$keychain" 2>/dev/null
    
    if [[ $? -eq 0 ]]; then
        echo "✅ Credentials stored securely in keychain"
    else
        echo "❌ Failed to store credentials in keychain"
    fi
}

# Retrieve credentials from keychain
decrypt_credentials() {
    local username="$1"
    local keychain="MacFleet-Proxy"
    
    local password
    password=$(security find-generic-password -a "$username" -s "proxy-credentials" -w "$keychain" 2>/dev/null)
    
    if [[ -n "$password" ]]; then
        echo "$password"
    else
        echo "ERROR: Could not retrieve password for $username"
        return 1
    fi
}

Important Configuration Notes

Network Service Names

  • Service names are case-sensitive
  • Use quotes for names with spaces: "Wi-Fi"
  • Common services: "Wi-Fi", "Ethernet", "USB 10/100/1000 LAN"

Proxy Authentication

  • Set authenticated to "on" to enable authentication
  • Set authenticated to "off" to disable authentication
  • Credentials will be prompted if authentication is enabled but not provided

macOS Version Compatibility

  • Streaming Proxy: Deprecated in macOS 13.0+
  • Gopher Proxy: Deprecated in macOS 13.0+
  • Web/Secure Web/SOCKS: Available on all supported macOS versions

Error Handling

  • Existing proxy configurations will show errors when reconfigured
  • Use networksetup -setproxystate to disable before reconfiguring
  • Test connectivity before applying to fleet devices

Best Practices

  1. Always backup current settings before changes
  2. Test connectivity after proxy configuration
  3. Use secure storage for proxy credentials
  4. Monitor proxy health continuously
  5. Validate certificates for HTTPS proxies
  6. Document configurations for compliance
  7. Implement logging for audit trails
  8. Test on individual devices before fleet deployment

Remember to validate all scripts on test devices before deploying across your MacFleet environment, and ensure proxy servers are accessible and properly configured for your network infrastructure.

Printer Management on macOS

Manage printer infrastructure across your MacFleet devices using advanced printer deployment, configuration management, and enterprise security controls. This tutorial provides comprehensive tools for implementing organizational printing policies and automated printer management.

Understanding macOS Printer Management

macOS provides several tools for printer management:

  • lpadmin - Command-line printer administration
  • lpstat - Printer status and queue information
  • lpoptions - Printer configuration and options
  • cups - Common Unix Printing System
  • System Preferences - GUI printer management interface

Basic Printer Operations

Deploy Single Printer

#!/bin/bash

# Deploy a network printer
PRINTER_NAME="Office_HP_LaserJet"
PRINTER_DESCRIPTION="HP LaserJet Pro in Main Office"
DEVICE_URI="ipp://192.168.1.100/ipp/print"

lpadmin -p "$PRINTER_NAME" -E -D "$PRINTER_DESCRIPTION" -v "$DEVICE_URI" -m everywhere

echo "Printer $PRINTER_NAME deployed successfully"

Remove Single Printer

#!/bin/bash

# Remove a printer
PRINTER_NAME="Office_HP_LaserJet"

lpadmin -x "$PRINTER_NAME"

echo "Printer $PRINTER_NAME removed successfully"

Check Printer Status

#!/bin/bash

# Check all printer statuses
echo "=== Printer Status ==="
lpstat -p

echo -e "\n=== Print Queues ==="
lpstat -o

Enterprise Printer Management System

#!/bin/bash

# MacFleet Enterprise Printer Management System
# Comprehensive printer deployment, configuration, and security management

# Configuration
MACFLEET_DIR="/etc/macfleet"
PRINTER_DIR="$MACFLEET_DIR/printer_management"
REPORTS_DIR="$MACFLEET_DIR/reports"
COMPLIANCE_DIR="$MACFLEET_DIR/compliance"
AUDIT_DIR="$MACFLEET_DIR/audit"
LOG_FILE="/var/log/macfleet_printer_management.log"
POLICIES_DIR="$MACFLEET_DIR/printer_policies"

# Create directory structure
create_directories() {
    local dirs=("$MACFLEET_DIR" "$PRINTER_DIR" "$REPORTS_DIR" "$COMPLIANCE_DIR" "$AUDIT_DIR" "$POLICIES_DIR")
    for dir in "${dirs[@]}"; do
        [[ ! -d "$dir" ]] && mkdir -p "$dir"
    done
}

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

# Printer Categories for Enterprise Management
declare -A PRINTER_CATEGORIES=(
    ["executive_printers"]="color_laser,high_capacity,secure_printing,duplex"
    ["departmental_printers"]="color_laser,medium_capacity,duplex,scan_to_email"
    ["workgroup_printers"]="monochrome_laser,standard_capacity,duplex"
    ["specialty_printers"]="wide_format,photo_printer,label_printer"
    ["mobile_printers"]="portable,bluetooth,battery_powered"
    ["secure_printers"]="badge_release,encrypted_queue,audit_trail"
)

# Printer Security Policies
declare -A SECURITY_POLICIES=(
    ["high_security"]="authentication_required,encryption_enabled,audit_logging,secure_queue"
    ["standard_security"]="authentication_optional,basic_logging,standard_queue"
    ["open_access"]="no_authentication,minimal_logging,open_queue"
    ["finance_department"]="authentication_required,encryption_enabled,watermark,audit_trail"
    ["hr_department"]="authentication_required,confidential_printing,audit_trail"
)

# Printer Deployment Profiles
declare -A DEPLOYMENT_PROFILES=(
    ["office_standard"]="HP_LaserJet_Pro,Canon_ImageRunner,Epson_WorkForce"
    ["creative_department"]="Canon_ColorMax,Epson_SureColor,HP_DesignJet"
    ["accounting_secure"]="HP_SecurePrint,Canon_SecureMode,Lexmark_Confidential"
    ["mobile_workforce"]="HP_OfficeJet_Mobile,Canon_SELPHY,Brother_PocketJet"
    ["warehouse_industrial"]="Zebra_Industrial,Honeywell_PC43t,TSC_Industrial"
)

# Deploy printer with advanced configuration
deploy_printer() {
    local printer_name="$1"
    local printer_ip="$2"
    local printer_type="$3"
    local security_policy="$4"
    local department="$5"
    
    log_action "Deploying printer: $printer_name (Type: $printer_type, Policy: $security_policy)"
    
    # Generate printer configuration
    local device_uri=""
    local printer_driver=""
    local additional_options=""
    
    case "$printer_type" in
        "network_ipp")
            device_uri="ipp://$printer_ip/ipp/print"
            printer_driver="everywhere"
            ;;
        "network_lpd")
            device_uri="lpd://$printer_ip/queue"
            printer_driver="everywhere"
            ;;
        "usb")
            device_uri="usb://Unknown/Unknown"
            printer_driver="everywhere"
            ;;
        "bluetooth")
            device_uri="bluetooth://$printer_ip"
            printer_driver="everywhere"
            ;;
    esac
    
    # Apply security policy settings
    case "$security_policy" in
        "high_security")
            additional_options="-o job-hold-until=indefinite -o job-sheets=confidential,confidential"
            ;;
        "finance_department")
            additional_options="-o job-sheets=standard,standard -o page-label='CONFIDENTIAL - FINANCE'"
            ;;
        "hr_department")
            additional_options="-o job-hold-until=indefinite -o page-label='HR CONFIDENTIAL'"
            ;;
    esac
    
    # Deploy the printer
    if lpadmin -p "$printer_name" -E -D "MacFleet $printer_type - $department" -v "$device_uri" -m "$printer_driver" $additional_options; then
        log_action "Successfully deployed printer: $printer_name"
        
        # Set additional CUPS options
        lpadmin -p "$printer_name" -o media=letter -o sides=two-sided-long-edge
        
        # Save printer metadata
        cat > "$PRINTER_DIR/${printer_name}_metadata.json" << EOF
{
  "printer_name": "$printer_name",
  "printer_ip": "$printer_ip",
  "printer_type": "$printer_type",
  "security_policy": "$security_policy",
  "department": "$department",
  "deployed_timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
  "deployed_by": "$(whoami)",
  "device_uri": "$device_uri"
}
EOF
        
        return 0
    else
        log_action "ERROR: Failed to deploy printer: $printer_name"
        return 1
    fi
}

# Bulk printer deployment
bulk_deploy_printers() {
    local printer_list_file="$1"
    local deployment_profile="$2"
    
    if [[ ! -f "$printer_list_file" ]]; then
        log_action "ERROR: Printer list file not found: $printer_list_file"
        return 1
    fi
    
    log_action "Starting bulk printer deployment with profile: $deployment_profile"
    
    local deployed_count=0
    local failed_count=0
    
    while IFS=',' read -r printer_name printer_ip printer_type security_policy department; do
        [[ "$printer_name" =~ ^#.*$ ]] && continue
        [[ -z "$printer_name" ]] && continue
        
        if deploy_printer "$printer_name" "$printer_ip" "$printer_type" "$security_policy" "$department"; then
            ((deployed_count++))
        else
            ((failed_count++))
        fi
        
        # Add small delay to prevent overwhelming the system
        sleep 2
    done < "$printer_list_file"
    
    log_action "Bulk deployment completed: $deployed_count successful, $failed_count failed"
}

# Advanced printer configuration
configure_printer_advanced() {
    local printer_name="$1"
    local config_type="$2"
    
    log_action "Applying advanced configuration to $printer_name: $config_type"
    
    case "$config_type" in
        "duplex_default")
            lpadmin -p "$printer_name" -o sides=two-sided-long-edge
            lpadmin -p "$printer_name" -o ColorModel=Gray
            ;;
        "high_quality")
            lpadmin -p "$printer_name" -o print-quality=5
            lpadmin -p "$printer_name" -o resolution=600dpi
            ;;
        "eco_mode")
            lpadmin -p "$printer_name" -o print-quality=3
            lpadmin -p "$printer_name" -o ColorModel=Gray
            lpadmin -p "$printer_name" -o sides=two-sided-long-edge
            ;;
        "secure_printing")
            lpadmin -p "$printer_name" -o job-hold-until=indefinite
            lpadmin -p "$printer_name" -o job-sheets=confidential,confidential
            ;;
    esac
    
    log_action "Advanced configuration applied to $printer_name"
}

# Printer health monitoring
monitor_printer_health() {
    local monitoring_level="$1"
    local health_report="$REPORTS_DIR/printer_health_$(date +%Y%m%d_%H%M%S).json"
    
    log_action "Starting printer health monitoring: $monitoring_level"
    
    local printers=$(lpstat -p | grep "printer" | awk '{print $2}')
    local printer_data=""
    local total_printers=0
    local online_printers=0
    local offline_printers=0
    
    while IFS= read -r printer; do
        [[ -z "$printer" ]] && continue
        ((total_printers++))
        
        local status=$(lpstat -p "$printer" | grep "printer" | awk '{print $4}')
        local queue_jobs=$(lpstat -o "$printer" 2>/dev/null | wc -l)
        
        if [[ "$status" == "idle" || "$status" == "printing" ]]; then
            ((online_printers++))
            local printer_status="online"
        else
            ((offline_printers++))
            local printer_status="offline"
        fi
        
        # Get printer metadata if available
        local metadata_file="$PRINTER_DIR/${printer}_metadata.json"
        local printer_type="unknown"
        local department="unknown"
        
        if [[ -f "$metadata_file" ]]; then
            printer_type=$(grep -o '"printer_type":"[^"]*' "$metadata_file" | cut -d'"' -f4)
            department=$(grep -o '"department":"[^"]*' "$metadata_file" | cut -d'"' -f4)
        fi
        
        printer_data="$printer_data{\"name\":\"$printer\",\"status\":\"$printer_status\",\"queue_jobs\":$queue_jobs,\"type\":\"$printer_type\",\"department\":\"$department\"},"
        
    done <<< "$printers"
    
    # Remove trailing comma
    printer_data="${printer_data%,}"
    
    cat > "$health_report" << EOF
{
  "health_monitoring": {
    "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
    "monitoring_level": "$monitoring_level",
    "total_printers": $total_printers,
    "online_printers": $online_printers,
    "offline_printers": $offline_printers,
    "system_status": "$(cupsd -t 2>&1 | grep -q "no errors" && echo "healthy" || echo "issues_detected")"
  },
  "printer_details": [$printer_data],
  "recommendations": [
    $([ $offline_printers -gt 0 ] && echo "\"Check offline printers for connectivity issues\",")
    $([ $total_printers -gt 20 ] && echo "\"Consider printer consolidation for better management\",")
    "\"Regular maintenance recommended for optimal performance\""
  ]
}
EOF
    
    if [[ $offline_printers -gt 0 ]]; then
        log_action "WARNING: $offline_printers printers are offline"
    fi
    
    log_action "Printer health monitoring completed. Report: $health_report"
    echo "$health_report"
}

# Print queue management
manage_print_queues() {
    local action="$1"
    local printer_name="$2"
    local job_id="$3"
    
    log_action "Print queue management: $action for $printer_name"
    
    case "$action" in
        "pause_all")
            cupsdisable "$printer_name"
            log_action "Paused all printing for: $printer_name"
            ;;
        "resume_all")
            cupsenable "$printer_name"
            log_action "Resumed printing for: $printer_name"
            ;;
        "clear_queue")
            cancel -a "$printer_name"
            log_action "Cleared print queue for: $printer_name"
            ;;
        "cancel_job")
            if [[ -n "$job_id" ]]; then
                cancel "$job_id"
                log_action "Cancelled print job: $job_id"
            fi
            ;;
        "hold_job")
            if [[ -n "$job_id" ]]; then
                lp -i "$job_id" -H hold
                log_action "Put print job on hold: $job_id"
            fi
            ;;
        "release_job")
            if [[ -n "$job_id" ]]; then
                lp -i "$job_id" -H resume
                log_action "Released print job: $job_id"
            fi
            ;;
    esac
    
    # Record action in audit log
    echo "$(date -u +%Y-%m-%dT%H:%M:%SZ):$action:$printer_name:$job_id:$(whoami)" >> "$AUDIT_DIR/print_queue_actions.log"
}

# Printer security enforcement
enforce_printer_security() {
    local security_level="$1"
    
    log_action "Enforcing printer security level: $security_level"
    
    case "$security_level" in
        "maximum")
            # Enable authentication for all printers
            for printer in $(lpstat -p | grep "printer" | awk '{print $2}'); do
                lpadmin -p "$printer" -o job-hold-until=indefinite
                lpadmin -p "$printer" -o job-sheets=confidential,confidential
                log_action "Applied maximum security to: $printer"
            done
            ;;
        "departmental")
            # Apply department-specific security
            for printer in $(lpstat -p | grep "printer" | awk '{print $2}'); do
                if [[ "$printer" =~ [Ff]inance ]]; then
                    lpadmin -p "$printer" -o page-label="CONFIDENTIAL - FINANCE"
                elif [[ "$printer" =~ [Hh][Rr] ]]; then
                    lpadmin -p "$printer" -o job-hold-until=indefinite
                fi
            done
            ;;
        "standard")
            # Apply standard security measures
            for printer in $(lpstat -p | grep "printer" | awk '{print $2}'); do
                lpadmin -p "$printer" -o job-sheets=none,none
                log_action "Applied standard security to: $printer"
            done
            ;;
    esac
    
    log_action "Printer security enforcement completed: $security_level"
}

# Printer usage analytics
generate_usage_analytics() {
    local analysis_period="$1"
    local analytics_file="$REPORTS_DIR/printer_analytics_$(date +%Y%m%d_%H%M%S).json"
    
    log_action "Generating printer usage analytics for period: $analysis_period"
    
    # Get print job history (last 30 days by default)
    local job_history=$(grep "$(date -v-30d '+%Y-%m-%d')" /var/log/cups/page_log 2>/dev/null || echo "")
    
    # Analyze usage patterns
    local total_jobs=0
    local total_pages=0
    local color_pages=0
    local duplex_jobs=0
    
    if [[ -n "$job_history" ]]; then
        total_jobs=$(echo "$job_history" | wc -l)
        total_pages=$(echo "$job_history" | awk '{sum += $7} END {print sum+0}')
        color_pages=$(echo "$job_history" | grep -i "color" | awk '{sum += $7} END {print sum+0}')
        duplex_jobs=$(echo "$job_history" | grep -i "duplex\|two-sided" | wc -l)
    fi
    
    # Calculate cost estimates (example rates)
    local mono_cost_per_page=0.02
    local color_cost_per_page=0.15
    local estimated_cost=$(echo "scale=2; ($total_pages - $color_pages) * $mono_cost_per_page + $color_pages * $color_cost_per_page" | bc -l 2>/dev/null || echo "0.00")
    
    cat > "$analytics_file" << EOF
{
  "usage_analytics": {
    "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
    "analysis_period": "$analysis_period",
    "total_print_jobs": $total_jobs,
    "total_pages_printed": $total_pages,
    "color_pages": $color_pages,
    "monochrome_pages": $((total_pages - color_pages)),
    "duplex_jobs": $duplex_jobs,
    "estimated_cost_usd": $estimated_cost
  },
  "efficiency_metrics": {
    "duplex_usage_percentage": $(echo "scale=2; $duplex_jobs * 100 / $total_jobs" | bc -l 2>/dev/null || echo "0"),
    "color_usage_percentage": $(echo "scale=2; $color_pages * 100 / $total_pages" | bc -l 2>/dev/null || echo "0"),
    "average_pages_per_job": $(echo "scale=2; $total_pages / $total_jobs" | bc -l 2>/dev/null || echo "0")
  },
  "cost_optimization": {
    "potential_duplex_savings": "$(echo "scale=2; ($total_jobs - $duplex_jobs) * $mono_cost_per_page * 0.5" | bc -l 2>/dev/null || echo "0.00")",
    "color_to_mono_savings": "$(echo "scale=2; $color_pages * ($color_cost_per_page - $mono_cost_per_page)" | bc -l 2>/dev/null || echo "0.00")"
  }
}
EOF
    
    log_action "Usage analytics generated: $analytics_file"
    echo "$analytics_file"
}

# Generate comprehensive compliance report
generate_compliance_report() {
    local policy="$1"
    local report_file="$REPORTS_DIR/printer_compliance_$(date +%Y%m%d_%H%M%S).json"
    
    local total_printers=$(lpstat -p | grep "printer" | wc -l)
    local secure_printers=0
    
    # Count printers with security configurations
    for printer in $(lpstat -p | grep "printer" | awk '{print $2}'); do
        if lpoptions -p "$printer" | grep -q "job-hold-until\|job-sheets"; then
            ((secure_printers++))
        fi
    done
    
    cat > "$report_file" << EOF
{
  "compliance_report": {
    "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
    "policy_applied": "$policy",
    "total_printers": $total_printers,
    "secure_printers": $secure_printers,
    "security_coverage": $(echo "scale=2; $secure_printers * 100 / $total_printers" | bc -l 2>/dev/null || echo "0")
  },
  "security_compliance": {
    "encryption_enabled": $(systemctl is-active cups-ssl 2>/dev/null | grep -q "active" && echo "true" || echo "false"),
    "audit_logging": $([ -f "/var/log/cups/access_log" ] && echo "true" || echo "false"),
    "authentication_configured": $(grep -q "AuthType" /etc/cups/cupsd.conf && echo "true" || echo "false")
  },
  "compliance_frameworks": ["SOX", "HIPAA", "NIST", "ISO27001"],
  "recommendations": [
    $([ $secure_printers -lt $total_printers ] && echo "\"Enable security features on all printers\",")
    "\"Regular security audits recommended\",\"Implement print release systems for sensitive documents\""
  ]
}
EOF
    
    log_action "Compliance report generated: $report_file"
    echo "Report saved to: $report_file"
}

# Automated printer maintenance
perform_printer_maintenance() {
    local maintenance_type="$1"
    
    log_action "Starting automated printer maintenance: $maintenance_type"
    
    case "$maintenance_type" in
        "cleanup")
            # Clean up old print jobs and logs
            find /var/spool/cups -name "c*" -mtime +7 -delete 2>/dev/null
            find /var/spool/cups -name "d*" -mtime +7 -delete 2>/dev/null
            log_action "Cleaned up old print jobs and spool files"
            ;;
        "queue_optimization")
            # Restart CUPS to clear any stuck queues
            launchctl kickstart -k system/org.cups.cupsd
            log_action "Restarted CUPS service for queue optimization"
            ;;
        "driver_update")
            # Check for printer driver updates (placeholder)
            log_action "Driver update check initiated (manual verification required)"
            ;;
        "full_maintenance")
            perform_printer_maintenance "cleanup"
            perform_printer_maintenance "queue_optimization"
            log_action "Full maintenance routine completed"
            ;;
    esac
}

# Health check and system validation
perform_health_check() {
    echo "=== MacFleet Printer Management Health Check ==="
    
    # Check CUPS service
    if launchctl list | grep -q "org.cups.cupsd"; then
        echo "✓ CUPS service: Running"
    else
        echo "✗ CUPS service: Not running"
    fi
    
    # Check printer count
    local printer_count=$(lpstat -p | grep "printer" | wc -l)
    echo "✓ Installed printers: $printer_count"
    
    # Check for offline printers
    local offline_printers=$(lpstat -p | grep -c "disabled\|stopped" || echo "0")
    if [[ $offline_printers -gt 0 ]]; then
        echo "⚠️  Offline printers: $offline_printers"
    else
        echo "✓ All printers online"
    fi
    
    # Check print queues
    local queued_jobs=$(lpstat -o | wc -l)
    echo "✓ Queued print jobs: $queued_jobs"
    
    # Check security configuration
    if grep -q "AuthType" /etc/cups/cupsd.conf; then
        echo "✓ Authentication: Configured"
    else
        echo "○ Authentication: Not configured"
    fi
    
    # Check audit logging
    if [[ -f "/var/log/cups/access_log" ]]; then
        echo "✓ Audit logging: Enabled"
    else
        echo "○ Audit logging: Disabled"
    fi
}

# Fleet deployment function
deploy_to_fleet() {
    local deployment_profile="$1"
    local fleet_file="$2"
    
    if [[ ! -f "$fleet_file" ]]; then
        log_action "ERROR: Fleet file not found: $fleet_file"
        return 1
    fi
    
    log_action "Starting fleet deployment of printer profile: $deployment_profile"
    
    while IFS= read -r host; do
        [[ -z "$host" || "$host" =~ ^#.*$ ]] && continue
        
        echo "Deploying to: $host"
        
        # Copy printer configuration to remote host
        ssh "$host" "bash -s" << EOF
#!/bin/bash
# Remote deployment of printer management: $deployment_profile

# Create directories
mkdir -p /etc/macfleet/{printer_management,reports,compliance,audit,printer_policies}

# Deploy common printers based on profile
case "$deployment_profile" in
    "office_standard")
        # Deploy standard office printers
        echo "Deploying standard office printer configuration"
        ;;
    "secure_environment")
        # Deploy high-security printer configuration
        echo "Deploying secure printer configuration"
        ;;
esac
EOF
        
        if [[ $? -eq 0 ]]; then
            log_action "Successfully deployed to: $host"
        else
            log_action "Failed to deploy to: $host"
        fi
        
    done < "$fleet_file"
    
    log_action "Fleet deployment completed"
}

# Main execution function
main() {
    create_directories
    
    case "${1:-}" in
        "deploy_printer")
            deploy_printer "$2" "$3" "$4" "${5:-standard_security}" "${6:-general}"
            ;;
        "bulk_deploy")
            bulk_deploy_printers "$2" "${3:-office_standard}"
            ;;
        "configure_advanced")
            configure_printer_advanced "$2" "${3:-duplex_default}"
            ;;
        "monitor_health")
            monitor_printer_health "${2:-standard}"
            ;;
        "manage_queues")
            manage_print_queues "$2" "$3" "$4"
            ;;
        "enforce_security")
            enforce_printer_security "${2:-standard}"
            ;;
        "usage_analytics")
            generate_usage_analytics "${2:-30days}"
            ;;
        "maintenance")
            perform_printer_maintenance "${2:-cleanup}"
            ;;
        "health_check")
            perform_health_check
            ;;
        "report")
            generate_compliance_report "${2:-manual}"
            ;;
        "deploy_fleet")
            deploy_to_fleet "$2" "$3"
            ;;
        "help"|*)
            echo "MacFleet Enterprise Printer Management System"
            echo ""
            echo "Usage: $0 <command> [options]"
            echo ""
            echo "Commands:"
            echo "  deploy_printer <name> <ip> <type> [security] [dept] - Deploy single printer"
            echo "  bulk_deploy <file> [profile]           - Deploy multiple printers from file"
            echo "  configure_advanced <printer> [config]  - Apply advanced configuration (duplex_default|high_quality|eco_mode|secure_printing)"
            echo "  monitor_health [level]                 - Monitor printer health (basic|standard|detailed)"
            echo "  manage_queues <action> <printer> [job] - Manage print queues (pause_all|resume_all|clear_queue|cancel_job|hold_job|release_job)"
            echo "  enforce_security [level]               - Enforce security policies (maximum|departmental|standard)"
            echo "  usage_analytics [period]               - Generate usage analytics (7days|30days|90days)"
            echo "  maintenance [type]                     - Perform maintenance (cleanup|queue_optimization|driver_update|full_maintenance)"
            echo "  health_check                           - Perform system health check"
            echo "  report [policy]                        - Generate compliance report"
            echo "  deploy_fleet <profile> <fleet_file>    - Deploy to fleet"
            echo ""
            echo "Examples:"
            echo "  $0 deploy_printer Office_HP 192.168.1.100 network_ipp high_security finance"
            echo "  $0 bulk_deploy printers.csv office_standard"
            echo "  $0 configure_advanced Office_HP secure_printing"
            echo "  $0 manage_queues pause_all Office_HP"
            echo "  $0 health_check"
            ;;
    esac
}

# Execute main function
main "$@"

Printer Types and Configurations

The enterprise system supports various printer types:

Printer TypeConnectionUse CaseSecurity Level
Network IPPipp://ip/ipp/printStandard office printingMedium
Network LPDlpd://ip/queueLegacy network printersMedium
USB Directusb://devicePersonal/desk printersLow
Bluetoothbluetooth://addressMobile printingMedium
Secure IPPipps://ip/ipp/printEncrypted printingHigh

Enterprise Deployment Examples

Deploy Standard Office Printer

# Deploy network printer with standard security
./printer_manager.sh deploy_printer "Office_HP_LaserJet" "192.168.1.100" "network_ipp" "standard_security" "general_office"

# Deploy high-security printer for finance department
./printer_manager.sh deploy_printer "Finance_Secure" "192.168.1.200" "network_ipp" "finance_department" "finance"

Bulk Printer Deployment

Create a CSV file printers.csv:

# printer_name,printer_ip,printer_type,security_policy,department
Office_HP_Main,192.168.1.100,network_ipp,standard_security,general
Finance_Secure,192.168.1.200,network_ipp,finance_department,finance
HR_Confidential,192.168.1.300,network_ipp,hr_department,hr
# Deploy all printers from file
./printer_manager.sh bulk_deploy printers.csv office_standard

Advanced Printer Configuration

# Configure duplex printing as default
./printer_manager.sh configure_advanced Office_HP duplex_default

# Enable secure printing with authentication
./printer_manager.sh configure_advanced Finance_Secure secure_printing

# Apply eco-friendly settings
./printer_manager.sh configure_advanced Office_HP eco_mode

Security and Compliance Features

Printer Security Enforcement

# Apply maximum security to all printers
./printer_manager.sh enforce_security maximum

# Apply department-specific security policies
./printer_manager.sh enforce_security departmental

Print Queue Management

# Pause all printing on a printer
./printer_manager.sh manage_queues pause_all Office_HP

# Clear all pending jobs
./printer_manager.sh manage_queues clear_queue Office_HP

# Hold specific job for approval
./printer_manager.sh manage_queues hold_job Office_HP 12345

Usage Analytics and Cost Control

# Generate 30-day usage analytics
./printer_manager.sh usage_analytics 30days

# Generate quarterly cost analysis
./printer_manager.sh usage_analytics 90days

Enterprise Features

Automated Maintenance

The system provides automated maintenance capabilities:

  • Print queue cleanup and optimization
  • Driver update checking
  • Performance monitoring
  • Preventive maintenance scheduling

Security Controls

Advanced security features include:

  • Authentication requirements
  • Encrypted print queues
  • Audit trail logging
  • Confidential document handling
  • Department-based access controls

Cost Management

Monitor and optimize printing costs:

  • Track paper and toner usage
  • Analyze color vs. monochrome ratios
  • Monitor duplex printing adoption
  • Generate cost-saving recommendations

Important Management Considerations

  • Print server security should include encrypted connections (IPPS)
  • User authentication may require Active Directory integration
  • Audit logging must comply with organizational retention policies
  • Driver management requires regular updates for security and compatibility
  • Queue monitoring helps prevent bottlenecks and resource waste

Compliance and Reporting

The enterprise system provides comprehensive audit trails for:

  • SOX Compliance - Financial document printing controls
  • HIPAA Requirements - Healthcare information printing security
  • ISO 27001 - Information security printing management
  • NIST Framework - Cybersecurity printing standards

Testing and Validation

Before enterprise deployment:

  1. Test printer connectivity and configuration accuracy
  2. Verify security policies are properly applied
  3. Confirm user authentication works correctly
  4. Test emergency procedures and queue recovery
  5. Validate compliance reporting completeness

This comprehensive system transforms basic printer management into an enterprise-grade printing infrastructure with advanced security, cost control, and fleet management capabilities.

Set Up Policy Banners on macOS Devices

This comprehensive guide demonstrates how to create, manage, and deploy interactive policy banners on macOS devices for organizational compliance and policy communication.

Overview

Policy banners are interactive messages that appear at the login screen, requiring users to acknowledge organizational policies, agreements, or guidelines before accessing the device. They serve as an essential compliance tool for:

  • Legal compliance: Displaying terms of use and acceptable use policies
  • Security awareness: Communicating security policies and best practices
  • Regulatory requirements: Meeting industry-specific compliance standards
  • Corporate governance: Ensuring users acknowledge company policies
  • Asset protection: Establishing legal framework for device usage

Basic Policy Banner Implementation

Simple Policy Banner Script

Create a basic policy banner with custom messaging:

#!/bin/bash

# Basic policy banner setup script
# Usage: ./create_policy_banner.sh "Your policy message"

create_policy_banner() {
    local message="$1"
    
    # Default message if none provided
    if [ -z "$message" ]; then
        message="This computer system is for authorized use only. By accessing this system, you agree to comply with all applicable policies and regulations."
    fi
    
    # Create the policy banner file
    sudo tee /Library/Security/PolicyBanner.txt <<EOF > /dev/null
$message
EOF
    
    # Set appropriate permissions
    sudo chmod 644 /Library/Security/PolicyBanner.txt
    sudo chown root:wheel /Library/Security/PolicyBanner.txt
    
    echo "Policy banner created successfully."
    echo "Message: $message"
}

# Main execution
if [ $# -eq 0 ]; then
    echo "Usage: $0 \"Your policy message\""
    echo "Example: $0 \"This system is monitored for security purposes.\""
    create_policy_banner
else
    create_policy_banner "$1"
fi

Enhanced Policy Banner with Validation

#!/bin/bash

# Enhanced policy banner setup with validation and logging
# Usage: ./enhanced_policy_banner.sh

setup_policy_banner() {
    local banner_file="/Library/Security/PolicyBanner.txt"
    local log_file="/var/log/macfleet_policy_banner.log"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    
    # Check if running as root
    if [ "$EUID" -ne 0 ]; then
        echo "Error: This script must be run as root"
        exit 1
    fi
    
    # Create log directory if it doesn't exist
    mkdir -p /var/log
    
    # Log the operation
    echo "[$timestamp] Starting policy banner setup on $(hostname)" >> "$log_file"
    
    # Create policy banner content
    cat > "$banner_file" << 'EOF'
AUTHORIZED USE ONLY

This computer system is the property of MacFleet Organization and is intended for authorized business use only. By continuing, you acknowledge that:

• You have read and agree to comply with all applicable policies
• Your activities may be monitored and recorded for security purposes
• Unauthorized access or use is prohibited and may result in criminal prosecution
• You understand that personal use may be restricted or prohibited

Click "Accept" to acknowledge these terms and continue.
EOF
    
    # Set proper permissions
    chmod 644 "$banner_file"
    chown root:wheel "$banner_file"
    
    # Validate the banner file
    if [ -f "$banner_file" ]; then
        echo "[$timestamp] Policy banner created successfully at $banner_file" >> "$log_file"
        echo "Policy banner setup completed successfully."
        
        # Display current content
        echo "Current policy banner content:"
        echo "================================"
        cat "$banner_file"
        echo "================================"
    else
        echo "[$timestamp] ERROR: Failed to create policy banner file" >> "$log_file"
        echo "Error: Failed to create policy banner file"
        exit 1
    fi
    
    # Update preboot volume for FileVault compatibility
    echo "[$timestamp] Updating preboot volume for FileVault compatibility" >> "$log_file"
    if diskutil apfs updatePreboot / 2>/dev/null; then
        echo "[$timestamp] Preboot volume updated successfully" >> "$log_file"
        echo "Preboot volume updated for FileVault compatibility."
    else
        echo "[$timestamp] Warning: Failed to update preboot volume" >> "$log_file"
        echo "Warning: Could not update preboot volume. Banner may not appear on FileVault-enabled devices."
    fi
}

# Execute setup
setup_policy_banner

Advanced Policy Banner Management

Multi-Language Policy Banner

#!/bin/bash

# Multi-language policy banner setup
# Usage: ./multilang_policy_banner.sh [language_code]

setup_multilang_banner() {
    local language=${1:-"en"}
    local banner_file="/Library/Security/PolicyBanner.txt"
    
    # Check if running as root
    if [ "$EUID" -ne 0 ]; then
        echo "Error: This script must be run as root"
        exit 1
    fi
    
    case $language in
        "en")
            create_english_banner
            ;;
        "fr")
            create_french_banner
            ;;
        "es")
            create_spanish_banner
            ;;
        "de")
            create_german_banner
            ;;
        *)
            echo "Unsupported language: $language"
            echo "Supported languages: en, fr, es, de"
            exit 1
            ;;
    esac
    
    # Set proper permissions
    chmod 644 "$banner_file"
    chown root:wheel "$banner_file"
    
    # Update preboot volume
    diskutil apfs updatePreboot / 2>/dev/null
    
    echo "Multi-language policy banner ($language) created successfully."
}

create_english_banner() {
    cat > "/Library/Security/PolicyBanner.txt" << 'EOF'
AUTHORIZED ACCESS ONLY

This computer system is owned by MacFleet Organization and is provided for authorized business use only.

By proceeding, you acknowledge that:
• You are an authorized user with legitimate business purpose
• All activities are subject to monitoring and logging
• Unauthorized access, use, or disclosure is prohibited
• Violations may result in disciplinary action and legal prosecution
• Personal use may be restricted per company policy

Your continued use constitutes acceptance of these terms.

Click "Accept" to proceed.
EOF
}

create_french_banner() {
    cat > "/Library/Security/PolicyBanner.txt" << 'EOF'
ACCÈS AUTORISÉ SEULEMENT

Ce système informatique appartient à l'organisation MacFleet et est fourni uniquement pour un usage professionnel autorisé.

En continuant, vous reconnaissez que :
• Vous êtes un utilisateur autorisé avec un objectif commercial légitime
• Toutes les activités sont sujettes à surveillance et enregistrement
• L'accès, l'utilisation ou la divulgation non autorisés sont interdits
• Les violations peuvent entraîner des mesures disciplinaires et des poursuites légales
• L'usage personnel peut être restreint selon la politique de l'entreprise

Votre utilisation continue constitue l'acceptation de ces termes.

Cliquez sur "Accepter" pour continuer.
EOF
}

create_spanish_banner() {
    cat > "/Library/Security/PolicyBanner.txt" << 'EOF'
SOLO ACCESO AUTORIZADO

Este sistema informático es propiedad de la Organización MacFleet y se proporciona únicamente para uso comercial autorizado.

Al continuar, usted reconoce que:
• Es un usuario autorizado con un propósito comercial legítimo
• Todas las actividades están sujetas a monitoreo y registro
• El acceso, uso o divulgación no autorizados están prohibidos
• Las violaciones pueden resultar en acción disciplinaria y enjuiciamiento legal
• El uso personal puede estar restringido según la política de la empresa

Su uso continuado constituye la aceptación de estos términos.

Haga clic en "Aceptar" para continuar.
EOF
}

create_german_banner() {
    cat > "/Library/Security/PolicyBanner.txt" << 'EOF'
NUR AUTORISIERTER ZUGANG

Dieses Computersystem gehört der MacFleet Organisation und wird nur für autorisierten geschäftlichen Gebrauch bereitgestellt.

Durch Fortfahren erkennen Sie an, dass:
• Sie ein autorisierter Benutzer mit legitimen geschäftlichen Zweck sind
• Alle Aktivitäten der Überwachung und Protokollierung unterliegen
• Unbefugter Zugang, Gebrauch oder Offenlegung verboten ist
• Verstöße zu Disziplinarmaßnahmen und rechtlicher Verfolgung führen können
• Persönlicher Gebrauch gemäß Firmenrichtlinie beschränkt sein kann

Ihre fortgesetzte Nutzung stellt die Annahme dieser Bedingungen dar.

Klicken Sie "Akzeptieren" um fortzufahren.
EOF
}

# Main execution
setup_multilang_banner "$1"

Dynamic Policy Banner Generator

#!/bin/bash

# Dynamic policy banner generator with template support
# Usage: ./dynamic_banner.sh [template_name]

generate_dynamic_banner() {
    local template=${1:-"corporate"}
    local banner_file="/Library/Security/PolicyBanner.txt"
    local config_file="/etc/macfleet/banner_config.conf"
    
    # Check if running as root
    if [ "$EUID" -ne 0 ]; then
        echo "Error: This script must be run as root"
        exit 1
    fi
    
    # Create configuration directory
    mkdir -p /etc/macfleet
    
    # Load or create configuration
    if [ -f "$config_file" ]; then
        source "$config_file"
    else
        create_default_config
        source "$config_file"
    fi
    
    # Generate banner based on template
    case $template in
        "corporate")
            generate_corporate_banner
            ;;
        "government")
            generate_government_banner
            ;;
        "healthcare")
            generate_healthcare_banner
            ;;
        "education")
            generate_education_banner
            ;;
        "financial")
            generate_financial_banner
            ;;
        *)
            echo "Unknown template: $template"
            echo "Available templates: corporate, government, healthcare, education, financial"
            exit 1
            ;;
    esac
    
    # Apply configuration
    chmod 644 "$banner_file"
    chown root:wheel "$banner_file"
    diskutil apfs updatePreboot / 2>/dev/null
    
    echo "Dynamic policy banner ($template) generated successfully."
}

create_default_config() {
    cat > "/etc/macfleet/banner_config.conf" << 'EOF'
# MacFleet Policy Banner Configuration
ORGANIZATION_NAME="MacFleet Organization"
CONTACT_EMAIL="support@macfleet.com"
CONTACT_PHONE="1-800-MACFLEET"
COMPLIANCE_OFFICER="Compliance Team"
EFFECTIVE_DATE="2025-01-01"
MONITORING_ENABLED="true"
PERSONAL_USE_POLICY="restricted"
EOF
}

generate_corporate_banner() {
    cat > "$banner_file" << EOF
$ORGANIZATION_NAME
AUTHORIZED USE POLICY

This computer system is provided for authorized business use only.

TERMS OF USE:
• Access is restricted to authorized personnel only
• All activities are monitored and logged for security purposes
• Unauthorized access or misuse is prohibited
• Personal use is $PERSONAL_USE_POLICY per company policy
• Users must comply with all applicable laws and regulations

MONITORING NOTICE:
By using this system, you consent to monitoring and recording of your activities.
This includes but is not limited to: network traffic, file access, and application usage.

For questions or concerns, contact:
$COMPLIANCE_OFFICER at $CONTACT_EMAIL or $CONTACT_PHONE

Effective Date: $EFFECTIVE_DATE

Your continued use constitutes acceptance of these terms.
EOF
}

generate_government_banner() {
    cat > "$banner_file" << EOF
$ORGANIZATION_NAME
OFFICIAL USE ONLY

WARNING: This is a U.S. Government computer system for official use only.

By accessing this system, you agree to the following:
• This system is for authorized government business only
• All activities are subject to monitoring and recording
• Unauthorized access is a violation of federal law
• Evidence of criminal activity will be reported to law enforcement
• Personal use is strictly prohibited

PRIVACY NOTICE:
Users have no expectation of privacy when using this system.
All information stored or transmitted may be monitored or recorded.

Unauthorized use may result in:
• Criminal prosecution under 18 USC 1030
• Civil liability
• Administrative action including termination

For official use authorization, contact: $CONTACT_EMAIL

Effective Date: $EFFECTIVE_DATE
EOF
}

generate_healthcare_banner() {
    cat > "$banner_file" << EOF
$ORGANIZATION_NAME
HIPAA COMPLIANCE NOTICE

This system contains Protected Health Information (PHI) subject to HIPAA regulations.

ACCESS REQUIREMENTS:
• Access is restricted to authorized healthcare personnel only
• Users must have legitimate business need for PHI access
• All PHI access is logged and monitored for compliance
• Unauthorized access may result in HIPAA violations

PRIVACY AND SECURITY:
• All activities are monitored for HIPAA compliance
• PHI must be handled according to organization policies
• Report suspected privacy breaches immediately
• Personal use of this system is prohibited

COMPLIANCE OBLIGATIONS:
• Users must complete required HIPAA training
• Passwords must meet complexity requirements
• Workstations must be locked when unattended
• PHI must not be disclosed to unauthorized persons

For HIPAA compliance questions: $CONTACT_EMAIL

Effective Date: $EFFECTIVE_DATE

Your access confirms your understanding of these obligations.
EOF
}

generate_education_banner() {
    cat > "$banner_file" << EOF
$ORGANIZATION_NAME
EDUCATIONAL TECHNOLOGY POLICY

This computer system is provided for educational purposes and authorized use only.

ACCEPTABLE USE:
• Access is limited to students, faculty, and authorized staff
• Use must support educational objectives and institutional mission
• All activities are monitored to ensure appropriate use
• Personal use is limited and subject to institutional policy

STUDENT PRIVACY:
• Student records are protected under FERPA regulations
• Access to student information requires legitimate educational interest
• Unauthorized disclosure of student information is prohibited
• Report suspected privacy violations immediately

PROHIBITED ACTIVITIES:
• Accessing, copying, or sharing inappropriate content
• Violating copyright or intellectual property rights
• Harassment, bullying, or discriminatory behavior
• Installing unauthorized software or applications

For technology support: $CONTACT_EMAIL
For policy questions: $COMPLIANCE_OFFICER

Effective Date: $EFFECTIVE_DATE

Your use indicates acceptance of these terms.
EOF
}

generate_financial_banner() {
    cat > "$banner_file" << EOF
$ORGANIZATION_NAME
FINANCIAL SERVICES COMPLIANCE

This system processes financial data subject to regulatory oversight.

REGULATORY COMPLIANCE:
• Access restricted to authorized financial services personnel
• All transactions are monitored for compliance with:
  - SOX (Sarbanes-Oxley Act)
  - GLBA (Gramm-Leach-Bliley Act)
  - PCI DSS (Payment Card Industry Data Security Standard)
• Financial data must be protected according to regulatory requirements

SECURITY REQUIREMENTS:
• Strong authentication is required for all access
• Financial data must not be stored on local devices
• All access is logged and subject to audit
• Suspicious activity will be reported to regulators

CONFIDENTIALITY:
• Customer financial information is strictly confidential
• Access requires legitimate business purpose
• Unauthorized disclosure may result in regulatory action
• Personal use of this system is prohibited

For compliance questions: $COMPLIANCE_OFFICER
For technical support: $CONTACT_EMAIL

Effective Date: $EFFECTIVE_DATE

Your access confirms compliance with these requirements.
EOF
}

# Execute generator
generate_dynamic_banner "$1"

Enterprise Policy Banner Management

Centralized Banner Deployment

#!/bin/bash

# Centralized policy banner deployment for Mac fleet
# Usage: ./enterprise_banner_deploy.sh

deploy_enterprise_banner() {
    local deployment_id="$(date +%Y%m%d_%H%M%S)"
    local log_file="/var/log/macfleet_banner_deployment.log"
    local config_server="https://config.macfleet.com"
    local device_id=$(system_profiler SPHardwareDataType | grep "Hardware UUID" | awk '{print $3}')
    
    # Check if running as root
    if [ "$EUID" -ne 0 ]; then
        echo "Error: This script must be run as root"
        exit 1
    fi
    
    # Create log entry
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Starting enterprise banner deployment (ID: $deployment_id)" >> "$log_file"
    
    # Get device information
    local computer_name=$(scutil --get ComputerName)
    local os_version=$(sw_vers -productVersion)
    local build_version=$(sw_vers -buildVersion)
    
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Device: $computer_name ($device_id)" >> "$log_file"
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] OS: macOS $os_version ($build_version)" >> "$log_file"
    
    # Fetch organization-specific banner configuration
    fetch_banner_config
    
    # Deploy banner based on configuration
    if [ -f "/tmp/banner_config.json" ]; then
        parse_and_deploy_banner
    else
        deploy_default_banner
    fi
    
    # Validate deployment
    validate_banner_deployment
    
    # Report deployment status
    report_deployment_status "$deployment_id"
    
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Enterprise banner deployment completed (ID: $deployment_id)" >> "$log_file"
}

fetch_banner_config() {
    local config_url="$config_server/api/banner/config"
    local headers="X-Device-ID: $device_id"
    
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Fetching banner configuration from: $config_url" >> "$log_file"
    
    # Attempt to fetch configuration (simulated - replace with actual API call)
    # curl -s -H "$headers" "$config_url" -o "/tmp/banner_config.json"
    
    # Create mock configuration for demonstration
    cat > "/tmp/banner_config.json" << 'EOF'
{
  "organization": "MacFleet Enterprise",
  "template": "corporate",
  "language": "en",
  "custom_message": "",
  "monitoring_enabled": true,
  "contact_info": {
    "email": "compliance@macfleet.com",
    "phone": "1-800-MACFLEET"
  },
  "compliance_requirements": [
    "SOX", "HIPAA", "PCI-DSS"
  ],
  "effective_date": "2025-07-07"
}
EOF
    
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Configuration fetched successfully" >> "$log_file"
}

parse_and_deploy_banner() {
    local config_file="/tmp/banner_config.json"
    
    # Parse JSON configuration (requires jq or manual parsing)
    local organization=$(grep -o '"organization"[^,]*' "$config_file" | cut -d'"' -f4)
    local template=$(grep -o '"template"[^,]*' "$config_file" | cut -d'"' -f4)
    local language=$(grep -o '"language"[^,]*' "$config_file" | cut -d'"' -f4)
    
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Deploying banner for $organization (template: $template, language: $language)" >> "$log_file"
    
    # Create banner based on configuration
    cat > "/Library/Security/PolicyBanner.txt" << EOF
$organization
ENTERPRISE POLICY BANNER

This computer system is owned by $organization and is provided for authorized business use only.

By accessing this system, you acknowledge and agree to:
• Comply with all applicable corporate policies and procedures
• Submit to monitoring and logging of all system activities
• Respect the confidentiality of proprietary information
• Report security incidents immediately to IT security team
• Use the system only for legitimate business purposes

MONITORING NOTICE:
All activities on this system are subject to monitoring and recording.
This includes but is not limited to network traffic, file access, email, and application usage.

COMPLIANCE REQUIREMENTS:
This system must comply with applicable regulations including SOX, HIPAA, and PCI-DSS.
Users are responsible for maintaining compliance with all applicable standards.

For questions or to report security incidents:
Email: compliance@macfleet.com
Phone: 1-800-MACFLEET

Effective Date: 2025-07-07

Your continued use constitutes acceptance of these terms and conditions.
EOF
    
    # Set proper permissions
    chmod 644 "/Library/Security/PolicyBanner.txt"
    chown root:wheel "/Library/Security/PolicyBanner.txt"
    
    # Clean up temporary files
    rm -f "/tmp/banner_config.json"
}

deploy_default_banner() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Deploying default banner (configuration not available)" >> "$log_file"
    
    cat > "/Library/Security/PolicyBanner.txt" << 'EOF'
MacFleet Organization
AUTHORIZED USE ONLY

This computer system is provided for authorized business use only.

By proceeding, you acknowledge that:
• You are an authorized user with legitimate business access
• All activities are monitored and logged for security purposes
• Unauthorized access or misuse is strictly prohibited
• Personal use may be restricted per company policy
• You agree to comply with all applicable policies and regulations

Your continued use constitutes acceptance of these terms.

For questions: support@macfleet.com
EOF
    
    chmod 644 "/Library/Security/PolicyBanner.txt"
    chown root:wheel "/Library/Security/PolicyBanner.txt"
}

validate_banner_deployment() {
    local banner_file="/Library/Security/PolicyBanner.txt"
    
    if [ -f "$banner_file" ]; then
        local file_size=$(stat -f%z "$banner_file")
        local file_perms=$(stat -f%p "$banner_file")
        
        echo "[$(date '+%Y-%m-%d %H:%M:%S')] Banner validation: File exists, size: $file_size bytes, permissions: $file_perms" >> "$log_file"
        
        # Update preboot volume
        if diskutil apfs updatePreboot / 2>/dev/null; then
            echo "[$(date '+%Y-%m-%d %H:%M:%S')] Preboot volume updated successfully" >> "$log_file"
        else
            echo "[$(date '+%Y-%m-%d %H:%M:%S')] Warning: Failed to update preboot volume" >> "$log_file"
        fi
        
        return 0
    else
        echo "[$(date '+%Y-%m-%d %H:%M:%S')] Error: Banner file not found after deployment" >> "$log_file"
        return 1
    fi
}

report_deployment_status() {
    local deployment_id="$1"
    local status_url="$config_server/api/banner/status"
    
    # Create status report
    cat > "/tmp/deployment_status.json" << EOF
{
  "deployment_id": "$deployment_id",
  "device_id": "$device_id",
  "computer_name": "$computer_name",
  "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
  "status": "completed",
  "os_version": "$os_version",
  "banner_deployed": true
}
EOF
    
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Deployment status prepared for reporting" >> "$log_file"
    
    # Send status report (simulated)
    # curl -s -X POST -H "Content-Type: application/json" -d @"/tmp/deployment_status.json" "$status_url"
    
    # Clean up
    rm -f "/tmp/deployment_status.json"
}

# Execute deployment
deploy_enterprise_banner

Policy Banner Monitoring and Compliance

#!/bin/bash

# Policy banner monitoring and compliance checking
# Usage: ./banner_compliance_check.sh

check_banner_compliance() {
    local log_file="/var/log/macfleet_banner_compliance.log"
    local banner_file="/Library/Security/PolicyBanner.txt"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    local device_id=$(system_profiler SPHardwareDataType | grep "Hardware UUID" | awk '{print $3}')
    
    echo "[$timestamp] Starting policy banner compliance check on device: $device_id" >> "$log_file"
    
    # Check if banner file exists
    if [ ! -f "$banner_file" ]; then
        echo "[$timestamp] COMPLIANCE VIOLATION: Policy banner file not found" >> "$log_file"
        echo "VIOLATION: Policy banner not deployed"
        return 1
    fi
    
    # Check file permissions
    local file_perms=$(stat -f%p "$banner_file")
    local expected_perms="100644"
    
    if [ "$file_perms" != "$expected_perms" ]; then
        echo "[$timestamp] COMPLIANCE WARNING: Banner file permissions incorrect (found: $file_perms, expected: $expected_perms)" >> "$log_file"
        echo "WARNING: Incorrect file permissions detected"
        
        # Attempt to fix permissions
        chmod 644 "$banner_file"
        chown root:wheel "$banner_file"
        echo "[$timestamp] Permissions corrected automatically" >> "$log_file"
    fi
    
    # Check file ownership
    local file_owner=$(stat -f%u:%g "$banner_file")
    local expected_owner="0:0"
    
    if [ "$file_owner" != "$expected_owner" ]; then
        echo "[$timestamp] COMPLIANCE WARNING: Banner file ownership incorrect (found: $file_owner, expected: $expected_owner)" >> "$log_file"
        echo "WARNING: Incorrect file ownership detected"
        
        # Attempt to fix ownership
        chown root:wheel "$banner_file"
        echo "[$timestamp] Ownership corrected automatically" >> "$log_file"
    fi
    
    # Check banner content
    local file_size=$(stat -f%z "$banner_file")
    if [ "$file_size" -lt 100 ]; then
        echo "[$timestamp] COMPLIANCE WARNING: Banner file appears to be empty or too small ($file_size bytes)" >> "$log_file"
        echo "WARNING: Banner content may be insufficient"
    fi
    
    # Check for required keywords
    local required_keywords=("AUTHORIZED" "MONITORING" "PROHIBITED" "POLICY")
    local missing_keywords=()
    
    for keyword in "${required_keywords[@]}"; do
        if ! grep -q "$keyword" "$banner_file" 2>/dev/null; then
            missing_keywords+=("$keyword")
        fi
    done
    
    if [ ${#missing_keywords[@]} -gt 0 ]; then
        echo "[$timestamp] COMPLIANCE WARNING: Missing required keywords: ${missing_keywords[*]}" >> "$log_file"
        echo "WARNING: Banner may not meet compliance requirements"
    fi
    
    # Check banner age
    local banner_age=$(( $(date +%s) - $(stat -f%m "$banner_file") ))
    local max_age=7776000  # 90 days in seconds
    
    if [ "$banner_age" -gt "$max_age" ]; then
        echo "[$timestamp] COMPLIANCE NOTICE: Banner is older than 90 days (age: $((banner_age/86400)) days)" >> "$log_file"
        echo "NOTICE: Banner may need updating"
    fi
    
    # Generate compliance report
    generate_compliance_report
    
    echo "[$timestamp] Compliance check completed" >> "$log_file"
    echo "Policy banner compliance check completed."
}

generate_compliance_report() {
    local report_file="/tmp/banner_compliance_report.txt"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    
    cat > "$report_file" << EOF
MacFleet Policy Banner Compliance Report
Generated: $timestamp
Device: $(scutil --get ComputerName)
Device ID: $device_id

COMPLIANCE STATUS:
$([ -f "$banner_file" ] && echo "✓ Policy banner deployed" || echo "✗ Policy banner missing")
$([ "$(stat -f%p "$banner_file" 2>/dev/null)" = "100644" ] && echo "✓ Correct file permissions" || echo "✗ Incorrect file permissions")
$([ "$(stat -f%u:%g "$banner_file" 2>/dev/null)" = "0:0" ] && echo "✓ Correct file ownership" || echo "✗ Incorrect file ownership")

BANNER CONTENT ANALYSIS:
File size: $(stat -f%z "$banner_file" 2>/dev/null || echo "N/A") bytes
Last modified: $(stat -f%Sm "$banner_file" 2>/dev/null || echo "N/A")
Content preview:
$(head -3 "$banner_file" 2>/dev/null || echo "No content available")

RECOMMENDATIONS:
• Review banner content regularly for policy updates
• Ensure banner meets organizational compliance requirements
• Monitor banner deployment across all managed devices
• Update banner when policies change

Report saved to: $report_file
EOF
    
    echo "Compliance report generated: $report_file"
}

# Execute compliance check
check_banner_compliance

Policy Banner Removal and Management

Safe Banner Removal

#!/bin/bash

# Safe policy banner removal with backup
# Usage: ./remove_policy_banner.sh

remove_policy_banner() {
    local banner_file="/Library/Security/PolicyBanner.txt"
    local backup_dir="/var/backups/macfleet"
    local timestamp=$(date '+%Y%m%d_%H%M%S')
    local log_file="/var/log/macfleet_banner_removal.log"
    
    # Check if running as root
    if [ "$EUID" -ne 0 ]; then
        echo "Error: This script must be run as root"
        exit 1
    fi
    
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Starting policy banner removal" >> "$log_file"
    
    # Check if banner exists
    if [ ! -f "$banner_file" ]; then
        echo "No policy banner found to remove."
        echo "[$(date '+%Y-%m-%d %H:%M:%S')] No policy banner found" >> "$log_file"
        return 0
    fi
    
    # Create backup directory
    mkdir -p "$backup_dir"
    
    # Backup current banner
    cp "$banner_file" "$backup_dir/PolicyBanner_backup_$timestamp.txt"
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Banner backed up to $backup_dir/PolicyBanner_backup_$timestamp.txt" >> "$log_file"
    
    # Remove banner file
    rm -f "$banner_file"
    
    # Verify removal
    if [ ! -f "$banner_file" ]; then
        echo "Policy banner removed successfully."
        echo "[$(date '+%Y-%m-%d %H:%M:%S')] Policy banner removed successfully" >> "$log_file"
        
        # Update preboot volume
        if diskutil apfs updatePreboot / 2>/dev/null; then
            echo "[$(date '+%Y-%m-%d %H:%M:%S')] Preboot volume updated" >> "$log_file"
            echo "Preboot volume updated."
        else
            echo "[$(date '+%Y-%m-%d %H:%M:%S')] Warning: Failed to update preboot volume" >> "$log_file"
            echo "Warning: Could not update preboot volume."
        fi
    else
        echo "Error: Failed to remove policy banner."
        echo "[$(date '+%Y-%m-%d %H:%M:%S')] Error: Failed to remove policy banner" >> "$log_file"
        return 1
    fi
}

# Execute removal
remove_policy_banner

Banner Management Dashboard

#!/bin/bash

# Interactive policy banner management dashboard
# Usage: ./banner_dashboard.sh

banner_management_dashboard() {
    local banner_file="/Library/Security/PolicyBanner.txt"
    
    while true; do
        clear
        echo "=================================="
        echo "MacFleet Policy Banner Management"
        echo "=================================="
        echo ""
        
        # Display current status
        if [ -f "$banner_file" ]; then
            echo "Status: Policy banner is ACTIVE"
            echo "Size: $(stat -f%z "$banner_file") bytes"
            echo "Modified: $(stat -f%Sm "$banner_file")"
            echo "Permissions: $(stat -f%p "$banner_file")"
        else
            echo "Status: No policy banner deployed"
        fi
        
        echo ""
        echo "Available Actions:"
        echo "1. View current banner"
        echo "2. Create new banner"
        echo "3. Edit existing banner"
        echo "4. Remove banner"
        echo "5. Check compliance"
        echo "6. Export banner"
        echo "7. Import banner"
        echo "8. View logs"
        echo "9. Exit"
        echo ""
        read -p "Select an option (1-9): " choice
        
        case $choice in
            1)
                view_current_banner
                ;;
            2)
                create_new_banner
                ;;
            3)
                edit_existing_banner
                ;;
            4)
                remove_banner
                ;;
            5)
                check_compliance
                ;;
            6)
                export_banner
                ;;
            7)
                import_banner
                ;;
            8)
                view_logs
                ;;
            9)
                echo "Exiting banner management dashboard."
                exit 0
                ;;
            *)
                echo "Invalid option. Please try again."
                ;;
        esac
        
        echo ""
        read -p "Press Enter to continue..."
    done
}

view_current_banner() {
    echo "=================================="
    echo "Current Policy Banner Content"
    echo "=================================="
    
    if [ -f "$banner_file" ]; then
        cat "$banner_file"
    else
        echo "No policy banner is currently deployed."
    fi
}

create_new_banner() {
    echo "=================================="
    echo "Create New Policy Banner"
    echo "=================================="
    
    echo "Enter your policy banner text (end with Ctrl+D):"
    cat > "$banner_file"
    
    # Set proper permissions
    chmod 644 "$banner_file"
    chown root:wheel "$banner_file"
    
    # Update preboot volume
    diskutil apfs updatePreboot / 2>/dev/null
    
    echo "New policy banner created successfully."
}

edit_existing_banner() {
    echo "=================================="
    echo "Edit Existing Policy Banner"
    echo "=================================="
    
    if [ ! -f "$banner_file" ]; then
        echo "No existing banner found. Create a new one first."
        return
    fi
    
    # Create backup
    cp "$banner_file" "$banner_file.backup"
    
    echo "Current banner content:"
    cat "$banner_file"
    echo ""
    echo "Enter new banner text (end with Ctrl+D):"
    cat > "$banner_file"
    
    # Set proper permissions
    chmod 644 "$banner_file"
    chown root:wheel "$banner_file"
    
    # Update preboot volume
    diskutil apfs updatePreboot / 2>/dev/null
    
    echo "Policy banner updated successfully."
}

remove_banner() {
    echo "=================================="
    echo "Remove Policy Banner"
    echo "=================================="
    
    if [ ! -f "$banner_file" ]; then
        echo "No policy banner found to remove."
        return
    fi
    
    read -p "Are you sure you want to remove the policy banner? (y/N): " confirm
    if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
        # Create backup
        cp "$banner_file" "/tmp/PolicyBanner_removed_$(date +%Y%m%d_%H%M%S).txt"
        
        # Remove banner
        rm -f "$banner_file"
        
        # Update preboot volume
        diskutil apfs updatePreboot / 2>/dev/null
        
        echo "Policy banner removed successfully."
    else
        echo "Operation cancelled."
    fi
}

check_compliance() {
    echo "=================================="
    echo "Policy Banner Compliance Check"
    echo "=================================="
    
    # Run compliance check (reuse function from earlier)
    check_banner_compliance
}

export_banner() {
    echo "=================================="
    echo "Export Policy Banner"
    echo "=================================="
    
    if [ ! -f "$banner_file" ]; then
        echo "No policy banner found to export."
        return
    fi
    
    local export_file="/tmp/PolicyBanner_export_$(date +%Y%m%d_%H%M%S).txt"
    cp "$banner_file" "$export_file"
    
    echo "Policy banner exported to: $export_file"
}

import_banner() {
    echo "=================================="
    echo "Import Policy Banner"
    echo "=================================="
    
    read -p "Enter the full path to the banner file to import: " import_file
    
    if [ ! -f "$import_file" ]; then
        echo "Error: File not found: $import_file"
        return
    fi
    
    # Copy imported file
    cp "$import_file" "$banner_file"
    
    # Set proper permissions
    chmod 644 "$banner_file"
    chown root:wheel "$banner_file"
    
    # Update preboot volume
    diskutil apfs updatePreboot / 2>/dev/null
    
    echo "Policy banner imported successfully."
}

view_logs() {
    echo "=================================="
    echo "Policy Banner Logs"
    echo "=================================="
    
    local log_files=(
        "/var/log/macfleet_policy_banner.log"
        "/var/log/macfleet_banner_deployment.log"
        "/var/log/macfleet_banner_compliance.log"
        "/var/log/macfleet_banner_removal.log"
    )
    
    for log_file in "${log_files[@]}"; do
        if [ -f "$log_file" ]; then
            echo "--- $log_file ---"
            tail -10 "$log_file"
            echo ""
        fi
    done
}

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    echo "Error: This script must be run as root"
    exit 1
fi

# Start dashboard
banner_management_dashboard

Troubleshooting and Best Practices

Common Issues and Solutions

1. Banner Not Appearing

# Check file permissions
ls -la /Library/Security/PolicyBanner.txt

# Fix permissions if needed
sudo chmod 644 /Library/Security/PolicyBanner.txt
sudo chown root:wheel /Library/Security/PolicyBanner.txt

# Update preboot volume
sudo diskutil apfs updatePreboot /

2. FileVault Compatibility

# For FileVault-enabled devices, ensure preboot volume is updated
sudo diskutil apfs updatePreboot /

# Check FileVault status
sudo fdesetup status

3. Banner Content Issues

# Check file encoding
file /Library/Security/PolicyBanner.txt

# Ensure proper line endings
dos2unix /Library/Security/PolicyBanner.txt

Best Practices for Policy Banner Management

  1. Regular Updates: Review and update policy banners regularly to reflect current policies
  2. Compliance Documentation: Maintain records of banner deployments for audit purposes
  3. User Training: Ensure users understand the importance of policy acknowledgment
  4. Monitoring: Implement monitoring to ensure banners remain deployed across all devices
  5. Backup Management: Maintain backups of all policy banner configurations
  6. Testing: Test banner deployments in a controlled environment before enterprise rollout

Security Considerations

  • File Integrity: Monitor banner files for unauthorized modifications
  • Access Control: Restrict banner management to authorized administrators only
  • Audit Trail: Maintain logs of all banner management activities
  • Encryption: Consider encrypting banner content for sensitive environments

Conclusion

Policy banners are essential tools for organizational compliance and security awareness. This comprehensive guide provides enterprise-grade solutions for deploying, managing, and monitoring policy banners across Mac fleets. The scripts and procedures outlined ensure consistent policy communication while maintaining security and compliance standards.

Remember to test all scripts in a controlled environment before deploying to production systems, and always maintain proper backups of your policy configurations. Regular monitoring and updates ensure that your policy banners remain effective and compliant with organizational requirements.