Tutorial

New updates and improvements to Macfleet.

Password Management on macOS

Implement comprehensive password management and authentication control across your MacFleet 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

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

# Configuration
PASSWORD_CONFIG_FILE="/etc/macfleet/password_config.conf"
LOG_FILE="/var/log/macfleet_password_management.log"
AUDIT_FILE="/var/log/macfleet_password_audit.log"
BACKUP_DIR="/var/backups/macfleet/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/macfleet_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 "=== MacFleet 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 "MacFleet 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 "=== MacFleet 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/macfleet"
    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'
# MacFleet 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/macfleet_password_audit_$(date +%Y%m%d_%H%M%S).txt"
    
    {
        echo "MacFleet 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 MacFleet Management

#!/bin/bash

# MacFleet password management integration
macfleet_password_integration() {
    echo "=== MacFleet 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 MacFleet 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 MacFleet 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"
}

macfleet_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 MacFleet 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

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

# Configuration
LOG_FILE="/var/log/macfleet_password_security.log"
POLICY_CONFIG="/etc/macfleet/password_policy.conf"
COMPLIANCE_REPORT="/var/log/macfleet_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/macfleet"
    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'
# MacFleet 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 MacFleet Management

#!/bin/bash

# MacFleet password management integration
macfleet_password_integration() {
    echo "=== MacFleet 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 MacFleet API (placeholder)
    local api_endpoint="https://api.macfleet.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 MacFleet"
}

macfleet_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 MacFleet devices while maintaining usability and compliance with enterprise security standards.

Password Change Management on macOS

Securely manage password change operations across your MacFleet 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

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

# Configuration
SCRIPT_NAME="MacFleet Password Change Manager"
VERSION="1.0.0"
LOG_FILE="/var/log/macfleet_password_operations.log"
AUDIT_LOG="/var/log/macfleet_password_audit.log"
POLICY_FILE="/etc/macfleet/password_policy.conf"
TEMP_DIR="/tmp/macfleet_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=("security@company.com" "admin@company.com")

# 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/macfleet/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/macfleet/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="MacFleet 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 MacFleet 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/macfleet_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/macfleet_password_report_$(date +%Y%m%d_%H%M%S).txt"
    
    {
        echo "MacFleet 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/macfleet_password_manager.sh" ]]; then
    curl -o "/usr/local/bin/macfleet_password_manager.sh" "https://scripts.macfleet.com/password_manager.sh"
    chmod +x "/usr/local/bin/macfleet_password_manager.sh"
fi

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

# Generate report
/usr/local/bin/macfleet_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.macfleet.password.policy</string>
            <key>PayloadIdentifier</key>
            <string>com.macfleet.password.policy.main</string>
            <key>PayloadDisplayName</key>
            <string>MacFleet 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/macfleet_password_operations.log

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

# Count password changes by user
grep "PASSWORD_CHANGED" /var/log/macfleet_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 MacFleet 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

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

# Configuration
LOG_FILE="/var/log/macfleet_homebrew.log"
CONFIG_DIR="/etc/macfleet/packages"
PROFILES_DIR="$CONFIG_DIR/profiles"
CACHE_DIR="/var/cache/macfleet/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": "MacFleet 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
# MacFleet 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=("python@3.8" "node@14" "openssl@1.1")
    
    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": "MacFleet 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 "=== MacFleet 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 MacFleet 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 "MacFleet: 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 "MacFleet: 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

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

# Configuration
LOG_FILE="/var/log/macfleet_notification_management.log"
CONFIG_DIR="/etc/macfleet/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": "MacFleet 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 "=== MacFleet 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/macfleet_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