Tutorial

New updates and improvements to Roundfleet.

Remote Management and Secure Access Control on macOS

Implement comprehensive remote management and secure access control across your Roundfleet 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

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

# Configuration
LOG_FILE="/var/log/roundfleet_remote_management.log"
CONFIG_DIR="/etc/roundfleet/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/roundfleet_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": "Roundfleet 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/roundfleet_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 "=== Roundfleet 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 "Roundfleet: High number of remote connection attempts detected: $CONNECTION_ATTEMPTS"
        # Send alert
        echo "High connection attempts: $CONNECTION_ATTEMPTS" | mail -s "Roundfleet Security Alert" [email protected]
    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 "Roundfleet: 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 "Roundfleet: 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 Roundfleet 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/roundfleet/proxy_config.conf"
LOG_FILE="/var/log/roundfleet_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

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

# Configuration
PROXY_CONFIG_DIR="/etc/roundfleet/proxy"
LOG_FILE="/var/log/roundfleet_proxy.log"
BACKUP_DIR="/var/backups/roundfleet/proxy"
API_ENDPOINT="https://api.roundfleet.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 "Roundfleet 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 "Roundfleet 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 "Roundfleet Proxy Management completed"
}

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

Proxy Configuration Templates

Corporate Web Proxy Template

# /etc/roundfleet/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/roundfleet/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/roundfleet/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="Roundfleet-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="Roundfleet-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 Roundfleet environment, and ensure proxy servers are accessible and properly configured for your network infrastructure.

Printer Management on macOS

Manage printer infrastructure across your Roundfleet 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

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

# Configuration
ROUNDFLEET_DIR="/etc/roundfleet"
PRINTER_DIR="$ROUNDFLEET_DIR/printer_management"
REPORTS_DIR="$ROUNDFLEET_DIR/reports"
COMPLIANCE_DIR="$ROUNDFLEET_DIR/compliance"
AUDIT_DIR="$ROUNDFLEET_DIR/audit"
LOG_FILE="/var/log/roundfleet_printer_management.log"
POLICIES_DIR="$ROUNDFLEET_DIR/printer_policies"

# Create directory structure
create_directories() {
    local dirs=("$ROUNDFLEET_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 "Roundfleet $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 "=== Roundfleet 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/roundfleet/{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 "Roundfleet 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/roundfleet_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 Roundfleet 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 Roundfleet 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 Roundfleet 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 Roundfleet 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 Roundfleet 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/roundfleet/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/roundfleet
    
    # 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/roundfleet/banner_config.conf" << 'EOF'
# Roundfleet Policy Banner Configuration
ORGANIZATION_NAME="Roundfleet Organization"
CONTACT_EMAIL="[email protected]"
CONTACT_PHONE="1-800-ROUNDFLEET"
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/roundfleet_banner_deployment.log"
    local config_server="https://config.roundfleet.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": "Roundfleet Enterprise",
  "template": "corporate",
  "language": "en",
  "custom_message": "",
  "monitoring_enabled": true,
  "contact_info": {
    "email": "[email protected]",
    "phone": "1-800-ROUNDFLEET"
  },
  "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: [email protected]
Phone: 1-800-ROUNDFLEET

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'
Roundfleet 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: [email protected]
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/roundfleet_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
Roundfleet 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/roundfleet"
    local timestamp=$(date '+%Y%m%d_%H%M%S')
    local log_file="/var/log/roundfleet_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 "Roundfleet 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/roundfleet_policy_banner.log"
        "/var/log/roundfleet_banner_deployment.log"
        "/var/log/roundfleet_banner_compliance.log"
        "/var/log/roundfleet_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.

Password Management on macOS

Implement comprehensive password management and authentication control across your Roundfleet devices using advanced directory services and system administration tools. This tutorial covers password clearing, policy enforcement, and enterprise authentication management.

Understanding macOS Password Management

macOS provides multiple tools for password management:

  • dscl - Directory Services Command Line utility for user management
  • sysadminctl - System administrator control tool for user operations
  • Directory Services - Core authentication and authorization framework
  • Security Framework - Advanced password policy and enforcement mechanisms

Basic Password Operations

Clear User Password (Basic Method)

#!/bin/bash

# Basic password clearing using dscl
clear_user_password_dscl() {
    local username="$1"
    local current_password="$2"
    
    echo "=== Clearing Password for User: $username ==="
    
    # Validate parameters
    if [[ -z "$username" || -z "$current_password" ]]; then
        echo "❌ Usage: clear_user_password_dscl <username> <current_password>"
        return 1
    fi
    
    # Check if user exists
    if ! dscl . -read "/Users/$username" >/dev/null 2>&1; then
        echo "❌ User '$username' does not exist"
        return 1
    fi
    
    # Clear password using dscl
    echo "Clearing password for user: $username"
    if dscl . passwd "/Users/$username" "$current_password" ""; then
        echo "✅ Password cleared successfully for user: $username"
        echo "ℹ️  User can now login by pressing Enter without a password"
    else
        echo "❌ Failed to clear password for user: $username"
        echo "   Check that the current password is correct"
        return 1
    fi
}

# Usage: clear_user_password_dscl "john.doe" "currentpass123"

Clear Password Using sysadminctl

#!/bin/bash

# Advanced password clearing using sysadminctl
clear_user_password_sysadminctl() {
    local target_username="$1"
    local admin_username="$2"
    local admin_password="$3"
    
    echo "=== Clearing Password Using sysadminctl ==="
    echo "Target user: $target_username"
    echo "Admin user: $admin_username"
    
    # Validate parameters
    if [[ -z "$target_username" || -z "$admin_username" || -z "$admin_password" ]]; then
        echo "❌ Usage: clear_user_password_sysadminctl <target_user> <admin_user> <admin_password>"
        return 1
    fi
    
    # Check if target user exists
    if ! dscl . -read "/Users/$target_username" >/dev/null 2>&1; then
        echo "❌ Target user '$target_username' does not exist"
        return 1
    fi
    
    # Check if admin user exists and has admin privileges
    if ! dscl . -read "/Users/$admin_username" >/dev/null 2>&1; then
        echo "❌ Admin user '$admin_username' does not exist"
        return 1
    fi
    
    # Clear password using sysadminctl
    echo "Clearing password for user: $target_username"
    if sysadminctl -resetPasswordFor "$target_username" -newPassword "" -adminUser "$admin_username" -adminPassword "$admin_password"; then
        echo "✅ Password cleared successfully for user: $target_username"
        echo "ℹ️  User can now login without entering a password"
    else
        echo "❌ Failed to clear password for user: $target_username"
        echo "   Check admin credentials and user permissions"
        return 1
    fi
}

# Usage: clear_user_password_sysadminctl "jane.doe" "admin" "adminpass123"

Advanced Password Management

Check Password Status

#!/bin/bash

# Check user password and authentication status
check_password_status() {
    local username="$1"
    
    echo "=== Password Status Check for User: $username ==="
    
    if [[ -z "$username" ]]; then
        echo "❌ Usage: check_password_status <username>"
        return 1
    fi
    
    # Check if user exists
    if ! dscl . -read "/Users/$username" >/dev/null 2>&1; then
        echo "❌ User '$username' does not exist"
        return 1
    fi
    
    # Get user information
    echo "User Information:"
    echo "Real Name: $(dscl . -read "/Users/$username" RealName | cut -d' ' -f2- || echo 'Not set')"
    echo "UID: $(dscl . -read "/Users/$username" UniqueID | awk '{print $2}')"
    echo "Primary Group ID: $(dscl . -read "/Users/$username" PrimaryGroupID | awk '{print $2}')"
    echo "Home Directory: $(dscl . -read "/Users/$username" NFSHomeDirectory | cut -d' ' -f2-)"
    echo "Shell: $(dscl . -read "/Users/$username" UserShell | cut -d' ' -f2-)"
    
    # Check password policy
    echo ""
    echo "Password Policy Information:"
    local password_policy=$(pwpolicy -u "$username" -getpolicy 2>/dev/null || echo "No specific policy")
    echo "Password Policy: $password_policy"
    
    # Check account status
    echo ""
    echo "Account Status:"
    local account_policy=$(pwpolicy -u "$username" -getaccountpolicy 2>/dev/null || echo "No account policy")
    echo "Account Policy: $account_policy"
    
    # Check if password is empty
    echo ""
    echo "Password Status:"
    local auth_authority=$(dscl . -read "/Users/$username" AuthenticationAuthority 2>/dev/null)
    if [[ -z "$auth_authority" ]] || echo "$auth_authority" | grep -q "ShadowHash"; then
        echo "Password Type: Shadow Hash (Standard)"
    else
        echo "Password Type: $auth_authority"
    fi
}

check_password_status

Secure Password Setting

#!/bin/bash

# Set secure password with validation
set_secure_password() {
    local username="$1"
    local new_password="$2"
    local admin_username="$3"
    local admin_password="$4"
    
    echo "=== Setting Secure Password for User: $username ==="
    
    # Validate parameters
    if [[ -z "$username" || -z "$new_password" || -z "$admin_username" || -z "$admin_password" ]]; then
        echo "❌ Usage: set_secure_password <username> <new_password> <admin_user> <admin_password>"
        return 1
    fi
    
    # Check password strength
    if ! validate_password_strength "$new_password"; then
        echo "❌ Password does not meet security requirements"
        return 1
    fi
    
    # Set password using sysadminctl
    echo "Setting secure password for user: $username"
    if sysadminctl -resetPasswordFor "$username" -newPassword "$new_password" -adminUser "$admin_username" -adminPassword "$admin_password"; then
        echo "✅ Secure password set successfully for user: $username"
        
        # Apply password policy
        apply_password_policy "$username"
    else
        echo "❌ Failed to set password for user: $username"
        return 1
    fi
}

# Validate password strength
validate_password_strength() {
    local password="$1"
    local min_length=8
    local has_upper=false
    local has_lower=false
    local has_digit=false
    local has_special=false
    
    # Check minimum length
    if [[ ${#password} -lt $min_length ]]; then
        echo "⚠️  Password must be at least $min_length characters long"
        return 1
    fi
    
    # Check for uppercase letter
    if [[ "$password" =~ [A-Z] ]]; then
        has_upper=true
    fi
    
    # Check for lowercase letter
    if [[ "$password" =~ [a-z] ]]; then
        has_lower=true
    fi
    
    # Check for digit
    if [[ "$password" =~ [0-9] ]]; then
        has_digit=true
    fi
    
    # Check for special character
    if [[ "$password" =~ [^a-zA-Z0-9] ]]; then
        has_special=true
    fi
    
    # Validate all requirements
    if [[ "$has_upper" == true && "$has_lower" == true && "$has_digit" == true && "$has_special" == true ]]; then
        echo "✅ Password meets security requirements"
        return 0
    else
        echo "⚠️  Password must contain uppercase, lowercase, digit, and special character"
        return 1
    fi
}

# Apply password policy
apply_password_policy() {
    local username="$1"
    
    echo "Applying password policy for user: $username"
    
    # Set password policy (requires admin privileges)
    pwpolicy -u "$username" -setpolicy "minChars=8 requiresAlpha requiresNumeric requiresMixedCase requiresSymbol passwordCannotBeName maxMinutesUntilChangePassword=7776000" 2>/dev/null || true
    
    echo "✅ Password policy applied"
}

Enterprise Password Management System

#!/bin/bash

# Roundfleet Enterprise Password Management System
# Comprehensive user authentication and password policy management

# Configuration
PASSWORD_CONFIG_FILE="/etc/roundfleet/password_config.conf"
LOG_FILE="/var/log/roundfleet_password_management.log"
AUDIT_FILE="/var/log/roundfleet_password_audit.log"
BACKUP_DIR="/var/backups/roundfleet/user_accounts"

# Default settings
DEFAULT_MIN_PASSWORD_LENGTH=12
DEFAULT_PASSWORD_EXPIRY_DAYS=90
DEFAULT_MAX_FAILED_ATTEMPTS=5
DEFAULT_LOCKOUT_DURATION=30

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

# Audit logging function
audit_log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - AUDIT - $1" | tee -a "$AUDIT_FILE"
}

# Load password management configuration
load_password_config() {
    if [[ -f "$PASSWORD_CONFIG_FILE" ]]; then
        source "$PASSWORD_CONFIG_FILE"
        log_action "Loaded password configuration from $PASSWORD_CONFIG_FILE"
    else
        log_action "Using default password configuration"
    fi
}

# Backup user account information
backup_user_account() {
    local username="$1"
    local backup_file="$BACKUP_DIR/user_backup_${username}_$(date +%Y%m%d_%H%M%S).plist"
    
    # Create backup directory
    sudo mkdir -p "$BACKUP_DIR"
    
    # Export user record
    if dscl . -read "/Users/$username" > "$backup_file" 2>/dev/null; then
        log_action "User account backup created: $backup_file"
        audit_log "BACKUP_CREATED for user: $username"
    else
        log_action "Failed to create backup for user: $username"
    fi
}

# Enterprise password clearing with safety checks
enterprise_clear_password() {
    local username="$1"
    local admin_username="$2"
    local admin_password="$3"
    local force_clear="${4:-false}"
    
    log_action "Starting enterprise password clear for user: $username"
    audit_log "PASSWORD_CLEAR_INITIATED for user: $username by admin: $admin_username"
    
    # Validate parameters
    if [[ -z "$username" || -z "$admin_username" || -z "$admin_password" ]]; then
        log_action "❌ Missing required parameters for password clear"
        return 1
    fi
    
    # Check if user exists
    if ! dscl . -read "/Users/$username" >/dev/null 2>&1; then
        log_action "❌ User '$username' does not exist"
        return 1
    fi
    
    # Security checks
    if ! perform_security_checks "$username" "$force_clear"; then
        log_action "❌ Security checks failed for user: $username"
        return 1
    fi
    
    # Create backup before making changes
    backup_user_account "$username"
    
    # Clear password using sysadminctl (more secure method)
    log_action "Clearing password for user: $username using sysadminctl"
    if sysadminctl -resetPasswordFor "$username" -newPassword "" -adminUser "$admin_username" -adminPassword "$admin_password" 2>/dev/null; then
        log_action "✅ Password cleared successfully for user: $username"
        audit_log "PASSWORD_CLEARED for user: $username"
        
        # Apply post-clear security measures
        apply_post_clear_security "$username"
        
        # Generate compliance report
        generate_password_compliance_report "$username"
        
        return 0
    else
        log_action "❌ Failed to clear password for user: $username"
        audit_log "PASSWORD_CLEAR_FAILED for user: $username"
        return 1
    fi
}

# Perform security checks before password operations
perform_security_checks() {
    local username="$1"
    local force_clear="$2"
    
    log_action "Performing security checks for user: $username"
    
    # Check if user is admin (extra caution required)
    if dscl . -read "/Groups/admin" GroupMembership 2>/dev/null | grep -q "$username"; then
        if [[ "$force_clear" != "true" ]]; then
            log_action "⚠️  User '$username' is an administrator - use force_clear=true to proceed"
            return 1
        else
            log_action "⚠️  Proceeding with admin user password clear (forced)"
            audit_log "ADMIN_PASSWORD_CLEAR_FORCED for user: $username"
        fi
    fi
    
    # Check FileVault status
    if fdesetup status | grep -q "FileVault is On"; then
        local filevault_users=$(fdesetup list | cut -d',' -f1)
        if echo "$filevault_users" | grep -q "$username"; then
            log_action "⚠️  User '$username' is a FileVault user - password clear may affect disk encryption"
            audit_log "FILEVAULT_USER_PASSWORD_CLEAR for user: $username"
        fi
    fi
    
    # Check if user is currently logged in
    if who | grep -q "$username"; then
        log_action "⚠️  User '$username' is currently logged in"
        audit_log "ACTIVE_USER_PASSWORD_CLEAR for user: $username"
    fi
    
    # Check last login time
    local last_login=$(last "$username" | head -1 | awk '{print $4, $5, $6}')
    log_action "Last login for user '$username': $last_login"
    
    return 0
}

# Apply security measures after password clearing
apply_post_clear_security() {
    local username="$1"
    
    log_action "Applying post-clear security measures for user: $username"
    
    # Set account policy to require password change on next login
    pwpolicy -u "$username" -setpolicy "requiresPasswordReset=1" 2>/dev/null || true
    
    # Log security event
    audit_log "POST_CLEAR_SECURITY_APPLIED for user: $username"
    
    # Optional: Send notification to security team
    if [[ "${ENABLE_SECURITY_NOTIFICATIONS}" == "true" ]]; then
        send_security_notification "$username" "password_cleared"
    fi
}

# Generate password compliance report
generate_password_compliance_report() {
    local username="$1"
    local report_file="/var/log/roundfleet_password_compliance_$(date +%Y%m%d_%H%M%S).json"
    
    # Get user information
    local uid=$(dscl . -read "/Users/$username" UniqueID 2>/dev/null | awk '{print $2}')
    local real_name=$(dscl . -read "/Users/$username" RealName 2>/dev/null | cut -d' ' -f2-)
    local home_dir=$(dscl . -read "/Users/$username" NFSHomeDirectory 2>/dev/null | cut -d' ' -f2-)
    
    # Check admin status
    local is_admin=false
    if dscl . -read "/Groups/admin" GroupMembership 2>/dev/null | grep -q "$username"; then
        is_admin=true
    fi
    
    # Check FileVault status
    local is_filevault_user=false
    if fdesetup status | grep -q "FileVault is On"; then
        if fdesetup list | cut -d',' -f1 | grep -q "$username"; then
            is_filevault_user=true
        fi
    fi
    
    # Generate compliance report
    local compliance_data='{
        "timestamp": "'$(date -u +%Y-%m-%dT%H:%M:%SZ)'",
        "device_id": "'$(system_profiler SPHardwareDataType | grep "Hardware UUID" | awk '{print $3}')'",
        "hostname": "'$(hostname)'",
        "operation": "password_cleared",
        "user_details": {
            "username": "'$username'",
            "uid": "'$uid'",
            "real_name": "'$real_name'",
            "home_directory": "'$home_dir'",
            "is_admin": '$is_admin',
            "is_filevault_user": '$is_filevault_user'
        },
        "security_status": {
            "password_cleared": true,
            "backup_created": true,
            "security_checks_passed": true,
            "post_clear_measures_applied": true
        }
    }'
    
    # Save compliance report
    echo "$compliance_data" | jq . > "$report_file"
    log_action "Password compliance report generated: $report_file"
}

# Bulk password operations for multiple users
bulk_password_operations() {
    local operation="$1"
    local users_file="$2"
    local admin_username="$3"
    local admin_password="$4"
    
    log_action "Starting bulk password operations: $operation"
    
    if [[ ! -f "$users_file" ]]; then
        log_action "❌ Users file not found: $users_file"
        return 1
    fi
    
    local success_count=0
    local failure_count=0
    
    while IFS= read -r username; do
        # Skip empty lines and comments
        [[ -z "$username" || "$username" =~ ^# ]] && continue
        
        log_action "Processing user: $username"
        
        case "$operation" in
            "clear")
                if enterprise_clear_password "$username" "$admin_username" "$admin_password" "false"; then
                    ((success_count++))
                else
                    ((failure_count++))
                fi
                ;;
            "check")
                check_password_status "$username"
                ;;
            *)
                log_action "❌ Unknown operation: $operation"
                return 1
                ;;
        esac
        
        # Small delay between operations
        sleep 1
        
    done < "$users_file"
    
    log_action "Bulk operations completed - Success: $success_count, Failures: $failure_count"
    audit_log "BULK_OPERATION_COMPLETED operation: $operation, success: $success_count, failures: $failure_count"
}

# Password policy enforcement
enforce_password_policies() {
    log_action "Enforcing enterprise password policies"
    
    # Get all users (excluding system users)
    local users=$(dscl . -list /Users | grep -v '^_' | grep -v '^root' | grep -v '^daemon' | grep -v '^nobody')
    
    for username in $users; do
        local uid=$(dscl . -read "/Users/$username" UniqueID 2>/dev/null | awk '{print $2}')
        
        # Skip system users (UID < 500)
        if [[ "$uid" -lt 500 ]]; then
            continue
        fi
        
        log_action "Enforcing password policy for user: $username"
        
        # Apply enterprise password policy
        local min_length="${MIN_PASSWORD_LENGTH:-$DEFAULT_MIN_PASSWORD_LENGTH}"
        local expiry_days="${PASSWORD_EXPIRY_DAYS:-$DEFAULT_PASSWORD_EXPIRY_DAYS}"
        local max_attempts="${MAX_FAILED_ATTEMPTS:-$DEFAULT_MAX_FAILED_ATTEMPTS}"
        
        pwpolicy -u "$username" -setpolicy "minChars=$min_length requiresAlpha requiresNumeric requiresMixedCase requiresSymbol passwordCannotBeName maxMinutesUntilChangePassword=$((expiry_days * 24 * 60)) maxFailedLoginAttempts=$max_attempts" 2>/dev/null || true
        
    done
    
    log_action "Password policy enforcement completed"
}

# Send security notification
send_security_notification() {
    local username="$1"
    local event_type="$2"
    
    # This would integrate with your notification system
    # For now, just log the event
    audit_log "SECURITY_NOTIFICATION sent for user: $username, event: $event_type"
}

# Main password management function
main() {
    local action="${1:-status}"
    local username="${2}"
    local admin_username="${3}"
    local admin_password="${4}"
    
    log_action "=== Roundfleet Password Management Started ==="
    
    case "$action" in
        "clear")
            if [[ -z "$username" || -z "$admin_username" || -z "$admin_password" ]]; then
                echo "Usage: $0 clear <username> <admin_username> <admin_password>"
                exit 1
            fi
            load_password_config
            enterprise_clear_password "$username" "$admin_username" "$admin_password"
            ;;
        "clear-force")
            if [[ -z "$username" || -z "$admin_username" || -z "$admin_password" ]]; then
                echo "Usage: $0 clear-force <username> <admin_username> <admin_password>"
                exit 1
            fi
            load_password_config
            enterprise_clear_password "$username" "$admin_username" "$admin_password" "true"
            ;;
        "check")
            if [[ -z "$username" ]]; then
                echo "Usage: $0 check <username>"
                exit 1
            fi
            check_password_status "$username"
            ;;
        "bulk")
            local operation="$2"
            local users_file="$3"
            shift 3
            admin_username="$1"
            admin_password="$2"
            load_password_config
            bulk_password_operations "$operation" "$users_file" "$admin_username" "$admin_password"
            ;;
        "enforce-policies")
            load_password_config
            enforce_password_policies
            ;;
        "status")
            echo "Roundfleet Password Management System"
            echo "Available commands:"
            echo "  clear <user> <admin_user> <admin_pass>  - Clear user password"
            echo "  clear-force <user> <admin_user> <admin_pass>  - Force clear (admin users)"
            echo "  check <user>                            - Check password status"
            echo "  bulk <operation> <users_file> <admin_user> <admin_pass>  - Bulk operations"
            echo "  enforce-policies                        - Apply password policies"
            echo "  status                                  - Show this help"
            ;;
        *)
            echo "❌ Unknown action: $action"
            echo "Use '$0 status' for available commands"
            exit 1
            ;;
    esac
    
    log_action "=== Roundfleet Password Management Completed ==="
}

# Execute main function
main "$@"

Password Management Configuration

Create a configuration file for enterprise password policies:

#!/bin/bash

# Create password management configuration file
create_password_config() {
    local config_dir="/etc/roundfleet"
    local config_file="$config_dir/password_config.conf"
    
    # Create directory if it doesn't exist
    sudo mkdir -p "$config_dir"
    
    # Create configuration file
    sudo tee "$config_file" > /dev/null << 'EOF'
# Roundfleet Password Management Configuration

# Password policy settings
MIN_PASSWORD_LENGTH=12
PASSWORD_EXPIRY_DAYS=90
MAX_FAILED_ATTEMPTS=5
LOCKOUT_DURATION=30

# Security requirements
REQUIRE_UPPERCASE=true
REQUIRE_LOWERCASE=true
REQUIRE_NUMBERS=true
REQUIRE_SPECIAL_CHARS=true
PREVENT_COMMON_PASSWORDS=true

# Operational settings
ENABLE_AUDIT_LOGGING=true
ENABLE_SECURITY_NOTIFICATIONS=true
ENABLE_AUTOMATIC_BACKUP=true
BACKUP_RETENTION_DAYS=365

# FileVault considerations
WARN_FILEVAULT_USERS=true
REQUIRE_FORCE_FOR_FILEVAULT=true

# Admin user protection
WARN_ADMIN_USERS=true
REQUIRE_FORCE_FOR_ADMIN=true

# Compliance settings
ENABLE_COMPLIANCE_REPORTING=true
COMPLIANCE_REPORT_INTERVAL=7200  # 2 hours
SEND_COMPLIANCE_ALERTS=true
EOF

    echo "Password management configuration created at: $config_file"
    echo "Please review and modify settings according to your security policies"
}

create_password_config

Security Considerations and Best Practices

FileVault Compatibility

#!/bin/bash

# Check FileVault compatibility before password operations
check_filevault_compatibility() {
    local username="$1"
    
    echo "=== FileVault Compatibility Check ==="
    
    # Check if FileVault is enabled
    if fdesetup status | grep -q "FileVault is On"; then
        echo "✅ FileVault is enabled"
        
        # Check if user is a FileVault user
        local filevault_users=$(fdesetup list)
        if echo "$filevault_users" | grep -q "$username"; then
            echo "⚠️  User '$username' is a FileVault user"
            echo "   Clearing password may affect disk encryption access"
            echo "   Consider the following before proceeding:"
            echo "   - Ensure other FileVault users exist"
            echo "   - Have recovery key available"
            echo "   - User may need to re-enable FileVault after password reset"
            return 1
        else
            echo "✅ User '$username' is not a FileVault user"
            return 0
        fi
    else
        echo "ℹ️  FileVault is not enabled"
        return 0
    fi
}

check_filevault_compatibility

Audit and Compliance

#!/bin/bash

# Generate comprehensive audit report
generate_audit_report() {
    local report_file="/var/log/roundfleet_password_audit_$(date +%Y%m%d_%H%M%S).txt"
    
    {
        echo "Roundfleet Password Management Audit Report"
        echo "Generated: $(date)"
        echo "Device: $(hostname)"
        echo "====================================="
        echo ""
        
        echo "System Users (UID >= 500):"
        dscl . -list /Users | while read username; do
            local uid=$(dscl . -read "/Users/$username" UniqueID 2>/dev/null | awk '{print $2}')
            if [[ "$uid" -ge 500 ]]; then
                local real_name=$(dscl . -read "/Users/$username" RealName 2>/dev/null | cut -d' ' -f2-)
                local is_admin=""
                if dscl . -read "/Groups/admin" GroupMembership 2>/dev/null | grep -q "$username"; then
                    is_admin=" (Admin)"
                fi
                echo "- $username (UID: $uid)$is_admin - $real_name"
            fi
        done
        echo ""
        
        echo "FileVault Status:"
        fdesetup status
        if fdesetup status | grep -q "FileVault is On"; then
            echo "FileVault Users:"
            fdesetup list
        fi
        echo ""
        
        echo "Recent Password Management Activities:"
        if [[ -f "$AUDIT_FILE" ]]; then
            tail -20 "$AUDIT_FILE"
        else
            echo "No audit log found"
        fi
        
    } > "$report_file"
    
    echo "Audit report generated: $report_file"
}

generate_audit_report

Integration with Roundfleet Management

#!/bin/bash

# Roundfleet password management integration
roundfleet_password_integration() {
    echo "=== Roundfleet Password Management Integration ==="
    
    # Device information
    local device_id=$(system_profiler SPHardwareDataType | grep "Hardware UUID" | awk '{print $3}')
    local hostname=$(hostname)
    local macos_version=$(sw_vers -productVersion)
    
    # Get user account statistics
    local total_users=$(dscl . -list /Users | grep -v '^_' | grep -v '^root' | grep -v '^daemon' | grep -v '^nobody' | wc -l)
    local admin_users=$(dscl . -read "/Groups/admin" GroupMembership 2>/dev/null | wc -w)
    
    # FileVault status
    local filevault_enabled=false
    local filevault_users=0
    if fdesetup status | grep -q "FileVault is On"; then
        filevault_enabled=true
        filevault_users=$(fdesetup list | wc -l)
    fi
    
    # Recent password management activities
    local recent_activities=0
    if [[ -f "$AUDIT_FILE" ]]; then
        recent_activities=$(grep "$(date +%Y-%m-%d)" "$AUDIT_FILE" | wc -l)
    fi
    
    # Report to Roundfleet API
    local api_data='{
        "device_id": "'$device_id'",
        "hostname": "'$hostname'",
        "timestamp": "'$(date -u +%Y-%m-%dT%H:%M:%SZ)'",
        "macos_version": "'$macos_version'",
        "password_management": {
            "total_users": '$total_users',
            "admin_users": '$admin_users',
            "filevault_enabled": '$filevault_enabled',
            "filevault_users": '$filevault_users',
            "recent_activities": '$recent_activities'
        },
        "password_management_status": "active"
    }'
    
    echo "Password management status reported to Roundfleet management system"
    echo "Device ID: $device_id"
    echo "Total Users: $total_users"
    echo "Admin Users: $admin_users"
    echo "FileVault Enabled: $filevault_enabled"
    echo "Recent Activities: $recent_activities"
}

roundfleet_password_integration

Important Security Notes

Security Warnings

  • Password clearing creates security risks - only use when necessary
  • FileVault users require special consideration - may affect disk encryption
  • Admin users need extra caution - can compromise system security
  • Always create backups before making password changes

Best Practices

  • Use sysadminctl over dscl for better security and audit trails
  • Implement strong password policies after clearing passwords
  • Monitor and audit all password operations
  • Test on pilot devices before fleet-wide deployment

Compliance Considerations

  • Document all password operations for security audits
  • Maintain backup and recovery procedures
  • Regular security assessments of user accounts
  • Integration with enterprise identity systems for centralized management

Password Enforcement on macOS

Enforce enterprise-grade password policies and security standards across your Roundfleet devices using comprehensive command-line tools and security frameworks. This tutorial covers password policy implementation, compliance monitoring, and automated enforcement systems.

Understanding macOS Password Security

macOS provides multiple layers of password security:

  • Password Policies - Complexity, length, and rotation requirements
  • Screen Lock Security - Automatic locking and unlock requirements
  • Secure Token Management - FileVault and encryption support
  • Account Security - User privilege and access controls

Password Policy Configuration

Basic Password Requirements

#!/bin/bash

# Set basic password policy using pwpolicy
configure_password_policy() {
    # Configure password complexity requirements
    sudo pwpolicy -a diradmin -u $USER -setpolicy "minChars=8 requiresAlpha requiresNumeric"
    
    # Set password history (prevent reuse of last 5 passwords)
    sudo pwpolicy -a diradmin -u $USER -setpolicy "usingHistory=5"
    
    # Set password expiration (90 days)
    sudo pwpolicy -a diradmin -u $USER -setpolicy "maxMinutesUntilChangePassword=129600"
    
    echo "Basic password policy configured successfully"
}

configure_password_policy

Advanced Security Settings

#!/bin/bash

# Configure advanced password and security settings
configure_advanced_security() {
    echo "=== Advanced Security Configuration ==="
    
    # Enable password requirement for wake from sleep
    osascript -e 'tell application "System Events" to set require password to wake of security preferences to true'
    
    # Set immediate password requirement
    defaults write com.apple.screensaver askForPassword -int 1
    defaults write com.apple.screensaver askForPasswordDelay -int 0
    
    # Configure account lockout policy
    sudo pwpolicy -a diradmin -setpolicy "maxFailedLoginAttempts=5"
    
    # Enable automatic logout after inactivity
    sudo defaults write /Library/Preferences/.GlobalPreferences com.apple.autologout.AutoLogOutDelay -int 3600
    
    echo "Advanced security settings configured"
}

configure_advanced_security

Screen Lock Enforcement

Automatic Screen Lock

#!/bin/bash

# Configure automatic screen lock settings
configure_screen_lock() {
    local lock_delay="${1:-300}" # Default 5 minutes
    
    echo "Configuring screen lock with ${lock_delay} second delay"
    
    # Set screen saver activation time
    defaults -currentHost write com.apple.screensaver idleTime -int "$lock_delay"
    
    # Enable password requirement for screen saver
    defaults write com.apple.screensaver askForPassword -int 1
    defaults write com.apple.screensaver askForPasswordDelay -int 0
    
    # Configure energy saver settings
    sudo pmset -a displaysleep 5    # Display sleep after 5 minutes
    sudo pmset -a sleep 30          # System sleep after 30 minutes
    
    # Kill screen saver preferences to apply changes
    killall ScreenSaverEngine 2>/dev/null || true
    
    echo "Screen lock configured successfully"
}

# Usage: configure_screen_lock [delay_in_seconds]
configure_screen_lock 300

Immediate Lock Enforcement

#!/bin/bash

# Force immediate screen lock
force_screen_lock() {
    echo "Forcing immediate screen lock..."
    
    # Multiple methods to ensure lock
    /System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend
    
    # Alternative method using pmset
    pmset displaysleepnow
    
    # Activate screen saver as backup
    /System/Library/Frameworks/ScreenSaver.framework/Resources/ScreenSaverEngine.app/Contents/MacOS/ScreenSaverEngine -background &
    
    echo "Screen locked successfully"
}

force_screen_lock

Password Complexity Enforcement

Complex Password Validation

#!/bin/bash

# Validate password complexity
validate_password_complexity() {
    local password="$1"
    local min_length=8
    local errors=0
    
    echo "=== Password Complexity Validation ==="
    
    # Check minimum length
    if [[ ${#password} -lt $min_length ]]; then
        echo "❌ Password must be at least $min_length characters"
        ((errors++))
    else
        echo "✅ Length requirement met"
    fi
    
    # Check for uppercase letter
    if [[ ! "$password" =~ [A-Z] ]]; then
        echo "❌ Password must contain at least one uppercase letter"
        ((errors++))
    else
        echo "✅ Uppercase letter found"
    fi
    
    # Check for lowercase letter
    if [[ ! "$password" =~ [a-z] ]]; then
        echo "❌ Password must contain at least one lowercase letter"
        ((errors++))
    else
        echo "✅ Lowercase letter found"
    fi
    
    # Check for number
    if [[ ! "$password" =~ [0-9] ]]; then
        echo "❌ Password must contain at least one number"
        ((errors++))
    else
        echo "✅ Number found"
    fi
    
    # Check for special character
    if [[ ! "$password" =~ [^a-zA-Z0-9] ]]; then
        echo "❌ Password must contain at least one special character"
        ((errors++))
    else
        echo "✅ Special character found"
    fi
    
    # Check for common patterns
    if [[ "$password" =~ (123|abc|password|qwerty) ]]; then
        echo "❌ Password contains common patterns"
        ((errors++))
    else
        echo "✅ No common patterns detected"
    fi
    
    if [[ $errors -eq 0 ]]; then
        echo "✅ Password meets all complexity requirements"
        return 0
    else
        echo "❌ Password failed $errors complexity checks"
        return 1
    fi
}

# Example usage (do not use in production with actual passwords)
# validate_password_complexity "TestPassword123!"

Password Generation

#!/bin/bash

# Generate secure passwords
generate_secure_password() {
    local length="${1:-12}"
    local include_symbols="${2:-true}"
    
    echo "=== Secure Password Generation ==="
    
    if [[ "$include_symbols" == "true" ]]; then
        # Generate password with symbols
        local charset='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*'
    else
        # Generate alphanumeric password
        local charset='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
    fi
    
    # Generate random password
    local password=$(openssl rand -base64 32 | tr -d "=+/" | cut -c1-${length})
    
    # Ensure complexity requirements
    password="${password:0:$((length-4))}A1@z"
    
    echo "Generated password length: ${#password}"
    echo "Password complexity verified"
    
    # Validate the generated password
    if validate_password_complexity "$password"; then
        echo "✅ Generated password meets all requirements"
    fi
}

generate_secure_password 12 true

User Account Management

Password Reset and Management

#!/bin/bash

# User account password management
manage_user_passwords() {
    local username="$1"
    local action="$2"
    
    echo "=== User Password Management ==="
    echo "Managing password for user: $username"
    
    case "$action" in
        "reset")
            # Force password reset on next login
            sudo pwpolicy -a diradmin -u "$username" -setpolicy "newPasswordRequired=1"
            echo "Password reset required for $username on next login"
            ;;
        "expire")
            # Expire password immediately
            sudo pwpolicy -a diradmin -u "$username" -setpolicy "passwordLastSetTime=0"
            echo "Password expired for $username"
            ;;
        "unlock")
            # Unlock account after failed attempts
            sudo pwpolicy -a diradmin -u "$username" -clearfailedlogins
            echo "Account unlocked for $username"
            ;;
        "status")
            # Check password status
            sudo pwpolicy -a diradmin -u "$username" -getpolicy
            ;;
        *)
            echo "Usage: manage_user_passwords <username> <reset|expire|unlock|status>"
            return 1
            ;;
    esac
}

# Example usage
# manage_user_passwords "johndoe" "status"

Secure Token Management

#!/bin/bash

# Add secure token to user account
add_secure_token() {
    local admin_user="$1"
    local admin_password="$2"
    local target_user="$3"
    local target_password="$4"
    
    echo "=== Secure Token Management ==="
    
    # Check macOS version compatibility
    local macos_version=$(sw_vers -productVersion)
    echo "macOS Version: $macos_version"
    
    # Check if target user already has secure token
    if sysadminctl -secureTokenStatus "$target_user" 2>&1 | grep -q "ENABLED"; then
        echo "✅ $target_user already has SecureToken"
        return 0
    fi
    
    # Check if admin user has secure token
    if sysadminctl -secureTokenStatus "$admin_user" 2>&1 | grep -q "DISABLED"; then
        echo "❌ Admin user $admin_user does not have SecureToken"
        return 1
    fi
    
    echo "Adding SecureToken to $target_user..."
    
    # Add secure token
    if sysadminctl -adminUser "$admin_user" \
                   -adminPassword "$admin_password" \
                   -secureTokenOn "$target_user" \
                   -password "$target_password"; then
        echo "✅ SecureToken added successfully to $target_user"
    else
        echo "❌ Failed to add SecureToken to $target_user"
        return 1
    fi
}

# Example usage (replace with actual credentials in secure environment)
# add_secure_token "admin" "admin_pass" "user" "user_pass"

Enterprise Password Management System

#!/bin/bash

# Roundfleet Enterprise Password Management System
# Comprehensive password policy enforcement and monitoring

# Configuration
LOG_FILE="/var/log/roundfleet_password_security.log"
POLICY_CONFIG="/etc/roundfleet/password_policy.conf"
COMPLIANCE_REPORT="/var/log/roundfleet_password_compliance.json"

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

# Load password policy configuration
load_policy_config() {
    if [[ -f "$POLICY_CONFIG" ]]; then
        source "$POLICY_CONFIG"
    else
        # Default values
        MIN_PASSWORD_LENGTH=8
        MAX_PASSWORD_AGE=90
        PASSWORD_HISTORY=5
        MAX_FAILED_ATTEMPTS=5
        LOCK_TIMEOUT=300
        COMPLEXITY_REQUIRED=true
    fi
}

# Check password compliance for all users
check_password_compliance() {
    log_action "Starting password compliance check"
    
    local compliance_data='{"timestamp":"'$(date -u +%Y-%m-%dT%H:%M:%SZ)'","users":[]}'
    local non_compliant_count=0
    
    # Get all local users
    local users=$(dscl . list /Users | grep -v '^_' | grep -v 'daemon\|nobody\|root')
    
    while IFS= read -r username; do
        if [[ -n "$username" ]]; then
            log_action "Checking compliance for user: $username"
            
            local user_data='{"username":"'$username'","compliant":true,"issues":[]}'
            local issues=()
            
            # Check password age
            local last_change=$(dscl . read "/Users/$username" passwordPolicyOptions | grep -o 'passwordLastSetTime</key><real>[0-9.]*' | cut -d'>' -f2 || echo "0")
            if [[ -n "$last_change" && "$last_change" != "0" ]]; then
                local age_days=$(( ($(date +%s) - ${last_change%.*}) / 86400 ))
                if [[ $age_days -gt $MAX_PASSWORD_AGE ]]; then
                    issues+=("Password expired ($age_days days old)")
                fi
            fi
            
            # Check account lockout status
            local failed_attempts=$(dscl . read "/Users/$username" | grep -c "authenticationHint" || echo "0")
            
            # Check secure token status
            if ! sysadminctl -secureTokenStatus "$username" 2>&1 | grep -q "ENABLED"; then
                issues+=("No SecureToken")
            fi
            
            # Update compliance data
            if [[ ${#issues[@]} -gt 0 ]]; then
                user_data='{"username":"'$username'","compliant":false,"issues":["'$(IFS='","'; echo "${issues[*]}")'"]}' 
                ((non_compliant_count++))
            fi
            
            # Add to compliance report
            compliance_data=$(echo "$compliance_data" | jq --argjson user "$user_data" '.users += [$user]')
        fi
    done <<< "$users"
    
    # Save compliance report
    echo "$compliance_data" | jq . > "$COMPLIANCE_REPORT"
    
    log_action "Compliance check completed: $non_compliant_count non-compliant users found"
    
    if [[ $non_compliant_count -gt 0 ]]; then
        log_action "⚠️ Password compliance issues detected"
        return 1
    else
        log_action "✅ All users are password compliant"
        return 0
    fi
}

# Enforce password policies
enforce_password_policies() {
    log_action "Starting password policy enforcement"
    
    # Configure system-wide password policies
    log_action "Applying system-wide password policies"
    
    # Set password complexity requirements
    if [[ "$COMPLEXITY_REQUIRED" == "true" ]]; then
        sudo pwpolicy -a diradmin -setglobalpolicy "minChars=$MIN_PASSWORD_LENGTH requiresAlpha requiresNumeric"
        log_action "Password complexity requirements set"
    fi
    
    # Configure account lockout
    sudo pwpolicy -a diradmin -setglobalpolicy "maxFailedLoginAttempts=$MAX_FAILED_ATTEMPTS"
    log_action "Account lockout policy set to $MAX_FAILED_ATTEMPTS failed attempts"
    
    # Configure password history
    sudo pwpolicy -a diradmin -setglobalpolicy "usingHistory=$PASSWORD_HISTORY"
    log_action "Password history set to $PASSWORD_HISTORY previous passwords"
    
    # Configure screen lock
    defaults write com.apple.screensaver askForPassword -int 1
    defaults write com.apple.screensaver askForPasswordDelay -int 0
    log_action "Screen lock password requirement enabled"
    
    # Set automatic screen lock
    defaults -currentHost write com.apple.screensaver idleTime -int "$LOCK_TIMEOUT"
    log_action "Automatic screen lock set to $LOCK_TIMEOUT seconds"
}

# Generate password compliance report
generate_compliance_report() {
    log_action "Generating password compliance report"
    
    if [[ -f "$COMPLIANCE_REPORT" ]]; then
        local total_users=$(jq '.users | length' "$COMPLIANCE_REPORT")
        local compliant_users=$(jq '.users | map(select(.compliant == true)) | length' "$COMPLIANCE_REPORT")
        local non_compliant_users=$(jq '.users | map(select(.compliant == false)) | length' "$COMPLIANCE_REPORT")
        
        echo "=== Password Compliance Report ==="
        echo "Report Generated: $(jq -r '.timestamp' "$COMPLIANCE_REPORT")"
        echo "Total Users: $total_users"
        echo "Compliant Users: $compliant_users"
        echo "Non-Compliant Users: $non_compliant_users"
        echo "Compliance Rate: $(( (compliant_users * 100) / total_users ))%"
        
        if [[ $non_compliant_users -gt 0 ]]; then
            echo ""
            echo "Non-Compliant Users:"
            jq -r '.users[] | select(.compliant == false) | "- " + .username + ": " + (.issues | join(", "))' "$COMPLIANCE_REPORT"
        fi
    else
        echo "No compliance report found. Run compliance check first."
    fi
}

# Automated password security tasks
run_security_maintenance() {
    log_action "=== Starting automated password security maintenance ==="
    
    # Load configuration
    load_policy_config
    
    # Check compliance
    check_password_compliance
    
    # Enforce policies
    enforce_password_policies
    
    # Generate report
    generate_compliance_report
    
    log_action "=== Password security maintenance completed ==="
}

# Main execution
main() {
    local action="${1:-maintenance}"
    
    case "$action" in
        "compliance")
            load_policy_config
            check_password_compliance
            ;;
        "enforce")
            load_policy_config
            enforce_password_policies
            ;;
        "report")
            generate_compliance_report
            ;;
        "maintenance")
            run_security_maintenance
            ;;
        *)
            echo "Usage: $0 [compliance|enforce|report|maintenance]"
            echo "  compliance - Check password compliance for all users"
            echo "  enforce    - Apply password policies"
            echo "  report     - Generate compliance report"
            echo "  maintenance - Run full maintenance cycle (default)"
            exit 1
            ;;
    esac
}

# Execute main function
main "$@"

Password Policy Configuration File

Create a configuration file for password policies:

#!/bin/bash

# Create password policy configuration
create_policy_config() {
    local config_dir="/etc/roundfleet"
    local config_file="$config_dir/password_policy.conf"
    
    # Create directory if it doesn't exist
    sudo mkdir -p "$config_dir"
    
    # Create configuration file
    sudo tee "$config_file" > /dev/null << 'EOF'
# Roundfleet Password Policy Configuration

# Password Requirements
MIN_PASSWORD_LENGTH=8
MAX_PASSWORD_LENGTH=128
REQUIRE_UPPERCASE=true
REQUIRE_LOWERCASE=true
REQUIRE_NUMBERS=true
REQUIRE_SPECIAL_CHARS=true

# Password Rotation
MAX_PASSWORD_AGE=90          # Days before password expires
PASSWORD_HISTORY=5           # Number of previous passwords to remember
EXPIRATION_WARNING_DAYS=14   # Days before expiration to warn user

# Account Security
MAX_FAILED_ATTEMPTS=5        # Failed login attempts before lockout
LOCKOUT_DURATION=1800        # Account lockout duration in seconds
AUTO_UNLOCK=true             # Automatically unlock after lockout duration

# Screen Security
LOCK_TIMEOUT=300             # Screen lock timeout in seconds
IMMEDIATE_LOCK=true          # Require password immediately after lock
SCREEN_SAVER_TIMEOUT=600     # Screen saver activation timeout

# Compliance
COMPLEXITY_REQUIRED=true     # Enforce password complexity
SECURE_TOKEN_REQUIRED=true   # Require SecureToken for all users
REGULAR_AUDITS=true          # Enable regular compliance audits
AUDIT_FREQUENCY=7            # Days between compliance audits

# Logging
ENABLE_LOGGING=true          # Enable security event logging
LOG_LEVEL="INFO"             # Log level: DEBUG, INFO, WARN, ERROR
LOG_RETENTION=30             # Days to retain log files
EOF

    echo "Password policy configuration created at: $config_file"
}

create_policy_config

Integration with Roundfleet Management

#!/bin/bash

# Roundfleet password management integration
roundfleet_password_integration() {
    echo "=== Roundfleet Password Management Integration ==="
    
    # Device registration
    local device_id=$(system_profiler SPHardwareDataType | grep "Hardware UUID" | awk '{print $3}')
    local hostname=$(hostname)
    
    echo "Device ID: $device_id"
    echo "Hostname: $hostname"
    
    # Report to Roundfleet API (placeholder)
    local api_endpoint="https://api.roundfleet.com/devices/$device_id/security"
    local report_data='{
        "device_id": "'$device_id'",
        "hostname": "'$hostname'",
        "timestamp": "'$(date -u +%Y-%m-%dT%H:%M:%SZ)'",
        "password_policy_status": "enforced",
        "compliance_check": "'$(date +%s)'",
        "security_level": "enterprise"
    }'
    
    echo "Security status reported to Roundfleet"
}

roundfleet_password_integration

Important Security Notes

Password Storage and Handling

  • Never log actual passwords in scripts or logs
  • Use secure credential management for administrative passwords
  • Implement proper encryption for any stored authentication data
  • Regular security audits of password policies and compliance

Best Practices

  • Test policies on development devices before fleet deployment
  • Gradual rollout of new password requirements
  • User communication about policy changes
  • Emergency procedures for account lockouts and password resets

Monitoring and Compliance

  • Regular audits of password compliance across the fleet
  • Automated alerts for policy violations
  • Reporting dashboard for security status
  • Integration with enterprise identity management systems

This enterprise password enforcement system provides comprehensive security management for Roundfleet devices while maintaining usability and compliance with enterprise security standards.

Password Change Management on macOS

Securely manage password change operations across your Roundfleet deployment with enterprise-grade security controls, policy enforcement, and comprehensive audit capabilities. This tutorial transforms the basic dscl command into a robust password management solution suitable for enterprise environments.

Understanding Enterprise Password Management

Enterprise password change operations require robust security measures beyond basic directory service commands:

  • Password policy enforcement to ensure security standards
  • Secure credential handling to prevent exposure
  • Comprehensive audit logging for compliance tracking
  • Multi-factor authentication integration for enhanced security
  • Privilege validation to ensure proper authorization
  • Keychain synchronization for seamless user experience

Core Password Change Operation

Basic Password Change Command

# Basic password change using dscl
sudo dscl . -passwd /Users/username currentpassword newpassword

This utilizes the directory service command-line utility (dscl) to modify user directory data, specifically the password field.

Enterprise Password Change Management System

#!/bin/bash

# Roundfleet Enterprise Password Change Management System
# Secure password change operations with comprehensive enterprise controls

# Configuration
SCRIPT_NAME="Roundfleet Password Change Manager"
VERSION="1.0.0"
LOG_FILE="/var/log/roundfleet_password_operations.log"
AUDIT_LOG="/var/log/roundfleet_password_audit.log"
POLICY_FILE="/etc/roundfleet/password_policy.conf"
TEMP_DIR="/tmp/roundfleet_password"
SECURE_LOG_RETENTION_DAYS=365
MAX_LOGIN_ATTEMPTS=3
PASSWORD_HISTORY_COUNT=12
LOCKOUT_DURATION=1800  # 30 minutes
MIN_PASSWORD_LENGTH=12
MAX_PASSWORD_LENGTH=128
COMPLEXITY_REQUIREMENTS=true
BUSINESS_HOURS_START=9
BUSINESS_HOURS_END=17
EMERGENCY_CONTACTS=("[email protected]" "[email protected]")

# Password complexity requirements
REQUIRE_UPPERCASE=true
REQUIRE_LOWERCASE=true
REQUIRE_NUMBERS=true
REQUIRE_SPECIAL_CHARS=true
FORBIDDEN_PATTERNS=("password" "123456" "qwerty" "admin" "root")

# Create necessary directories
mkdir -p "$TEMP_DIR"
mkdir -p "$(dirname "$LOG_FILE")"
mkdir -p "$(dirname "$AUDIT_LOG")"
mkdir -p "$(dirname "$POLICY_FILE")"

# Set secure permissions
chmod 700 "$TEMP_DIR"
touch "$LOG_FILE" && chmod 640 "$LOG_FILE"
touch "$AUDIT_LOG" && chmod 600 "$AUDIT_LOG"

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

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

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

# Check if user exists
user_exists() {
    local username="$1"
    dscl . -read "/Users/$username" &>/dev/null
    return $?
}

# Check if user is system account
is_system_account() {
    local username="$1"
    local uid=$(dscl . -read "/Users/$username" UniqueID 2>/dev/null | awk '{print $2}')
    
    # System accounts typically have UID < 500
    if [[ -n "$uid" && $uid -lt 500 ]]; then
        return 0
    fi
    
    # Check for common system accounts
    local system_accounts=("root" "daemon" "nobody" "_www" "_mysql" "_postgres")
    for sys_account in "${system_accounts[@]}"; do
        if [[ "$username" == "$sys_account" ]]; then
            return 0
        fi
    done
    
    return 1
}

# Validate current user has permission to change password
validate_permission() {
    local target_username="$1"
    local current_user=$(whoami)
    
    # Root can change any password
    if [[ "$current_user" == "root" ]]; then
        return 0
    fi
    
    # Users can change their own password
    if [[ "$current_user" == "$target_username" ]]; then
        return 0
    fi
    
    # Check if current user is admin
    if dseditgroup -o checkmember -m "$current_user" admin &>/dev/null; then
        return 0
    fi
    
    log_security_event "PERMISSION_DENIED" "$target_username" "User $current_user attempted unauthorized password change"
    return 1
}

# Generate secure random password
generate_secure_password() {
    local length="${1:-16}"
    local password=""
    local attempts=0
    local max_attempts=10
    
    while [[ $attempts -lt $max_attempts ]]; do
        # Generate password with mixed character set
        password=$(openssl rand -base64 32 | tr -d "=+/" | cut -c1-"$length")
        
        # Add special characters
        password="${password}$(openssl rand -base64 4 | tr -d "=+/" | tr 'A-Za-z0-9' '@#$%&*' | cut -c1-2)"
        
        # Validate password meets requirements
        if validate_password_complexity "$password"; then
            echo "$password"
            return 0
        fi
        
        ((attempts++))
    done
    
    log_operation "ERROR" "Failed to generate secure password after $max_attempts attempts"
    return 1
}

# Validate password complexity
validate_password_complexity() {
    local password="$1"
    local length=${#password}
    
    # Check length requirements
    if [[ $length -lt $MIN_PASSWORD_LENGTH ]]; then
        log_operation "WARNING" "Password too short: $length < $MIN_PASSWORD_LENGTH"
        return 1
    fi
    
    if [[ $length -gt $MAX_PASSWORD_LENGTH ]]; then
        log_operation "WARNING" "Password too long: $length > $MAX_PASSWORD_LENGTH"
        return 1
    fi
    
    if [[ "$COMPLEXITY_REQUIREMENTS" == "true" ]]; then
        # Check for uppercase letters
        if [[ "$REQUIRE_UPPERCASE" == "true" ]] && ! [[ "$password" =~ [A-Z] ]]; then
            log_operation "WARNING" "Password missing uppercase letters"
            return 1
        fi
        
        # Check for lowercase letters
        if [[ "$REQUIRE_LOWERCASE" == "true" ]] && ! [[ "$password" =~ [a-z] ]]; then
            log_operation "WARNING" "Password missing lowercase letters"
            return 1
        fi
        
        # Check for numbers
        if [[ "$REQUIRE_NUMBERS" == "true" ]] && ! [[ "$password" =~ [0-9] ]]; then
            log_operation "WARNING" "Password missing numbers"
            return 1
        fi
        
        # Check for special characters
        if [[ "$REQUIRE_SPECIAL_CHARS" == "true" ]] && ! [[ "$password" =~ [^a-zA-Z0-9] ]]; then
            log_operation "WARNING" "Password missing special characters"
            return 1
        fi
    fi
    
    # Check for forbidden patterns
    local password_lower=$(echo "$password" | tr '[:upper:]' '[:lower:]')
    for pattern in "${FORBIDDEN_PATTERNS[@]}"; do
        if [[ "$password_lower" == *"$pattern"* ]]; then
            log_operation "WARNING" "Password contains forbidden pattern: $pattern"
            return 1
        fi
    done
    
    return 0
}

# Check password history
check_password_history() {
    local username="$1"
    local new_password="$2"
    local history_file="/var/db/roundfleet/password_history/$username"
    
    if [[ ! -f "$history_file" ]]; then
        return 0  # No history, password is acceptable
    fi
    
    # Hash new password for comparison
    local new_hash=$(echo -n "$new_password" | shasum -a 256 | cut -d' ' -f1)
    
    # Check against stored hashes
    if grep -q "$new_hash" "$history_file"; then
        log_operation "WARNING" "Password reuse detected for user $username"
        return 1
    fi
    
    return 0
}

# Store password in history
store_password_history() {
    local username="$1"
    local password="$2"
    local history_dir="/var/db/roundfleet/password_history"
    local history_file="$history_dir/$username"
    
    # Create directory if it doesn't exist
    mkdir -p "$history_dir"
    chmod 700 "$history_dir"
    
    # Hash password
    local password_hash=$(echo -n "$password" | shasum -a 256 | cut -d' ' -f1)
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    
    # Add to history
    echo "$timestamp:$password_hash" >> "$history_file"
    chmod 600 "$history_file"
    
    # Maintain history count
    if [[ $(wc -l < "$history_file") -gt $PASSWORD_HISTORY_COUNT ]]; then
        tail -n "$PASSWORD_HISTORY_COUNT" "$history_file" > "$history_file.tmp"
        mv "$history_file.tmp" "$history_file"
    fi
}

# Verify current password
verify_current_password() {
    local username="$1"
    local current_password="$2"
    
    # Use dscl to verify password
    if dscl . -authonly "$username" "$current_password" &>/dev/null; then
        return 0
    else
        log_security_event "AUTH_FAILURE" "$username" "Current password verification failed"
        return 1
    fi
}

# Update keychain password
update_keychain_password() {
    local username="$1"
    local old_password="$2"
    local new_password="$3"
    
    log_operation "INFO" "Updating keychain password for user $username"
    
    # Get user's home directory
    local home_dir=$(dscl . -read "/Users/$username" NFSHomeDirectory | awk '{print $2}')
    local keychain_path="$home_dir/Library/Keychains/login.keychain-db"
    
    if [[ -f "$keychain_path" ]]; then
        # Update keychain password
        if su "$username" -c "security unlock-keychain -p '$old_password' '$keychain_path' && security set-keychain-password -o '$old_password' -p '$new_password' '$keychain_path'" &>/dev/null; then
            log_operation "SUCCESS" "Keychain password updated for user $username"
            return 0
        else
            log_operation "WARNING" "Failed to update keychain password for user $username"
            return 1
        fi
    else
        log_operation "INFO" "No keychain found for user $username"
        return 0
    fi
}

# Force password change on next login
force_password_change_on_login() {
    local username="$1"
    
    # Set password change required flag
    if dscl . -create "/Users/$username" accountPolicyData '<dict><key>isDisabled</key><false/><key>isAdminUser</key><false/><key>newPasswordRequired</key><true/></dict>'; then
        log_operation "SUCCESS" "Password change on next login set for user $username"
        return 0
    else
        log_operation "ERROR" "Failed to set password change requirement for user $username"
        return 1
    fi
}

# Send notification to security team
send_security_notification() {
    local event_type="$1"
    local username="$2"
    local details="$3"
    
    local subject="Roundfleet Security Alert: $event_type"
    local message="Security Event Details:
Event: $event_type
User: $username
Time: $(date)
Host: $(hostname)
Details: $details

This is an automated security notification from Roundfleet Password Management System."
    
    for email in "${EMERGENCY_CONTACTS[@]}"; do
        echo "$message" | mail -s "$subject" "$email" 2>/dev/null || true
    done
}

# Enterprise password change function
enterprise_change_password() {
    local username="$1"
    local current_password="$2"
    local new_password="$3"
    local force_change="${4:-false}"
    local bypass_history="${5:-false}"
    
    local operation_id=$(date +%s)
    log_operation "INFO" "Starting password change operation [$operation_id] for user: $username"
    
    # Validate user exists
    if ! user_exists "$username"; then
        log_operation "ERROR" "User does not exist: $username"
        log_security_event "USER_NOT_FOUND" "$username" "Password change attempted for non-existent user"
        return 1
    fi
    
    # Check if system account
    if is_system_account "$username"; then
        log_operation "ERROR" "Cannot change password for system account: $username"
        log_security_event "SYSTEM_ACCOUNT_ACCESS" "$username" "Attempted password change on system account"
        send_security_notification "SYSTEM_ACCOUNT_ACCESS" "$username" "Attempted password change on system account"
        return 1
    fi
    
    # Validate permissions
    if ! validate_permission "$username"; then
        log_operation "ERROR" "Permission denied for password change: $username"
        return 1
    fi
    
    # Verify current password (unless forced)
    if [[ "$force_change" != "true" ]]; then
        if ! verify_current_password "$username" "$current_password"; then
            log_operation "ERROR" "Current password verification failed for user: $username"
            return 1
        fi
    fi
    
    # Validate new password complexity
    if ! validate_password_complexity "$new_password"; then
        log_operation "ERROR" "New password does not meet complexity requirements for user: $username"
        return 1
    fi
    
    # Check password history (unless bypassed)
    if [[ "$bypass_history" != "true" ]]; then
        if ! check_password_history "$username" "$new_password"; then
            log_operation "ERROR" "Password reuse detected for user: $username"
            return 1
        fi
    fi
    
    # Create secure temporary files
    local temp_script="$TEMP_DIR/change_password_${operation_id}.sh"
    local temp_log="$TEMP_DIR/change_password_${operation_id}.log"
    
    # Change password using dscl
    log_operation "INFO" "Executing password change for user: $username"
    
    if [[ "$force_change" == "true" ]]; then
        # Force change without current password
        if dscl . -passwd "/Users/$username" "$new_password" 2>"$temp_log"; then
            local result=0
        else
            local result=1
        fi
    else
        # Normal change with current password verification
        if dscl . -passwd "/Users/$username" "$current_password" "$new_password" 2>"$temp_log"; then
            local result=0
        else
            local result=1
        fi
    fi
    
    # Check result
    if [[ $result -eq 0 ]]; then
        log_operation "SUCCESS" "Password changed successfully [$operation_id] for user: $username"
        log_security_event "PASSWORD_CHANGED" "$username" "Password changed successfully"
        
        # Store in password history
        store_password_history "$username" "$new_password"
        
        # Update keychain if not forced change
        if [[ "$force_change" != "true" ]]; then
            update_keychain_password "$username" "$current_password" "$new_password"
        fi
        
        # Clear temporary files securely
        shred -vfz -n 3 "$temp_script" "$temp_log" 2>/dev/null || {
            rm -f "$temp_script" "$temp_log"
        }
        
        return 0
    else
        log_operation "ERROR" "Password change failed [$operation_id] for user: $username"
        log_security_event "PASSWORD_CHANGE_FAILED" "$username" "Password change operation failed"
        
        # Log error details
        if [[ -f "$temp_log" ]]; then
            local error_msg=$(cat "$temp_log")
            log_operation "ERROR" "dscl error: $error_msg"
        fi
        
        # Clear temporary files securely
        shred -vfz -n 3 "$temp_script" "$temp_log" 2>/dev/null || {
            rm -f "$temp_script" "$temp_log"
        }
        
        return 1
    fi
}

# Bulk password change operation
bulk_password_change() {
    local users_file="$1"
    local password_source="${2:-generate}"  # "generate" or "file"
    local password_file="$3"
    
    if [[ ! -f "$users_file" ]]; then
        log_operation "ERROR" "Users file not found: $users_file"
        return 1
    fi
    
    local total_users=$(grep -v '^#\|^$' "$users_file" | wc -l)
    local current_user=0
    local success_count=0
    local failure_count=0
    
    log_operation "INFO" "Starting bulk password change operation - Total users: $total_users"
    
    while IFS='|' read -r username current_password force_change; do
        # Skip empty lines and comments
        [[ -z "$username" || "$username" =~ ^#.* ]] && continue
        
        ((current_user++))
        
        # Trim whitespace
        username=$(echo "$username" | xargs)
        current_password=$(echo "$current_password" | xargs)
        force_change=$(echo "$force_change" | xargs)
        
        echo "Processing [$current_user/$total_users]: $username"
        
        # Generate or get new password
        local new_password
        if [[ "$password_source" == "generate" ]]; then
            new_password=$(generate_secure_password)
            if [[ $? -ne 0 ]]; then
                log_operation "ERROR" "Failed to generate password for user: $username"
                ((failure_count++))
                continue
            fi
        elif [[ "$password_source" == "file" && -f "$password_file" ]]; then
            new_password=$(sed -n "${current_user}p" "$password_file")
            if [[ -z "$new_password" ]]; then
                log_operation "ERROR" "No password found in file for user: $username"
                ((failure_count++))
                continue
            fi
        else
            log_operation "ERROR" "Invalid password source or file not found"
            ((failure_count++))
            continue
        fi
        
        # Change password
        if enterprise_change_password "$username" "$current_password" "$new_password" "$force_change"; then
            ((success_count++))
            
            # Save generated password securely if needed
            if [[ "$password_source" == "generate" ]]; then
                local password_output="/tmp/roundfleet_passwords_$(date +%s).txt"
                echo "$username:$new_password" >> "$password_output"
                chmod 600 "$password_output"
            fi
        else
            ((failure_count++))
        fi
        
        # Progress update
        local progress=$((current_user * 100 / total_users))
        echo "Progress: $progress% ($success_count successful, $failure_count failed)"
        
    done < "$users_file"
    
    log_operation "SUCCESS" "Bulk password change completed - Success: $success_count, Failed: $failure_count"
    
    if [[ "$password_source" == "generate" && -f "$password_output" ]]; then
        echo "Generated passwords saved to: $password_output"
        echo "WARNING: This file contains sensitive data. Handle appropriately and delete when no longer needed."
    fi
    
    return $failure_count
}

# Password expiration management
manage_password_expiration() {
    local username="$1"
    local expiration_days="${2:-90}"
    local action="${3:-set}"  # "set", "remove", "check"
    
    case "$action" in
        "set")
            local expiration_date=$(date -v+${expiration_days}d '+%Y-%m-%d %H:%M:%S')
            if dscl . -create "/Users/$username" accountPolicyData "<dict><key>passwordLastSetTime</key><date>$(date -u '+%Y-%m-%dT%H:%M:%SZ')</date><key>maxMinutesUntilChangePassword</key><integer>$((expiration_days * 24 * 60))</integer></dict>"; then
                log_operation "SUCCESS" "Password expiration set for user $username: $expiration_days days"
                return 0
            else
                log_operation "ERROR" "Failed to set password expiration for user $username"
                return 1
            fi
            ;;
        "remove")
            if dscl . -delete "/Users/$username" accountPolicyData; then
                log_operation "SUCCESS" "Password expiration removed for user $username"
                return 0
            else
                log_operation "ERROR" "Failed to remove password expiration for user $username"
                return 1
            fi
            ;;
        "check")
            local policy_data=$(dscl . -read "/Users/$username" accountPolicyData 2>/dev/null)
            if [[ -n "$policy_data" ]]; then
                echo "Password expiration policy exists for user $username"
                echo "$policy_data"
                return 0
            else
                echo "No password expiration policy for user $username"
                return 1
            fi
            ;;
    esac
}

# Generate password compliance report
generate_password_report() {
    local report_file="/tmp/roundfleet_password_report_$(date +%Y%m%d_%H%M%S).txt"
    
    {
        echo "Roundfleet Password Management Report"
        echo "Generated: $(date)"
        echo "Hostname: $(hostname)"
        echo "Administrator: $(whoami)"
        echo "=================================="
        echo ""
        
        echo "Recent Password Operations (Last 24 hours):"
        if [[ -f "$LOG_FILE" ]]; then
            local yesterday=$(date -v-1d '+%Y-%m-%d')
            grep "$yesterday\|$(date '+%Y-%m-%d')" "$LOG_FILE" | grep -E "(PASSWORD_CHANGED|PASSWORD_CHANGE_FAILED)" | tail -50
        else
            echo "No log file found"
        fi
        
        echo ""
        echo "Security Events (Last 24 hours):"
        if [[ -f "$AUDIT_LOG" ]]; then
            local yesterday=$(date -v-1d '+%Y-%m-%d')
            grep "$yesterday\|$(date '+%Y-%m-%d')" "$AUDIT_LOG" | tail -20
        else
            echo "No audit log found"
        fi
        
        echo ""
        echo "Password Policy Status:"
        echo "Minimum Length: $MIN_PASSWORD_LENGTH"
        echo "Maximum Length: $MAX_PASSWORD_LENGTH"
        echo "Complexity Required: $COMPLEXITY_REQUIREMENTS"
        echo "History Count: $PASSWORD_HISTORY_COUNT"
        echo "Lockout Duration: $LOCKOUT_DURATION seconds"
        
        echo ""
        echo "User Account Summary:"
        local total_users=$(dscl . -list /Users | grep -v '^_' | grep -v '^daemon\|^nobody\|^root' | wc -l)
        echo "Total Active Users: $total_users"
        
        echo ""
        echo "System Information:"
        echo "macOS Version: $(sw_vers -productVersion)"
        echo "Security Framework: $(security --version 2>/dev/null || echo "Unknown")"
        
    } > "$report_file"
    
    echo "Password management report saved to: $report_file"
    log_operation "INFO" "Password report generated: $report_file"
}

# Main password management function
main() {
    local action="${1:-help}"
    
    case "$action" in
        "change")
            local username="$2"
            local current_password="$3"
            local new_password="$4"
            local force_change="${5:-false}"
            
            if [[ -z "$username" ]]; then
                echo "Usage: $0 change <username> [current_password] [new_password] [force]"
                echo "Note: If passwords are not provided, you will be prompted securely"
                exit 1
            fi
            
            # Prompt for passwords if not provided
            if [[ -z "$current_password" && "$force_change" != "true" ]]; then
                echo -n "Enter current password for $username: "
                read -s current_password
                echo
            fi
            
            if [[ -z "$new_password" ]]; then
                echo -n "Enter new password for $username (or press Enter to generate): "
                read -s new_password
                echo
                
                if [[ -z "$new_password" ]]; then
                    new_password=$(generate_secure_password)
                    if [[ $? -eq 0 ]]; then
                        echo "Generated secure password for $username"
                        echo "New password: $new_password"
                        echo "WARNING: Save this password securely and provide it to the user"
                    else
                        echo "Failed to generate secure password"
                        exit 1
                    fi
                fi
            fi
            
            enterprise_change_password "$username" "$current_password" "$new_password" "$force_change"
            ;;
        "generate")
            local length="${2:-16}"
            generate_secure_password "$length"
            ;;
        "validate")
            local password="$2"
            if [[ -z "$password" ]]; then
                echo -n "Enter password to validate: "
                read -s password
                echo
            fi
            
            if validate_password_complexity "$password"; then
                echo "Password meets complexity requirements"
                exit 0
            else
                echo "Password does not meet complexity requirements"
                exit 1
            fi
            ;;
        "bulk")
            local users_file="$2"
            local password_source="${3:-generate}"
            local password_file="$4"
            
            if [[ -z "$users_file" ]]; then
                echo "Usage: $0 bulk <users_file> [password_source] [password_file]"
                echo "password_source: 'generate' or 'file'"
                exit 1
            fi
            
            bulk_password_change "$users_file" "$password_source" "$password_file"
            ;;
        "expiration")
            local username="$2"
            local expiration_days="${3:-90}"
            local expiration_action="${4:-set}"
            
            if [[ -z "$username" ]]; then
                echo "Usage: $0 expiration <username> [days] [action]"
                echo "action: 'set', 'remove', or 'check'"
                exit 1
            fi
            
            manage_password_expiration "$username" "$expiration_days" "$expiration_action"
            ;;
        "force-change")
            local username="$2"
            
            if [[ -z "$username" ]]; then
                echo "Usage: $0 force-change <username>"
                exit 1
            fi
            
            force_password_change_on_login "$username"
            ;;
        "report")
            generate_password_report
            ;;
        "help"|*)
            echo "$SCRIPT_NAME v$VERSION"
            echo "Enterprise Password Change Management"
            echo ""
            echo "Usage: $0 <action> [options]"
            echo ""
            echo "Actions:"
            echo "  change <username> [current_pass] [new_pass] [force]     - Change user password"
            echo "  generate [length]                                       - Generate secure password"
            echo "  validate [password]                                     - Validate password complexity"
            echo "  bulk <users_file> [source] [password_file]             - Bulk password changes"
            echo "  expiration <username> [days] [action]                   - Manage password expiration"
            echo "  force-change <username>                                 - Force password change on next login"
            echo "  report                                                   - Generate password management report"
            echo "  help                                                     - Show this help message"
            echo ""
            echo "Password Sources (for bulk operations):"
            echo "  generate    - Auto-generate secure passwords"
            echo "  file        - Read passwords from file"
            echo ""
            echo "Expiration Actions:"
            echo "  set         - Set password expiration"
            echo "  remove      - Remove password expiration"
            echo "  check       - Check current expiration policy"
            echo ""
            echo "Features:"
            echo "  • Enterprise-grade password complexity validation"
            echo "  • Comprehensive security audit logging"
            echo "  • Password history tracking and reuse prevention"
            echo "  • Secure random password generation"
            echo "  • Bulk password change operations"
            echo "  • Keychain synchronization"
            echo "  • Business hours and permission enforcement"
            echo "  • System account protection"
            echo ""
            echo "Security Features:"
            echo "  • Multi-layer authentication verification"
            echo "  • Secure credential handling with memory cleanup"
            echo "  • Comprehensive audit trail for compliance"
            echo "  • Real-time security event monitoring"
            echo "  • Automated security notifications"
            ;;
    esac
}

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

Quick Reference Commands

Single Password Changes

# Interactive password change
./password_manager.sh change john.doe

# Password change with current password
./password_manager.sh change john.doe "current_password" "new_secure_password"

# Force password change (admin only)
./password_manager.sh change john.doe "" "new_password" true

# Force password change on next login
./password_manager.sh force-change john.doe

Password Generation and Validation

# Generate secure password (default 16 chars)
./password_manager.sh generate

# Generate password with specific length
./password_manager.sh generate 20

# Validate password complexity
./password_manager.sh validate "MyPassword123!"

# Interactive password validation
./password_manager.sh validate

Bulk Operations

# Create bulk users specification file
cat > /tmp/users_to_change.txt << EOF
# username|current_password|force_change
john.doe|oldpass123|false
jane.smith||true
admin.user|adminpass|false
EOF

# Bulk change with auto-generated passwords
./password_manager.sh bulk "/tmp/users_to_change.txt" "generate"

# Bulk change with passwords from file
echo -e "NewPass123!\nSecurePass456@\nAdminNew789#" > /tmp/new_passwords.txt
./password_manager.sh bulk "/tmp/users_to_change.txt" "file" "/tmp/new_passwords.txt"

Password Expiration Management

# Set 90-day password expiration
./password_manager.sh expiration john.doe 90 set

# Set 60-day password expiration
./password_manager.sh expiration jane.smith 60 set

# Check current expiration policy
./password_manager.sh expiration john.doe "" check

# Remove password expiration
./password_manager.sh expiration john.doe "" remove

Integration Examples

JAMF Pro Integration

#!/bin/bash

# JAMF Pro script for enterprise password management
# Parameters: $4 = action, $5 = username, $6 = new_password, $7 = force_change

ACTION="$4"
USERNAME="$5"
NEW_PASSWORD="$6"
FORCE_CHANGE="${7:-false}"

# Download password manager if not present
if [[ ! -f "/usr/local/bin/roundfleet_password_manager.sh" ]]; then
    curl -o "/usr/local/bin/roundfleet_password_manager.sh" "https://scripts.roundfleet.com/password_manager.sh"
    chmod +x "/usr/local/bin/roundfleet_password_manager.sh"
fi

# Execute password operation
case "$ACTION" in
    "change")
        if [[ -z "$NEW_PASSWORD" ]]; then
            # Generate secure password
            NEW_PASSWORD=$(/usr/local/bin/roundfleet_password_manager.sh generate 16)
        fi
        
        /usr/local/bin/roundfleet_password_manager.sh change "$USERNAME" "" "$NEW_PASSWORD" "$FORCE_CHANGE"
        
        # Store password in JAMF (encrypted)
        echo "Password changed for $USERNAME"
        ;;
    "force-change")
        /usr/local/bin/roundfleet_password_manager.sh force-change "$USERNAME"
        ;;
    "expiration")
        local expiration_days="${6:-90}"
        /usr/local/bin/roundfleet_password_manager.sh expiration "$USERNAME" "$expiration_days" "set"
        ;;
    *)
        echo "Invalid action: $ACTION"
        exit 1
        ;;
esac

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

exit $?

Configuration Profile for Password Policy

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>PayloadContent</key>
    <array>
        <dict>
            <key>PayloadType</key>
            <string>com.roundfleet.password.policy</string>
            <key>PayloadIdentifier</key>
            <string>com.roundfleet.password.policy.main</string>
            <key>PayloadDisplayName</key>
            <string>Roundfleet Password Policy</string>
            <key>MinimumPasswordLength</key>
            <integer>12</integer>
            <key>MaximumPasswordLength</key>
            <integer>128</integer>
            <key>RequireUppercase</key>
            <true/>
            <key>RequireLowercase</key>
            <true/>
            <key>RequireNumbers</key>
            <true/>
            <key>RequireSpecialCharacters</key>
            <true/>
            <key>PasswordHistoryCount</key>
            <integer>12</integer>
            <key>MaximumFailedAttempts</key>
            <integer>3</integer>
            <key>LockoutDuration</key>
            <integer>1800</integer>
            <key>ForbiddenPatterns</key>
            <array>
                <string>password</string>
                <string>123456</string>
                <string>qwerty</string>
                <string>admin</string>
            </array>
        </dict>
    </array>
</dict>
</plist>

Active Directory Integration

#!/bin/bash

# Integration with Active Directory for password synchronization
sync_password_with_ad() {
    local username="$1"
    local new_password="$2"
    local ad_domain="company.local"
    
    # Change local password first
    if enterprise_change_password "$username" "" "$new_password" "true"; then
        log_operation "SUCCESS" "Local password changed for $username"
        
        # Sync with Active Directory
        if command -v dsconfigad &>/dev/null; then
            if dsconfigad -passinterval 0 -username "$username" -password "$new_password"; then
                log_operation "SUCCESS" "Password synchronized with Active Directory for $username"
                return 0
            else
                log_operation "ERROR" "Failed to synchronize password with Active Directory for $username"
                return 1
            fi
        else
            log_operation "WARNING" "Active Directory tools not available"
            return 1
        fi
    else
        log_operation "ERROR" "Failed to change local password for $username"
        return 1
    fi
}

Security Features

Secure Password Handling

# Secure memory cleanup
cleanup_sensitive_data() {
    local password_var="$1"
    
    # Clear variable content
    unset "$password_var"
    
    # Clear bash history of sensitive commands
    history -c
    history -w
    
    # Clear temporary files
    find "$TEMP_DIR" -name "*.tmp" -type f -exec shred -vfz -n 3 {} \; 2>/dev/null
}

# Secure password input
secure_password_input() {
    local prompt="$1"
    local password=""
    
    echo -n "$prompt"
    
    # Disable echo and read password
    stty -echo
    read password
    stty echo
    echo
    
    echo "$password"
}

Audit and Compliance

# Generate compliance report for auditors
generate_compliance_report() {
    local report_file="/var/reports/password_compliance_$(date +%Y%m%d).csv"
    
    echo "Timestamp,User,Event,Source_IP,Session,Details,Compliance_Status" > "$report_file"
    
    # Parse audit log for password events
    grep "SECURITY_EVENT" "$AUDIT_LOG" | while IFS='|' read -r event_type timestamp event_name username source_ip session details; do
        local compliance_status="COMPLIANT"
        
        # Check for non-compliant events
        case "$event_name" in
            "AUTH_FAILURE"|"PERMISSION_DENIED"|"SYSTEM_ACCOUNT_ACCESS")
                compliance_status="NON_COMPLIANT"
                ;;
        esac
        
        echo "$timestamp,$username,$event_name,$source_ip,$session,$details,$compliance_status" >> "$report_file"
    done
    
    echo "Compliance report generated: $report_file"
}

Troubleshooting

Common Issues and Solutions

IssueCauseSolution
Permission deniedInsufficient privilegesRun as admin or root
Current password incorrectWrong current passwordVerify current password or use force change
Password complexity failureWeak passwordUse password generator or strengthen password
Keychain update failedKeychain locked or corruptedManually unlock keychain or reset
System account protectionAttempted change on system userUse regular user accounts only

Log Analysis

# View recent password operations
tail -f /var/log/roundfleet_password_operations.log

# Search for security events
grep "SECURITY_EVENT" /var/log/roundfleet_password_audit.log

# Count password changes by user
grep "PASSWORD_CHANGED" /var/log/roundfleet_password_audit.log | cut -d'|' -f4 | sort | uniq -c

Best Practices

  1. Use strong password policies with complexity requirements
  2. Enable password history to prevent reuse
  3. Implement regular password rotation for high-privilege accounts
  4. Monitor audit logs for suspicious activity
  5. Use secure password generation for temporary passwords
  6. Integrate with directory services for centralized management
  7. Test password changes on non-production systems first
  8. Implement emergency procedures for account lockouts

This enterprise password change management system provides comprehensive security controls, audit capabilities, and policy enforcement while maintaining the reliability of the core dscl command for effective fleet password management.

Package Management with Homebrew on macOS

Streamline software deployment and package management across your Roundfleet devices using Homebrew. This tutorial covers enterprise software installation, configuration management, compliance tracking, and automated deployment workflows for comprehensive fleet management.

Understanding Homebrew for Enterprise

Homebrew provides powerful package management for macOS:

  • Formula packages - Command-line tools and libraries
  • Cask applications - GUI applications and large binaries
  • Tap repositories - Third-party package sources
  • Bundle files - Declarative package manifests
  • Services - Background daemon management

Basic Homebrew Installation

Install Homebrew

#!/bin/bash

# Install Homebrew package manager
install_homebrew() {
    echo "=== Installing Homebrew Package Manager ==="
    
    # Check if Homebrew is already installed
    if command -v brew >/dev/null 2>&1; then
        echo "✅ Homebrew already installed: $(brew --version | head -1)"
        return 0
    fi
    
    echo "📦 Installing Homebrew..."
    
    # Install Homebrew
    if /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"; then
        echo "✅ Homebrew installation completed"
        
        # Add Homebrew to PATH for current session
        if [[ -f "/opt/homebrew/bin/brew" ]]; then
            eval "$(/opt/homebrew/bin/brew shellenv)"
        elif [[ -f "/usr/local/bin/brew" ]]; then
            eval "$(/usr/local/bin/brew shellenv)"
        fi
        
        # Verify installation
        if command -v brew >/dev/null 2>&1; then
            echo "🔍 Homebrew version: $(brew --version | head -1)"
            return 0
        else
            echo "❌ Homebrew installation verification failed"
            return 1
        fi
    else
        echo "❌ Homebrew installation failed"
        return 1
    fi
}

# Execute installation
install_homebrew

Enhanced Package Installation Script

#!/bin/bash

# Enhanced package installation based on GitHub Gist
# Reference: https://gist.github.com/CliffordAnderson/817777b5dc0e67769e4b

enhanced_package_installation() {
    echo "=== Enhanced Package Installation ==="
    
    # Ensure Homebrew is installed
    if ! command -v brew >/dev/null 2>&1; then
        echo "❌ Homebrew not found. Installing..."
        install_homebrew || return 1
    fi
    
    # Update Homebrew
    echo "🔄 Updating Homebrew..."
    brew update
    
    # Programming Languages
    echo "💻 Installing programming languages..."
    brew install scala
    brew install --cask r
    brew install openjdk
    
    # Development Tools
    echo "🛠️ Installing development tools..."
    brew install docker
    brew install git
    brew install --cask github
    brew install --cask visual-studio-code
    brew install --cask hyper
    
    # Communication Apps
    echo "💬 Installing communication apps..."
    brew install --cask discord
    brew install --cask microsoft-teams
    brew install --cask slack
    brew install --cask zoom
    
    # Web Tools
    echo "🌐 Installing web tools..."
    brew install httpie
    brew install node
    brew install nvm
    brew install --cask firefox
    brew install --cask google-chrome
    brew install --cask postman
    
    # File Storage
    echo "📁 Installing file storage tools..."
    brew install --cask dropbox
    brew install --cask onedrive
    
    # Writing Apps
    echo "✍️ Installing writing apps..."
    brew install pandoc
    brew install --cask zotero
    brew install --cask microsoft-word
    
    # Other Applications
    echo "🎯 Installing additional applications..."
    brew install --cask anki
    
    echo "✅ Package installation completed"
}

# Execute enhanced installation
enhanced_package_installation

Enterprise Homebrew Management System

#!/bin/bash

# Roundfleet Enterprise Homebrew Management System
# Comprehensive package deployment, compliance tracking, and fleet management

# Configuration
LOG_FILE="/var/log/roundfleet_homebrew.log"
CONFIG_DIR="/etc/roundfleet/packages"
PROFILES_DIR="$CONFIG_DIR/profiles"
CACHE_DIR="/var/cache/roundfleet/homebrew"
REPORTS_DIR="$CONFIG_DIR/reports"
COMPLIANCE_DIR="$CONFIG_DIR/compliance"

# Package profiles for different roles
declare -A PACKAGE_PROFILES=(
    ["developer"]="git,node,python,docker,visual-studio-code,github,postman,hyper"
    ["designer"]="adobe-creative-cloud,figma,sketch,canva,affinity-designer,imageoptim"
    ["manager"]="microsoft-office,slack,zoom,teams,dropbox,onedrive,notion"
    ["analyst"]="r,python,tableau,microsoft-excel,jupyter-notebook,pandas"
    ["security"]="wireshark,nmap,burp-suite,malwarebytes,1password,gpg-suite"
    ["education"]="zoom,microsoft-office,rstudio,zotero,anki,mendeley"
    ["minimal"]="google-chrome,firefox,zoom,slack"
    ["corporate"]="microsoft-office,teams,onedrive,1password,chrome-enterprise"
)

# Compliance frameworks
declare -A COMPLIANCE_PACKAGES=(
    ["hipaa"]="1password,malwarebytes,gpg-suite,microsoft-office"
    ["sox"]="microsoft-office,1password,box-drive,tableau"
    ["gdpr"]="1password,gpg-suite,notion,signal"
    ["iso27001"]="1password,malwarebytes,gpg-suite,microsoft-defender"
)

# License tracking
declare -A LICENSE_REQUIRED=(
    ["microsoft-office"]="commercial"
    ["adobe-creative-cloud"]="commercial"
    ["tableau"]="commercial"
    ["sketch"]="commercial"
    ["1password"]="commercial"
    ["zoom"]="freemium"
    ["slack"]="freemium"
    ["notion"]="freemium"
)

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

# Ensure Homebrew is installed and configured
ensure_homebrew() {
    log_action "Ensuring Homebrew is properly configured"
    
    # Check if Homebrew is installed
    if ! command -v brew >/dev/null 2>&1; then
        log_action "Installing Homebrew..."
        if ! /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"; then
            log_action "❌ Failed to install Homebrew"
            return 1
        fi
        
        # Configure PATH
        if [[ -f "/opt/homebrew/bin/brew" ]]; then
            eval "$(/opt/homebrew/bin/brew shellenv)"
        elif [[ -f "/usr/local/bin/brew" ]]; then
            eval "$(/usr/local/bin/brew shellenv)"
        fi
    fi
    
    # Update Homebrew
    log_action "Updating Homebrew..."
    brew update 2>/dev/null || log_action "⚠️ Homebrew update failed"
    
    # Verify Homebrew health
    if brew doctor >/dev/null 2>&1; then
        log_action "✅ Homebrew health check passed"
    else
        log_action "⚠️ Homebrew health check issues detected"
    fi
    
    return 0
}

# Install packages from profile
install_package_profile() {
    local profile_name="$1"
    local dry_run="${2:-false}"
    
    log_action "Installing package profile: $profile_name (dry_run: $dry_run)"
    
    # Get profile packages
    local profile_packages="${PACKAGE_PROFILES[$profile_name]}"
    if [[ -z "$profile_packages" ]]; then
        log_action "❌ Unknown profile: $profile_name"
        return 1
    fi
    
    # Ensure Homebrew is ready
    ensure_homebrew || return 1
    
    # Parse packages
    IFS=',' read -ra PACKAGES <<< "$profile_packages"
    
    local success_count=0
    local failure_count=0
    local already_installed=0
    
    for package in "${PACKAGES[@]}"; do
        # Clean package name
        package=$(echo "$package" | sed 's/^[ \t]*//;s/[ \t]*$//')
        
        log_action "Processing package: $package"
        
        if [[ "$dry_run" == "true" ]]; then
            echo "Would install: $package"
            continue
        fi
        
        # Check if already installed
        if is_package_installed "$package"; then
            log_action "✅ Package already installed: $package"
            already_installed=$((already_installed + 1))
            continue
        fi
        
        # Install package
        if install_single_package "$package"; then
            log_action "✅ Successfully installed: $package"
            success_count=$((success_count + 1))
        else
            log_action "❌ Failed to install: $package"
            failure_count=$((failure_count + 1))
        fi
    done
    
    # Summary
    log_action "Installation summary - Success: $success_count, Failed: $failure_count, Already installed: $already_installed"
    
    # Generate installation report
    generate_installation_report "$profile_name" "$success_count" "$failure_count" "$already_installed"
    
    return 0
}

# Check if package is installed
is_package_installed() {
    local package="$1"
    
    # Check if it's a cask
    if brew list --cask "$package" >/dev/null 2>&1; then
        return 0
    fi
    
    # Check if it's a formula
    if brew list "$package" >/dev/null 2>&1; then
        return 0
    fi
    
    return 1
}

# Install single package
install_single_package() {
    local package="$1"
    
    # Try as cask first (for GUI applications)
    if brew install --cask "$package" 2>/dev/null; then
        return 0
    fi
    
    # Try as formula (for CLI tools)
    if brew install "$package" 2>/dev/null; then
        return 0
    fi
    
    return 1
}

# Generate comprehensive software inventory
generate_software_inventory() {
    log_action "Generating comprehensive software inventory"
    
    local inventory_file="$REPORTS_DIR/software_inventory_$(date '+%Y%m%d_%H%M%S').json"
    
    cat > "$inventory_file" << EOF
{
    "inventory_metadata": {
        "timestamp": "$(date -Iseconds)",
        "hostname": "$(hostname)",
        "os_version": "$(sw_vers -productVersion)",
        "homebrew_version": "$(brew --version | head -1)",
        "generator": "Roundfleet Homebrew Manager"
    },
    "installed_packages": {
        "formulae": $(brew list --formula --json),
        "casks": $(brew list --cask --json)
    },
    "package_summary": {
        "total_formulae": $(brew list --formula | wc -l | tr -d ' '),
        "total_casks": $(brew list --cask | wc -l | tr -d ' '),
        "outdated_packages": $(brew outdated --json)
    },
    "system_info": {
        "homebrew_prefix": "$(brew --prefix)",
        "homebrew_cellar": "$(brew --cellar)",
        "homebrew_cache": "$(brew --cache)"
    }
}
EOF

    log_action "✅ Software inventory generated: $inventory_file"
    echo "$inventory_file"
}

# License compliance check
check_license_compliance() {
    log_action "Checking license compliance for installed packages"
    
    local compliance_report="$COMPLIANCE_DIR/license_compliance_$(date '+%Y%m%d_%H%M%S').json"
    
    cat > "$compliance_report" << EOF
{
    "compliance_metadata": {
        "timestamp": "$(date -Iseconds)",
        "hostname": "$(hostname)",
        "check_type": "license_compliance"
    },
    "license_analysis": [
EOF

    local first=true
    local compliance_issues=0
    
    # Check installed casks for license requirements
    while IFS= read -r package; do
        local license_type="${LICENSE_REQUIRED[$package]}"
        
        if [[ -n "$license_type" ]]; then
            if [[ "$first" == true ]]; then
                first=false
            else
                echo "," >> "$compliance_report"
            fi
            
            local compliance_status="unknown"
            local needs_attention=false
            
            case "$license_type" in
                "commercial")
                    compliance_status="requires_license"
                    needs_attention=true
                    compliance_issues=$((compliance_issues + 1))
                    ;;
                "freemium")
                    compliance_status="freemium_check_usage"
                    ;;
            esac
            
            cat >> "$compliance_report" << EOF
        {
            "package": "$package",
            "license_type": "$license_type",
            "compliance_status": "$compliance_status",
            "needs_attention": $needs_attention,
            "installed_date": "$(brew list --cask --versions "$package" 2>/dev/null | awk '{print $2}' || echo 'unknown')"
        }
EOF
        fi
    done < <(brew list --cask)
    
    cat >> "$compliance_report" << EOF
    ],
    "summary": {
        "total_packages_checked": $(brew list --cask | wc -l | tr -d ' '),
        "license_issues_found": $compliance_issues,
        "compliance_status": "$([ $compliance_issues -eq 0 ] && echo 'compliant' || echo 'requires_attention')"
    }
}
EOF

    log_action "✅ License compliance check completed: $compliance_report"
    echo "$compliance_report"
}

# Update all packages
update_all_packages() {
    local update_mode="${1:-safe}"  # safe, aggressive, or security-only
    
    log_action "Starting package updates (mode: $update_mode)"
    
    # Ensure Homebrew is ready
    ensure_homebrew || return 1
    
    # Update Homebrew itself
    log_action "Updating Homebrew..."
    if brew update; then
        log_action "✅ Homebrew updated successfully"
    else
        log_action "❌ Homebrew update failed"
        return 1
    fi
    
    # Get outdated packages
    local outdated_formulae outdated_casks
    outdated_formulae=$(brew outdated --formula --quiet)
    outdated_casks=$(brew outdated --cask --quiet)
    
    case "$update_mode" in
        "safe")
            # Update formulae only (CLI tools are generally safer to update)
            if [[ -n "$outdated_formulae" ]]; then
                log_action "Updating outdated formulae: $outdated_formulae"
                brew upgrade
            fi
            ;;
        "aggressive")
            # Update everything
            if [[ -n "$outdated_formulae" ]]; then
                log_action "Updating all outdated formulae"
                brew upgrade
            fi
            if [[ -n "$outdated_casks" ]]; then
                log_action "Updating all outdated casks"
                brew upgrade --cask
            fi
            ;;
        "security-only")
            # Only update packages with known security issues
            # This would require integration with vulnerability databases
            log_action "Security-only updates not yet implemented"
            ;;
    esac
    
    # Cleanup
    log_action "Cleaning up old versions..."
    brew cleanup
    
    log_action "✅ Package updates completed"
    
    # Generate post-update inventory
    generate_software_inventory
}

# Generate Brewfile for current installation
generate_brewfile() {
    local brewfile_path="${1:-$CONFIG_DIR/Brewfile}"
    
    log_action "Generating Brewfile: $brewfile_path"
    
    # Create Brewfile header
    cat > "$brewfile_path" << EOF
# Roundfleet Brewfile
# Generated on $(date)
# Hostname: $(hostname)

# Taps
EOF

    # Add taps
    brew tap | while read -r tap; do
        echo "tap \"$tap\"" >> "$brewfile_path"
    done
    
    echo "" >> "$brewfile_path"
    echo "# Formulae" >> "$brewfile_path"
    
    # Add formulae
    brew list --formula | while read -r formula; do
        echo "brew \"$formula\"" >> "$brewfile_path"
    done
    
    echo "" >> "$brewfile_path"
    echo "# Casks" >> "$brewfile_path"
    
    # Add casks
    brew list --cask | while read -r cask; do
        echo "cask \"$cask\"" >> "$brewfile_path"
    done
    
    log_action "✅ Brewfile generated: $brewfile_path"
    echo "$brewfile_path"
}

# Install from Brewfile
install_from_brewfile() {
    local brewfile_path="$1"
    local dry_run="${2:-false}"
    
    if [[ ! -f "$brewfile_path" ]]; then
        log_action "❌ Brewfile not found: $brewfile_path"
        return 1
    fi
    
    log_action "Installing from Brewfile: $brewfile_path (dry_run: $dry_run)"
    
    # Ensure Homebrew is ready
    ensure_homebrew || return 1
    
    if [[ "$dry_run" == "true" ]]; then
        log_action "Dry run - would install packages from: $brewfile_path"
        brew bundle --file="$brewfile_path" --verbose --no-install
    else
        # Install packages from Brewfile
        if brew bundle --file="$brewfile_path"; then
            log_action "✅ Brewfile installation completed"
            return 0
        else
            log_action "❌ Brewfile installation failed"
            return 1
        fi
    fi
}

# Security audit of installed packages
security_audit() {
    log_action "Performing security audit of installed packages"
    
    local audit_report="$REPORTS_DIR/security_audit_$(date '+%Y%m%d_%H%M%S').json"
    
    cat > "$audit_report" << EOF
{
    "audit_metadata": {
        "timestamp": "$(date -Iseconds)",
        "hostname": "$(hostname)",
        "audit_type": "security"
    },
    "security_findings": [
EOF

    local first=true
    local security_issues=0
    
    # Check for known vulnerable packages (simplified check)
    # In production, this would integrate with CVE databases
    local vulnerable_packages=("[email protected]" "node@14" "[email protected]")
    
    for vuln_package in "${vulnerable_packages[@]}"; do
        if is_package_installed "$vuln_package"; then
            if [[ "$first" == true ]]; then
                first=false
            else
                echo "," >> "$audit_report"
            fi
            
            cat >> "$audit_report" << EOF
        {
            "package": "$vuln_package",
            "severity": "medium",
            "issue": "potentially_outdated_version",
            "recommendation": "update_to_latest_version",
            "installed_version": "$(brew list --versions "$vuln_package" | awk '{print $2}')"
        }
EOF
            security_issues=$((security_issues + 1))
        fi
    done
    
    cat >> "$audit_report" << EOF
    ],
    "summary": {
        "total_packages_audited": $(( $(brew list --formula | wc -l) + $(brew list --cask | wc -l) )),
        "security_issues_found": $security_issues,
        "security_status": "$([ $security_issues -eq 0 ] && echo 'secure' || echo 'requires_attention')"
    }
}
EOF

    log_action "✅ Security audit completed: $audit_report"
    echo "$audit_report"
}

# Generate installation report
generate_installation_report() {
    local profile_name="$1"
    local success_count="$2"
    local failure_count="$3"
    local already_installed="$4"
    
    local report_file="$REPORTS_DIR/installation_report_${profile_name}_$(date '+%Y%m%d_%H%M%S').json"
    
    cat > "$report_file" << EOF
{
    "installation_metadata": {
        "timestamp": "$(date -Iseconds)",
        "hostname": "$(hostname)",
        "profile": "$profile_name",
        "generator": "Roundfleet Homebrew Manager"
    },
    "installation_results": {
        "successful_installations": $success_count,
        "failed_installations": $failure_count,
        "already_installed": $already_installed,
        "total_processed": $(( success_count + failure_count + already_installed ))
    },
    "post_installation_inventory": $(generate_software_inventory | tail -n +2 | head -n -1)
}
EOF

    log_action "✅ Installation report generated: $report_file"
    echo "$report_file"
}

# Main execution function
main() {
    local action="${1:-inventory}"
    local parameter="$2"
    local additional_param="$3"
    
    log_action "=== Roundfleet Homebrew Management Started ==="
    log_action "Action: $action"
    log_action "Parameter: ${parameter:-N/A}"
    
    setup_directories
    
    case "$action" in
        "install-profile")
            if [[ -z "$parameter" ]]; then
                echo "Available package profiles:"
                for profile in "${!PACKAGE_PROFILES[@]}"; do
                    echo "  - $profile: ${PACKAGE_PROFILES[$profile]}"
                done
                echo ""
                echo "Usage: $0 install-profile <profile_name> [dry_run]"
                exit 1
            fi
            install_package_profile "$parameter" "$additional_param"
            ;;
        "inventory")
            generate_software_inventory
            ;;
        "update")
            update_all_packages "$parameter"
            ;;
        "compliance")
            check_license_compliance
            ;;
        "security")
            security_audit
            ;;
        "brewfile-generate")
            generate_brewfile "$parameter"
            ;;
        "brewfile-install")
            if [[ -z "$parameter" ]]; then
                echo "Usage: $0 brewfile-install <brewfile_path> [dry_run]"
                exit 1
            fi
            install_from_brewfile "$parameter" "$additional_param"
            ;;
        "ensure")
            ensure_homebrew
            ;;
        *)
            echo "Usage: $0 {install-profile|inventory|update|compliance|security|brewfile-generate|brewfile-install|ensure}"
            echo "  install-profile    - Install packages from predefined profile"
            echo "  inventory         - Generate software inventory report"
            echo "  update           - Update all packages (safe|aggressive|security-only)"
            echo "  compliance       - Check license compliance"
            echo "  security         - Perform security audit"
            echo "  brewfile-generate - Generate Brewfile from current installation"
            echo "  brewfile-install  - Install packages from Brewfile"
            echo "  ensure           - Ensure Homebrew is installed and configured"
            exit 1
            ;;
    esac
    
    log_action "=== Homebrew management completed ==="
}

# Execute main function
main "$@"

Advanced Package Management Features

Custom Package Profile Creation

#!/bin/bash

# Create custom package profile
create_custom_profile() {
    local profile_name="$1"
    local packages="$2"
    
    echo "=== Creating Custom Package Profile ==="
    echo "Profile: $profile_name"
    echo "Packages: $packages"
    
    # Validate packages exist
    IFS=',' read -ra PACKAGE_LIST <<< "$packages"
    local valid_packages=()
    
    for package in "${PACKAGE_LIST[@]}"; do
        package=$(echo "$package" | sed 's/^[ \t]*//;s/[ \t]*$//')
        
        # Check if package exists in Homebrew
        if brew search --formula --cask "$package" | grep -q "^$package$"; then
            valid_packages+=("$package")
            echo "✅ Valid package: $package"
        else
            echo "⚠️  Package not found: $package"
        fi
    done
    
    if [[ ${#valid_packages[@]} -eq 0 ]]; then
        echo "❌ No valid packages found"
        return 1
    fi
    
    # Create profile
    local profile_packages
    printf -v profile_packages '%s,' "${valid_packages[@]}"
    profile_packages=${profile_packages%,}  # Remove trailing comma
    
    PACKAGE_PROFILES["$profile_name"]="$profile_packages"
    
    echo "✅ Custom profile created: $profile_name"
    echo "Packages: $profile_packages"
}

Automated License Management

#!/bin/bash

# Automated license management and tracking
manage_software_licenses() {
    echo "=== Software License Management ==="
    
    local license_db="$COMPLIANCE_DIR/license_database.json"
    
    # Create license database if it doesn't exist
    if [[ ! -f "$license_db" ]]; then
        cat > "$license_db" << EOF
{
    "license_metadata": {
        "created": "$(date -Iseconds)",
        "last_updated": "$(date -Iseconds)"
    },
    "licenses": {},
    "compliance_rules": {}
}
EOF
    fi
    
    # Scan for commercial software
    local commercial_software=()
    while IFS= read -r package; do
        if [[ -n "${LICENSE_REQUIRED[$package]}" ]]; then
            commercial_software+=("$package")
        fi
    done < <(brew list --cask)
    
    echo "Found ${#commercial_software[@]} packages requiring license management:"
    printf '%s\n' "${commercial_software[@]}"
    
    # Generate license report
    local license_report="$REPORTS_DIR/license_report_$(date '+%Y%m%d_%H%M%S').json"
    
    cat > "$license_report" << EOF
{
    "license_report_metadata": {
        "timestamp": "$(date -Iseconds)",
        "hostname": "$(hostname)"
    },
    "commercial_software": [
EOF

    local first=true
    for package in "${commercial_software[@]}"; do
        if [[ "$first" == true ]]; then
            first=false
        else
            echo "," >> "$license_report"
        fi
        
        cat >> "$license_report" << EOF
        {
            "package": "$package",
            "license_type": "${LICENSE_REQUIRED[$package]}",
            "installed_version": "$(brew list --cask --versions "$package" 2>/dev/null | awk '{print $2}' || echo 'unknown')",
            "license_status": "requires_verification"
        }
EOF
    done
    
    cat >> "$license_report" << EOF
    ]
}
EOF

    echo "📋 License report generated: $license_report"
}

Best Practices

🚀 Enterprise Deployment

  • Profile-based installations for different user roles and departments
  • Centralized package management with Brewfile deployment across fleets
  • Automated software inventory tracking and reporting
  • License compliance monitoring with automated auditing

🔐 Security Management

  • Regular security audits of installed packages and dependencies
  • Vulnerability scanning integration with CVE databases
  • Package signature verification and trusted source validation
  • Controlled update deployment with testing phases

📋 Compliance and Governance

  • License tracking for commercial software compliance
  • Policy enforcement based on organizational requirements
  • Audit trails for all package installations and updates
  • Cost management through license optimization

🔧 Maintenance and Optimization

  • Automated updates with rollback capabilities
  • Cleanup and optimization to manage disk space
  • Performance monitoring of package management operations
  • Custom profile creation for specialized use cases

Important Notes

  • Test deployments in staging environments before production rollout
  • Backup configurations before major package updates
  • Monitor license compliance to avoid legal and financial risks
  • Regular inventory audits to maintain accurate software tracking
  • Network bandwidth considerations for large-scale deployments
  • User communication for software changes and updates

Integration with Enterprise Systems

The Homebrew management system can be integrated with:

  • MDM solutions for policy enforcement
  • Asset management systems for inventory tracking
  • License management platforms for compliance automation
  • Security tools for vulnerability assessment
  • Monitoring systems for deployment tracking

Notification Management and User Experience Optimization on macOS

Optimize user productivity and maintain enterprise communication standards across your Roundfleet devices with comprehensive notification management and user experience optimization. This tutorial covers advanced notification controls, productivity enhancement, distraction management, and automated policy enforcement for improved organizational efficiency.

Understanding macOS Notification Management

macOS notification system serves multiple enterprise functions:

  • Communication Hub - Centralized message delivery and user alerts
  • Productivity Controller - Managing interruptions and focus time
  • Security Gateway - Controlling information exposure and access
  • User Experience Optimizer - Balancing information delivery with workflow efficiency
  • Enterprise Policy Enforcer - Ensuring compliance with communication standards

Basic Notification Center Management

Disable Notification Center

#!/bin/bash

# Disable Notification Center for current user
disable_notification_center() {
    echo "=== Disabling Notification Center ==="
    
    # Get currently logged in user
    local current_user=$(echo "show State:/Users/ConsoleUser" | scutil | awk '/Name :/ { print $3 }')
    
    # Validate user login
    if [[ -z "$current_user" || "$current_user" == "loginwindow" ]]; then
        echo "❌ No user logged in, cannot proceed"
        return 1
    fi
    
    echo "Disabling Notification Center for user: $current_user"
    
    # Get user UID
    local uid=$(id -u "$current_user")
    
    # Function to run commands as current user
    run_as_user() {
        if [[ "$current_user" != "loginwindow" ]]; then
            launchctl asuser "$uid" sudo -u "$current_user" "$@"
        else
            echo "❌ No valid user session"
            return 1
        fi
    }
    
    # Check SIP status before proceeding
    local sip_status=$(csrutil status | grep -o "enabled\|disabled")
    if [[ "$sip_status" == "enabled" ]]; then
        echo "⚠️  System Integrity Protection (SIP) is enabled"
        echo "   Alternative notification management will be applied"
        apply_alternative_notification_management "$current_user"
        return 0
    fi
    
    # Disable Notification Center (requires SIP disabled)
    if run_as_user launchctl unload -w /System/Library/LaunchAgents/com.apple.notificationcenterui.plist 2>/dev/null; then
        echo "✅ Notification Center disabled successfully"
        
        # Log the action
        logger "Roundfleet: Notification Center disabled for user $current_user"
    else
        echo "⚠️  Direct disable failed, applying alternative management"
        apply_alternative_notification_management "$current_user"
    fi
    
    return 0
}

# Execute function
disable_notification_center

Enable Notification Center

#!/bin/bash

# Enable Notification Center for current user
enable_notification_center() {
    echo "=== Enabling Notification Center ==="
    
    # Get currently logged in user
    local current_user=$(echo "show State:/Users/ConsoleUser" | scutil | awk '/Name :/ { print $3 }')
    
    # Validate user login
    if [[ -z "$current_user" || "$current_user" == "loginwindow" ]]; then
        echo "❌ No user logged in, cannot proceed"
        return 1
    fi
    
    echo "Enabling Notification Center for user: $current_user"
    
    # Get user UID
    local uid=$(id -u "$current_user")
    
    # Function to run commands as current user
    run_as_user() {
        if [[ "$current_user" != "loginwindow" ]]; then
            launchctl asuser "$uid" sudo -u "$current_user" "$@"
        else
            echo "❌ No valid user session"
            return 1
        fi
    }
    
    # Check SIP status
    local sip_status=$(csrutil status | grep -o "enabled\|disabled")
    if [[ "$sip_status" == "enabled" ]]; then
        echo "✅ System Integrity Protection (SIP) is enabled (recommended)"
        echo "   Applying SIP-compatible notification management"
        configure_sip_compatible_notifications "$current_user"
        return 0
    fi
    
    # Enable Notification Center (requires SIP disabled)
    if run_as_user launchctl load -w /System/Library/LaunchAgents/com.apple.notificationcenterui.plist 2>/dev/null; then
        echo "✅ Notification Center enabled successfully"
        
        # Log the action
        logger "Roundfleet: Notification Center enabled for user $current_user"
    else
        echo "⚠️  Direct enable failed, applying alternative configuration"
        configure_sip_compatible_notifications "$current_user"
    fi
    
    return 0
}

# Execute function
enable_notification_center

SIP-Compatible Alternative Management

#!/bin/bash

# Apply notification management without requiring SIP disable
apply_alternative_notification_management() {
    local username="$1"
    
    echo "🔒 Applying SIP-Compatible Notification Management"
    
    # Configure Do Not Disturb settings
    sudo -u "$username" defaults write com.apple.ncprefs dnd_prefs -dict-add dndDisplayLock -bool true
    sudo -u "$username" defaults write com.apple.ncprefs dnd_prefs -dict-add dndDisplaySleep -bool true
    sudo -u "$username" defaults write com.apple.ncprefs dnd_prefs -dict-add dndMirrored -bool true
    
    # Disable notification sounds for productivity
    sudo -u "$username" defaults write com.apple.sound.beep.feedback -bool false
    sudo -u "$username" defaults write com.apple.sound.uiaudio.enabled -int 0
    
    # Configure notification banner settings
    sudo -u "$username" defaults write com.apple.ncprefs banner_setting -dict-add showOnLockScreen -bool false
    sudo -u "$username" defaults write com.apple.ncprefs banner_setting -dict-add showInNotificationCenter -bool false
    
    echo "✅ SIP-compatible notification management applied"
}

# Configure notifications while maintaining SIP
configure_sip_compatible_notifications() {
    local username="$1"
    
    echo "🔧 Configuring SIP-Compatible Notifications"
    
    # Enable optimized notification settings
    sudo -u "$username" defaults write com.apple.ncprefs apps_setting -dict-add showOnLockScreen -bool true
    sudo -u "$username" defaults write com.apple.ncprefs apps_setting -dict-add showInNotificationCenter -bool true
    sudo -u "$username" defaults write com.apple.ncprefs apps_setting -dict-add showPreviews -int 2
    
    # Configure notification grouping
    sudo -u "$username" defaults write com.apple.ncprefs notification_group_settings -dict-add grouping -int 1
    
    # Restart notification service
    sudo -u "$username" killall NotificationCenter 2>/dev/null || true
    
    echo "✅ SIP-compatible notification configuration applied"
}

Enterprise Notification Management System

#!/bin/bash

# Roundfleet Enterprise Notification Management System
# Comprehensive communication control, productivity optimization, and user experience enhancement

# Configuration
LOG_FILE="/var/log/roundfleet_notification_management.log"
CONFIG_DIR="/etc/roundfleet/notification_management"
POLICIES_DIR="$CONFIG_DIR/policies"
PROFILES_DIR="$CONFIG_DIR/profiles"
ANALYTICS_DIR="$CONFIG_DIR/analytics"
REPORTS_DIR="$CONFIG_DIR/reports"
COMPLIANCE_DIR="$CONFIG_DIR/compliance"
PRODUCTIVITY_DIR="$CONFIG_DIR/productivity"

# Notification management policies
declare -A NOTIFICATION_POLICIES=(
    ["focus_mode"]="minimal_interruptions,priority_only,scheduled_quiet_hours"
    ["productivity_optimized"]="smart_grouping,delayed_delivery,batch_notifications"
    ["enterprise_standard"]="security_alerts_priority,meeting_notifications,email_summaries"
    ["executive_minimal"]="critical_only,no_social,urgent_calls_only"
    ["developer_focused"]="code_alerts,build_status,critical_system_only"
    ["support_reactive"]="all_communications,instant_delivery,escalation_alerts"
    ["kiosk_restricted"]="system_alerts_only,no_personal,maintenance_notifications"
)

# Productivity optimization profiles
declare -A PRODUCTIVITY_PROFILES=(
    ["deep_work"]="2_hour_blocks,no_notifications,emergency_only"
    ["collaborative"]="team_messages,meeting_alerts,shared_documents"
    ["monitoring"]="system_status,security_events,performance_alerts"
    ["creative"]="inspiration_apps,design_feedback,minimal_interruptions"
    ["executive"]="calendar_updates,urgent_calls,board_communications"
)

# Communication channels priority
declare -A CHANNEL_PRIORITIES=(
    ["emergency"]="1"
    ["security"]="2"
    ["executive"]="3"
    ["team_lead"]="4"
    ["project"]="5"
    ["general"]="6"
    ["social"]="7"
    ["promotional"]="8"
)

# Enterprise applications configuration
declare -A ENTERPRISE_APPS=(
    ["communication"]="Slack,Microsoft Teams,Zoom,Webex"
    ["productivity"]="Microsoft Office,Google Workspace,Notion,Trello"
    ["security"]="CrowdStrike,Okta,1Password,VPN Clients"
    ["development"]="Xcode,Visual Studio Code,GitHub Desktop,Docker"
    ["business"]="Salesforce,HubSpot,Tableau,Power BI"
)

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

# Analyze current notification status
analyze_notification_status() {
    echo "=== Notification System Analysis ==="
    
    local current_user=$(echo "show State:/Users/ConsoleUser" | scutil | awk '/Name :/ { print $3 }')
    local analysis_report="$ANALYTICS_DIR/notification_analysis_$(date '+%Y%m%d_%H%M%S').json"
    
    cat > "$analysis_report" << EOF
{
    "analysis_metadata": {
        "timestamp": "$(date -Iseconds)",
        "hostname": "$(hostname)",
        "current_user": "$current_user",
        "macos_version": "$(sw_vers -productVersion)"
    },
    "system_status": {
        "notification_center_running": $(pgrep -x "NotificationCenter" >/dev/null && echo "true" || echo "false"),
        "sip_status": "$(csrutil status | grep -o "enabled\|disabled")",
        "dnd_status": $(get_dnd_status "$current_user"),
        "user_session_active": $(test -n "$current_user" && test "$current_user" != "loginwindow" && echo "true" || echo "false")
    },
    "notification_settings": $(get_notification_settings "$current_user"),
    "app_permissions": $(analyze_app_notification_permissions "$current_user"),
    "productivity_metrics": $(calculate_notification_productivity_impact "$current_user"),
    "security_assessment": $(assess_notification_security "$current_user")
}
EOF

    log_action "✅ Notification analysis completed: $analysis_report"
    echo "$analysis_report"
}

# Get Do Not Disturb status
get_dnd_status() {
    local username="$1"
    
    local dnd_enabled
    dnd_enabled=$(sudo -u "$username" defaults read com.apple.ncprefs dnd_prefs 2>/dev/null | grep -c "dndDisplayLock.*1" || echo "0")
    
    if [[ "$dnd_enabled" -gt 0 ]]; then
        echo "true"
    else
        echo "false"
    fi
}

# Get comprehensive notification settings
get_notification_settings() {
    local username="$1"
    
    cat << EOF
{
    "banner_style": "$(sudo -u "$username" defaults read com.apple.ncprefs banner_setting 2>/dev/null || echo 'default')",
    "lock_screen_enabled": $(sudo -u "$username" defaults read com.apple.ncprefs apps_setting showOnLockScreen 2>/dev/null || echo "true"),
    "notification_center_enabled": $(sudo -u "$username" defaults read com.apple.ncprefs apps_setting showInNotificationCenter 2>/dev/null || echo "true"),
    "preview_style": $(sudo -u "$username" defaults read com.apple.ncprefs apps_setting showPreviews 2>/dev/null || echo "2"),
    "grouping_enabled": $(sudo -u "$username" defaults read com.apple.ncprefs notification_group_settings grouping 2>/dev/null || echo "1"),
    "sound_enabled": $(sudo -u "$username" defaults read com.apple.sound.beep.feedback 2>/dev/null || echo "true")
}
EOF
}

# Configure enterprise notification policies
configure_enterprise_notification_policy() {
    local policy_name="$1"
    local target_users="$2"
    local deployment_scope="$3"
    
    log_action "Configuring enterprise notification policy: $policy_name"
    
    local policy_settings="${NOTIFICATION_POLICIES[$policy_name]}"
    if [[ -z "$policy_settings" ]]; then
        log_action "❌ Unknown notification policy: $policy_name"
        return 1
    fi
    
    echo "📋 Configuring Enterprise Notification Policy: $policy_name"
    echo "Target users: $target_users"
    echo "Deployment scope: $deployment_scope"
    
    # Create policy configuration
    local policy_config="$POLICIES_DIR/notification_policy_${policy_name}.json"
    
    cat > "$policy_config" << EOF
{
    "policy_metadata": {
        "name": "$policy_name",
        "created": "$(date -Iseconds)",
        "settings": "$policy_settings",
        "target_users": "$target_users",
        "deployment_scope": "$deployment_scope"
    },
    "notification_rules": $(generate_notification_rules "$policy_name"),
    "app_configurations": $(generate_app_configurations "$policy_name"),
    "productivity_settings": $(generate_productivity_settings "$policy_name"),
    "security_controls": $(generate_security_controls "$policy_name")
}
EOF

    # Apply policy based on deployment scope
    case "$deployment_scope" in
        "user_specific")
            apply_user_specific_policy "$policy_name" "$target_users" "$policy_config"
            ;;
        "group_based")
            apply_group_based_policy "$policy_name" "$target_users" "$policy_config"
            ;;
        "fleet_wide")
            apply_fleet_wide_policy "$policy_name" "$policy_config"
            ;;
        *)
            log_action "⚠️  Unknown deployment scope: $deployment_scope"
            return 1
            ;;
    esac
    
    log_action "✅ Enterprise notification policy configured: $policy_name"
    return 0
}

# Generate notification rules for policy
generate_notification_rules() {
    local policy_name="$1"
    
    case "$policy_name" in
        "focus_mode")
            cat << 'EOF'
{
    "interruption_level": "critical_only",
    "quiet_hours": {"start": "09:00", "end": "17:00"},
    "allowed_apps": ["Calendar", "Phone", "Security"],
    "blocked_categories": ["social", "entertainment", "promotional"],
    "batch_delivery": true,
    "delay_non_urgent": 900
}
EOF
            ;;
        "productivity_optimized")
            cat << 'EOF'
{
    "interruption_level": "important",
    "smart_grouping": true,
    "summary_delivery": {"frequency": "hourly", "times": ["09:00", "13:00", "17:00"]},
    "priority_channels": ["work_communication", "calendar", "security"],
    "distraction_blocking": true,
    "focus_sessions": true
}
EOF
            ;;
        "enterprise_standard")
            cat << 'EOF'
{
    "interruption_level": "standard",
    "business_hours_only": false,
    "priority_contacts": "enterprise_directory",
    "security_alerts": "immediate",
    "meeting_notifications": "15_minutes_before",
    "email_batching": true
}
EOF
            ;;
        *)
            echo '{"default": "standard_enterprise_rules"}'
            ;;
    esac
}

# Apply productivity optimization
optimize_notification_productivity() {
    local optimization_level="$1"
    local username="$2"
    local work_schedule="$3"
    
    log_action "Optimizing notifications for productivity: level=$optimization_level, user=$username"
    
    local current_user=$(echo "show State:/Users/ConsoleUser" | scutil | awk '/Name :/ { print $3 }')
    local target_user="${username:-$current_user}"
    
    echo "🚀 Optimizing Notification Productivity"
    echo "Optimization level: $optimization_level"
    echo "Target user: $target_user"
    echo "Work schedule: $work_schedule"
    
    case "$optimization_level" in
        "basic")
            apply_basic_productivity_optimizations "$target_user" "$work_schedule"
            ;;
        "advanced")
            apply_advanced_productivity_optimizations "$target_user" "$work_schedule"
            ;;
        "expert")
            apply_expert_productivity_optimizations "$target_user" "$work_schedule"
            ;;
        *)
            log_action "⚠️  Unknown optimization level: $optimization_level"
            return 1
            ;;
    esac
    
    # Configure focus sessions
    configure_focus_sessions "$target_user" "$work_schedule"
    
    # Set up notification analytics
    setup_notification_analytics "$target_user"
    
    # Apply smart notification grouping
    configure_smart_notification_grouping "$target_user"
    
    log_action "✅ Notification productivity optimization completed"
    return 0
}

# Apply basic productivity optimizations
apply_basic_productivity_optimizations() {
    local username="$1"
    local schedule="$2"
    
    echo "📋 Applying Basic Productivity Optimizations"
    
    # Configure Do Not Disturb schedule
    if [[ "$schedule" == "business_hours" ]]; then
        # Enable DND outside business hours (6 PM to 9 AM)
        sudo -u "$username" defaults write com.apple.ncprefs dnd_prefs -dict-add fromHour -int 18
        sudo -u "$username" defaults write com.apple.ncprefs dnd_prefs -dict-add toHour -int 9
        sudo -u "$username" defaults write com.apple.ncprefs dnd_prefs -dict-add dndStart -bool true
    fi
    
    # Reduce notification sounds
    sudo -u "$username" defaults write com.apple.sound.beep.feedback -bool false
    
    # Enable notification grouping
    sudo -u "$username" defaults write com.apple.ncprefs notification_group_settings -dict-add grouping -int 1
    
    # Configure banner display time (shorter for less distraction)
    sudo -u "$username" defaults write com.apple.ncprefs banner_setting -dict-add bannerTime -int 5
    
    echo "✅ Basic productivity optimizations applied"
}

# Configure smart notification grouping
configure_smart_notification_grouping() {
    local username="$1"
    
    echo "🧠 Configuring Smart Notification Grouping"
    
    # Group notifications by app
    sudo -u "$username" defaults write com.apple.ncprefs notification_group_settings -dict-add groupByApp -bool true
    
    # Group notifications by thread
    sudo -u "$username" defaults write com.apple.ncprefs notification_group_settings -dict-add groupByThread -bool true
    
    # Set notification summary schedule
    sudo -u "$username" defaults write com.apple.ncprefs summary_settings -dict-add summaryEnabled -bool true
    sudo -u "$username" defaults write com.apple.ncprefs summary_settings -dict-add summaryTime -array "09:00" "13:00" "17:00"
    
    echo "✅ Smart notification grouping configured"
}

# Monitor notification productivity impact
monitor_notification_impact() {
    log_action "Starting notification productivity impact monitoring"
    
    local current_user=$(echo "show State:/Users/ConsoleUser" | scutil | awk '/Name :/ { print $3 }')
    local impact_report="$PRODUCTIVITY_DIR/notification_impact_$(date '+%Y%m%d_%H%M%S').json"
    
    cat > "$impact_report" << EOF
{
    "impact_metadata": {
        "timestamp": "$(date -Iseconds)",
        "hostname": "$(hostname)",
        "monitored_user": "$current_user",
        "monitoring_period": "real_time"
    },
    "productivity_metrics": {
        "interruption_frequency": $(calculate_interruption_frequency "$current_user"),
        "focus_session_effectiveness": $(measure_focus_session_effectiveness "$current_user"),
        "notification_response_time": $(calculate_notification_response_time "$current_user"),
        "app_switching_frequency": $(measure_app_switching_frequency "$current_user")
    },
    "notification_analytics": {
        "total_notifications": $(count_daily_notifications "$current_user"),
        "critical_notifications": $(count_critical_notifications "$current_user"),
        "dismissed_without_action": $(count_dismissed_notifications "$current_user"),
        "notification_sources": $(analyze_notification_sources "$current_user")
    },
    "recommendations": {
        "optimization_suggestions": $(generate_optimization_suggestions "$current_user"),
        "policy_adjustments": $(suggest_policy_adjustments "$current_user"),
        "productivity_improvements": $(identify_productivity_improvements "$current_user")
    }
}
EOF

    log_action "✅ Notification impact monitoring completed: $impact_report"
    echo "$impact_report"
}

# Configure application-specific notification settings
configure_app_notification_settings() {
    local app_category="$1"
    local notification_level="$2"
    local username="$3"
    
    log_action "Configuring app-specific notifications: category=$app_category, level=$notification_level"
    
    local current_user=$(echo "show State:/Users/ConsoleUser" | scutil | awk '/Name :/ { print $3 }')
    local target_user="${username:-$current_user}"
    
    echo "📱 Configuring App-Specific Notification Settings"
    echo "Category: $app_category"
    echo "Notification level: $notification_level"
    echo "Target user: $target_user"
    
    local apps="${ENTERPRISE_APPS[$app_category]}"
    if [[ -z "$apps" ]]; then
        log_action "⚠️  Unknown app category: $app_category"
        return 1
    fi
    
    # Parse app list
    IFS=',' read -ra APP_LIST <<< "$apps"
    
    for app in "${APP_LIST[@]}"; do
        configure_individual_app_notifications "$app" "$notification_level" "$target_user"
    done
    
    # Create app category configuration
    local app_config="$PROFILES_DIR/app_notifications_${app_category}.json"
    
    cat > "$app_config" << EOF
{
    "category_metadata": {
        "category": "$app_category",
        "notification_level": "$notification_level",
        "configured_user": "$target_user",
        "configured_time": "$(date -Iseconds)"
    },
    "configured_apps": $(echo "${apps}" | jq -R 'split(",")'),
    "notification_settings": $(get_category_notification_settings "$notification_level"),
    "productivity_impact": $(assess_category_productivity_impact "$app_category")
}
EOF

    log_action "✅ App-specific notification settings configured for category: $app_category"
    return 0
}

# Generate enterprise compliance report
generate_notification_compliance_report() {
    local compliance_framework="$1"
    
    log_action "Generating notification compliance report for: $compliance_framework"
    
    local compliance_report="$COMPLIANCE_DIR/notification_compliance_${compliance_framework}_$(date '+%Y%m%d_%H%M%S').json"
    local current_user=$(echo "show State:/Users/ConsoleUser" | scutil | awk '/Name :/ { print $3 }')
    
    cat > "$compliance_report" << EOF
{
    "compliance_metadata": {
        "timestamp": "$(date -Iseconds)",
        "framework": "$compliance_framework",
        "hostname": "$(hostname)",
        "assessed_user": "$current_user",
        "generator": "Roundfleet Notification Management Compliance"
    },
    "framework_requirements": $(get_framework_notification_requirements "$compliance_framework"),
    "compliance_assessment": {
        "overall_score": $(calculate_notification_compliance_score "$compliance_framework"),
        "privacy_compliance": $(assess_notification_privacy_compliance "$compliance_framework"),
        "security_compliance": $(assess_notification_security_compliance "$compliance_framework"),
        "data_handling_compliance": $(assess_notification_data_compliance "$compliance_framework")
    },
    "policy_adherence": {
        "enterprise_policies": $(check_enterprise_policy_adherence),
        "user_privacy_settings": $(verify_user_privacy_settings "$current_user"),
        "data_retention_policies": $(check_notification_data_retention),
        "access_controls": $(verify_notification_access_controls "$current_user")
    },
    "recommendations": $(generate_compliance_recommendations "$compliance_framework"),
    "remediation_actions": $(generate_compliance_remediation_actions "$compliance_framework")
}
EOF

    log_action "✅ Notification compliance report generated: $compliance_report"
    echo "$compliance_report"
}

# Main execution function
main() {
    local action="${1:-status}"
    local parameter="$2"
    local additional_param="$3"
    local extra_param="$4"
    
    log_action "=== Roundfleet Notification Management Started ==="
    log_action "Action: $action"
    log_action "Parameter: ${parameter:-N/A}"
    
    setup_directories
    
    case "$action" in
        "disable")
            disable_notification_center
            ;;
        "enable")
            enable_notification_center
            ;;
        "analyze")
            analyze_notification_status
            ;;
        "policy")
            if [[ -z "$parameter" || -z "$additional_param" ]]; then
                echo "Available notification policies:"
                for policy in "${!NOTIFICATION_POLICIES[@]}"; do
                    echo "  - $policy: ${NOTIFICATION_POLICIES[$policy]}"
                done
                echo ""
                echo "Usage: $0 policy <policy_name> <target_users> [deployment_scope]"
                echo "Deployment scopes: user_specific, group_based, fleet_wide"
                exit 1
            fi
            configure_enterprise_notification_policy "$parameter" "$additional_param" "$extra_param"
            ;;
        "optimize")
            if [[ -z "$parameter" ]]; then
                echo "Optimization levels: basic, advanced, expert"
                echo "Work schedules: business_hours, flexible, 24x7"
                echo ""
                echo "Usage: $0 optimize <level> [username] [work_schedule]"
                exit 1
            fi
            optimize_notification_productivity "$parameter" "$additional_param" "$extra_param"
            ;;
        "monitor")
            monitor_notification_impact
            ;;
        "apps")
            if [[ -z "$parameter" || -z "$additional_param" ]]; then
                echo "Available app categories:"
                for category in "${!ENTERPRISE_APPS[@]}"; do
                    echo "  - $category: ${ENTERPRISE_APPS[$category]}"
                done
                echo ""
                echo "Notification levels: critical_only, important, standard, all, disabled"
                echo "Usage: $0 apps <category> <notification_level> [username]"
                exit 1
            fi
            configure_app_notification_settings "$parameter" "$additional_param" "$extra_param"
            ;;
        "compliance")
            if [[ -z "$parameter" ]]; then
                echo "Available compliance frameworks:"
                echo "  - gdpr: GDPR privacy compliance"
                echo "  - hipaa: HIPAA healthcare compliance"
                echo "  - sox: Sarbanes-Oxley financial compliance"
                echo "  - pci_dss: PCI DSS payment compliance"
                echo ""
                echo "Usage: $0 compliance <framework>"
                exit 1
            fi
            generate_notification_compliance_report "$parameter"
            ;;
        "status")
            analyze_notification_status
            ;;
        *)
            echo "Usage: $0 {disable|enable|analyze|policy|optimize|monitor|apps|compliance|status}"
            echo "  disable     - Disable notification center (with SIP considerations)"
            echo "  enable      - Enable notification center"
            echo "  analyze     - Analyze current notification system status"
            echo "  policy      - Configure enterprise notification policies"
            echo "  optimize    - Optimize notifications for productivity"
            echo "  monitor     - Monitor notification productivity impact"
            echo "  apps        - Configure app-specific notification settings"
            echo "  compliance  - Generate compliance report"
            echo "  status      - Check notification system status"
            exit 1
            ;;
    esac
    
    log_action "=== Notification management operation completed ==="
}

# Execute main function
main "$@"

Advanced Notification Management Features

Intelligent Focus Sessions

#!/bin/bash

# AI-powered focus session management
configure_intelligent_focus_sessions() {
    local username="$1"
    local productivity_goals="$2"
    
    echo "🧠 Configuring Intelligent Focus Sessions"
    
    local focus_config="$PRODUCTIVITY_DIR/focus_sessions_${username}.json"
    
    cat > "$focus_config" << EOF
{
    "focus_session_config": {
        "user": "$username",
        "productivity_goals": "$productivity_goals",
        "session_types": {
            "deep_work": {
                "duration": 120,
                "break_duration": 15,
                "allowed_notifications": ["emergency", "security"],
                "blocked_apps": ["social", "entertainment"],
                "productivity_score_weight": 0.8
            },
            "collaborative": {
                "duration": 60,
                "break_duration": 10,
                "allowed_notifications": ["team_communication", "calendar"],
                "blocked_apps": ["personal_social"],
                "productivity_score_weight": 0.6
            },
            "creative": {
                "duration": 90,
                "break_duration": 20,
                "allowed_notifications": ["inspiration", "creative_tools"],
                "blocked_apps": ["analytical_tools"],
                "productivity_score_weight": 0.7
            }
        },
        "adaptive_learning": {
            "track_productivity_patterns": true,
            "adjust_session_length": true,
            "optimize_break_timing": true,
            "personalize_notification_filtering": true
        }
    }
}
EOF

    echo "✅ Intelligent focus sessions configured"
}

# Real-time productivity analytics
real_time_productivity_analytics() {
    echo "📊 Real-time Productivity Analytics"
    
    local analytics_script="$PRODUCTIVITY_DIR/real_time_analytics.sh"
    
    cat > "$analytics_script" << 'EOF'
#!/bin/bash

# Real-time notification productivity analytics

while true; do
    CURRENT_USER=$(echo "show State:/Users/ConsoleUser" | scutil | awk '/Name :/ { print $3 }')
    
    if [[ -n "$CURRENT_USER" && "$CURRENT_USER" != "loginwindow" ]]; then
        # Track notification interruptions
        NOTIFICATION_COUNT=$(log show --predicate 'subsystem == "com.apple.notificationcenter"' --last 1h | wc -l)
        
        # Calculate focus score
        FOCUS_SCORE=$(calculate_real_time_focus_score "$CURRENT_USER" "$NOTIFICATION_COUNT")
        
        # Generate productivity insights
        PRODUCTIVITY_INSIGHTS=$(generate_real_time_insights "$CURRENT_USER" "$FOCUS_SCORE")
        
        # Log analytics
        echo "$(date): User=$CURRENT_USER, Notifications=$NOTIFICATION_COUNT, Focus Score=$FOCUS_SCORE" >> /var/log/roundfleet_productivity_analytics.log
        
        # Adaptive optimization
        if [[ $FOCUS_SCORE -lt 60 ]]; then
            apply_adaptive_optimization "$CURRENT_USER"
        fi
    fi
    
    sleep 300  # Check every 5 minutes
done
EOF

    chmod +x "$analytics_script"
    echo "📈 Real-time analytics script created"
}

Machine Learning Optimization

#!/bin/bash

# ML-powered notification optimization
implement_ml_notification_optimization() {
    echo "🤖 Implementing ML Notification Optimization"
    
    local ml_config="$PRODUCTIVITY_DIR/ml_optimization.json"
    
    cat > "$ml_config" << EOF
{
    "ml_optimization": {
        "learning_algorithms": {
            "pattern_recognition": {
                "notification_timing_analysis": true,
                "user_response_prediction": true,
                "interruption_cost_calculation": true
            },
            "adaptive_filtering": {
                "priority_learning": true,
                "context_awareness": true,
                "productivity_correlation": true
            },
            "predictive_scheduling": {
                "optimal_delivery_times": true,
                "batch_optimization": true,
                "urgency_assessment": true
            }
        },
        "optimization_features": {
            "smart_batching": "group_related_notifications",
            "contextual_delivery": "deliver_based_on_user_activity",
            "priority_learning": "learn_from_user_actions",
            "productivity_preservation": "minimize_deep_work_interruptions"
        }
    }
}
EOF

    echo "🎯 ML optimization configuration created"
}

Enterprise Integration Features

🔗 System Integration

  • Active Directory integration for user-based notification policies
  • LDAP authentication for notification permission management
  • SIEM integration with security notification prioritization
  • Productivity platform sync (Slack, Teams, Asana integration)

📱 Fleet Management

  • Centralized policy deployment across enterprise devices
  • Role-based notification profiles with automatic assignment
  • Bulk configuration management with rollback capabilities
  • Compliance monitoring with automated reporting

🎯 User Experience Optimization

  • AI-powered notification filtering with learning algorithms
  • Context-aware delivery based on user activity and calendar
  • Productivity analytics with personalized insights
  • Focus session automation with smart interruption management

🛡️ Security and Privacy

  • SIP-compatible operations maintaining system security
  • Privacy-preserving analytics with data minimization
  • Secure notification routing with encryption in transit
  • Compliance framework support (GDPR, HIPAA, SOX, PCI DSS)

Important Notes

  • System Integrity Protection (SIP) should remain enabled for security
  • Alternative management methods provided for SIP-enabled systems
  • User privacy considerations essential for notification monitoring
  • Productivity optimization requires careful balance with communication needs
  • Regular assessment needed to maintain optimal notification policies
  • Compliance requirements may override productivity optimizations