Tutorial

New updates and improvements to Macfleet.

Apple ID Management and Identity Tracking on macOS

Manage Apple ID usage, monitor iCloud services, and implement enterprise identity policies across your MacFleet devices. This tutorial covers Apple ID discovery, service monitoring, privacy compliance, and comprehensive identity management for enterprise environments.

Understanding Apple ID Integration on macOS

Apple ID integration provides access to various Apple services:

  • iCloud services - Storage, synchronization, and backup
  • Find My network - Device location and security features
  • App Store - Application downloads and updates
  • Apple Pay - Secure payment processing
  • Keychain - Password and credential synchronization

Basic Apple ID Detection

Simple Apple ID Discovery

#!/bin/bash

# Basic Apple ID detection for all users
check_apple_ids() {
    echo "=== Apple ID Detection ==="
    
    for user in $(dscl . list /Users UniqueID | awk '$2 >= 500 {print $1}'); do
        local userHome
        userHome=$(dscl . read /Users/"$user" NFSHomeDirectory | sed 's/NFSHomeDirectory://' | grep "/" | sed 's/^[ \t]*//')
        
        local appleid
        appleid=$(dscl . readpl "${userHome}" dsAttrTypeNative:LinkedIdentity appleid.apple.com:linked\ identities:0:full\ name 2>/dev/null | awk -F'full name: ' '{print $2}')
        
        if [[ "${appleid}" == "" ]]; then
            echo "👤 User: ${user} - No Apple ID signed in"
        else
            echo "🍎 User: ${user} - Apple ID: ${appleid}"
        fi
    done
}

# Usage
check_apple_ids

Enhanced Apple ID Information

#!/bin/bash

# Enhanced Apple ID detection with additional details
get_detailed_apple_id_info() {
    local username="$1"
    
    echo "=== Detailed Apple ID Information for: $username ==="
    
    # Get user home directory
    local userHome
    userHome=$(dscl . read /Users/"$username" NFSHomeDirectory | sed 's/NFSHomeDirectory://' | grep "/" | sed 's/^[ \t]*//')
    
    if [[ -z "$userHome" ]]; then
        echo "❌ User not found: $username"
        return 1
    fi
    
    # Check Apple ID
    local appleid
    appleid=$(dscl . readpl "${userHome}" dsAttrTypeNative:LinkedIdentity appleid.apple.com:linked\ identities:0:full\ name 2>/dev/null | awk -F'full name: ' '{print $2}')
    
    if [[ -n "$appleid" ]]; then
        echo "🍎 Apple ID: $appleid"
        
        # Check iCloud status
        local icloud_status
        if defaults read "${userHome}/Library/Preferences/MobileMeAccounts" Accounts &>/dev/null; then
            echo "☁️  iCloud: Configured"
        else
            echo "☁️  iCloud: Not configured"
        fi
        
        # Check Find My status
        if defaults read "${userHome}/Library/Preferences/com.apple.preferences.account" &>/dev/null; then
            echo "📍 Find My: Available"
        else
            echo "📍 Find My: Not available"
        fi
        
        # Check Keychain status
        if [[ -d "${userHome}/Library/Keychains" ]]; then
            local keychain_count
            keychain_count=$(find "${userHome}/Library/Keychains" -name "*.keychain*" | wc -l)
            echo "🔑 Keychains: $keychain_count found"
        fi
        
    else
        echo "❌ No Apple ID signed in"
    fi
}

# Usage example
# get_detailed_apple_id_info "john.doe"

Enterprise Apple ID Management System

#!/bin/bash

# MacFleet Enterprise Apple ID Management System
# Comprehensive identity management, compliance tracking, and service monitoring

# Configuration
LOG_FILE="/var/log/macfleet_apple_id.log"
CONFIG_DIR="/etc/macfleet/identity"
REPORTS_DIR="$CONFIG_DIR/reports"
POLICIES_DIR="$CONFIG_DIR/policies"
BACKUP_DIR="/var/backups/identity_configs"

# Apple service configurations
declare -A APPLE_SERVICES=(
    ["icloud"]="com.apple.bird,com.apple.iCloudHelper,MobileMeAccounts"
    ["findmy"]="com.apple.icloud.findmydeviced,com.apple.FindMyMacHelper"
    ["appstore"]="com.apple.appstore,com.apple.CommerceKit"
    ["keychain"]="Security,Keychain"
    ["handoff"]="com.apple.coreservices.useractivityd"
)

# Privacy policy templates
declare -A PRIVACY_POLICIES=(
    ["strict"]="no_icloud,no_sync,audit_all"
    ["balanced"]="limited_icloud,controlled_sync,audit_sensitive"
    ["permissive"]="full_icloud,full_sync,audit_minimal"
    ["education"]="edu_icloud,student_sync,audit_compliance"
    ["enterprise"]="corp_icloud,enterprise_sync,audit_comprehensive"
)

# Compliance frameworks
declare -A COMPLIANCE_FRAMEWORKS=(
    ["hipaa"]="healthcare,strict_audit,encrypted_only"
    ["sox"]="financial,comprehensive_audit,controlled_access"
    ["gdpr"]="privacy_first,consent_required,data_minimization"
    ["ferpa"]="education,student_privacy,limited_sharing"
    ["corporate"]="business_use,managed_access,policy_enforcement"
)

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

# Comprehensive Apple ID discovery
discover_apple_ids() {
    log_action "Starting comprehensive Apple ID discovery"
    
    local discovery_report="$REPORTS_DIR/apple_id_discovery_$(date '+%Y%m%d_%H%M%S').json"
    
    cat > "$discovery_report" << EOF
{
    "discovery_metadata": {
        "timestamp": "$(date -Iseconds)",
        "hostname": "$(hostname)",
        "os_version": "$(sw_vers -productVersion)",
        "generator": "MacFleet Apple ID Manager"
    },
    "user_accounts": [
EOF

    local first=true
    local total_users=0
    local signed_in_users=0
    
    # Process each user account
    for user in $(dscl . list /Users UniqueID | awk '$2 >= 500 {print $1}'); do
        total_users=$((total_users + 1))
        
        if [[ "$first" == true ]]; then
            first=false
        else
            echo "," >> "$discovery_report"
        fi
        
        local userHome uid gid realName
        userHome=$(dscl . read /Users/"$user" NFSHomeDirectory | sed 's/NFSHomeDirectory://' | grep "/" | sed 's/^[ \t]*//')
        uid=$(dscl . read /Users/"$user" UniqueID | awk '{print $2}')
        gid=$(dscl . read /Users/"$user" PrimaryGroupID | awk '{print $2}')
        realName=$(dscl . read /Users/"$user" RealName | sed 's/RealName://' | sed 's/^[ \t]*//' || echo "")
        
        # Get Apple ID information
        local appleid=""
        if [[ -n "$userHome" ]]; then
            appleid=$(dscl . readpl "${userHome}" dsAttrTypeNative:LinkedIdentity appleid.apple.com:linked\ identities:0:full\ name 2>/dev/null | awk -F'full name: ' '{print $2}')
        fi
        
        local apple_id_status="not_signed_in"
        if [[ -n "$appleid" ]]; then
            apple_id_status="signed_in"
            signed_in_users=$((signed_in_users + 1))
        fi
        
        # Check Apple services
        local services_status
        services_status=$(check_apple_services "$user" "$userHome")
        
        # Generate user record
        cat >> "$discovery_report" << EOF
        {
            "username": "$user",
            "real_name": "$realName",
            "uid": $uid,
            "gid": $gid,
            "home_directory": "$userHome",
            "apple_id_status": "$apple_id_status",
            "apple_id": "${appleid:-null}",
            "services": $services_status,
            "last_login": "$(last -1 "$user" | head -1 | awk '{print $4, $5, $6, $7}' || echo 'Never')",
            "account_created": "$(stat -f %SB -t %Y-%m-%d "$userHome" 2>/dev/null || echo 'Unknown')"
        }
EOF
        
        log_action "Processed user: $user (Apple ID: ${apple_id_status})"
    done
    
    cat >> "$discovery_report" << EOF
    ],
    "summary": {
        "total_users": $total_users,
        "users_with_apple_id": $signed_in_users,
        "users_without_apple_id": $((total_users - signed_in_users)),
        "apple_id_adoption_rate": $(awk "BEGIN {printf \"%.2f\", ($signed_in_users/$total_users)*100}")
    }
}
EOF

    log_action "✅ Apple ID discovery completed: $discovery_report"
    echo "$discovery_report"
}

# Check Apple services for a user
check_apple_services() {
    local username="$1"
    local userHome="$2"
    
    cat << EOF
{
    "icloud": {
        "enabled": $(check_icloud_status "$userHome"),
        "drive": $(check_icloud_drive "$userHome"),
        "photos": $(check_icloud_photos "$userHome"),
        "mail": $(check_icloud_mail "$userHome")
    },
    "find_my": {
        "enabled": $(check_findmy_status "$userHome"),
        "device_registered": $(check_findmy_device "$userHome")
    },
    "app_store": {
        "signed_in": $(check_appstore_status "$userHome"),
        "automatic_downloads": $(check_auto_downloads "$userHome")
    },
    "keychain": {
        "sync_enabled": $(check_keychain_sync "$userHome"),
        "keychain_count": $(count_keychains "$userHome")
    },
    "handoff": {
        "enabled": $(check_handoff_status "$userHome")
    }
}
EOF
}

# Individual service check functions
check_icloud_status() {
    local userHome="$1"
    if defaults read "${userHome}/Library/Preferences/MobileMeAccounts" Accounts &>/dev/null; then
        echo "true"
    else
        echo "false"
    fi
}

check_icloud_drive() {
    local userHome="$1"
    if [[ -d "${userHome}/Library/Mobile Documents/com~apple~CloudDocs" ]]; then
        echo "true"
    else
        echo "false"
    fi
}

check_icloud_photos() {
    local userHome="$1"
    if defaults read "${userHome}/Library/Preferences/com.apple.photoanalysisd" &>/dev/null; then
        echo "true"
    else
        echo "false"
    fi
}

check_icloud_mail() {
    local userHome="$1"
    if defaults read "${userHome}/Library/Preferences/com.apple.mail" &>/dev/null | grep -q "icloud"; then
        echo "true"
    else
        echo "false"
    fi
}

check_findmy_status() {
    local userHome="$1"
    if defaults read "${userHome}/Library/Preferences/com.apple.preferences.account" &>/dev/null; then
        echo "true"
    else
        echo "false"
    fi
}

check_findmy_device() {
    local userHome="$1"
    if pgrep -f "FindMyMacHelper" >/dev/null; then
        echo "true"
    else
        echo "false"
    fi
}

check_appstore_status() {
    local userHome="$1"
    if defaults read "${userHome}/Library/Preferences/com.apple.appstore" &>/dev/null; then
        echo "true"
    else
        echo "false"
    fi
}

check_auto_downloads() {
    local userHome="$1"
    local auto_downloads
    auto_downloads=$(defaults read "${userHome}/Library/Preferences/com.apple.appstore" AutomaticallyDownloadApps 2>/dev/null || echo "0")
    if [[ "$auto_downloads" == "1" ]]; then
        echo "true"
    else
        echo "false"
    fi
}

check_keychain_sync() {
    local userHome="$1"
    if security list-keychains -d user | grep -q "iCloud"; then
        echo "true"
    else
        echo "false"
    fi
}

count_keychains() {
    local userHome="$1"
    if [[ -d "${userHome}/Library/Keychains" ]]; then
        find "${userHome}/Library/Keychains" -name "*.keychain*" | wc -l | tr -d ' '
    else
        echo "0"
    fi
}

check_handoff_status() {
    local userHome="$1"
    local handoff_enabled
    handoff_enabled=$(defaults read "${userHome}/Library/Preferences/com.apple.coreservices.useractivityd" ActivityAdvertisingAllowed 2>/dev/null || echo "0")
    if [[ "$handoff_enabled" == "1" ]]; then
        echo "true"
    else
        echo "false"
    fi
}

# Monitor Apple ID changes
monitor_apple_id_changes() {
    local monitoring_duration="${1:-3600}"  # 1 hour default
    local check_interval="${2:-300}"        # 5 minutes default
    
    log_action "Starting Apple ID monitoring for ${monitoring_duration} seconds"
    
    local monitoring_report="$REPORTS_DIR/apple_id_monitoring_$(date '+%Y%m%d_%H%M%S').json"
    local baseline_file="/tmp/apple_id_baseline.json"
    
    # Create baseline
    discover_apple_ids > "$baseline_file"
    
    cat > "$monitoring_report" << EOF
{
    "monitoring_metadata": {
        "start_time": "$(date -Iseconds)",
        "duration_seconds": $monitoring_duration,
        "check_interval_seconds": $check_interval,
        "hostname": "$(hostname)"
    },
    "changes_detected": [
EOF

    local start_time end_time
    start_time=$(date +%s)
    end_time=$((start_time + monitoring_duration))
    
    local first=true
    while [[ $(date +%s) -lt $end_time ]]; do
        sleep "$check_interval"
        
        # Check for changes
        local current_state="/tmp/apple_id_current.json"
        discover_apple_ids > "$current_state"
        
        # Compare with baseline (simplified comparison)
        if ! diff "$baseline_file" "$current_state" >/dev/null 2>&1; then
            if [[ "$first" == true ]]; then
                first=false
            else
                echo "," >> "$monitoring_report"
            fi
            
            cat >> "$monitoring_report" << EOF
        {
            "timestamp": "$(date -Iseconds)",
            "change_type": "apple_id_status_change",
            "details": "Changes detected in Apple ID configuration"
        }
EOF
            
            log_action "⚠️  Apple ID configuration changes detected"
            
            # Update baseline
            cp "$current_state" "$baseline_file"
        fi
        
        rm -f "$current_state"
    done
    
    cat >> "$monitoring_report" << EOF
    ],
    "end_time": "$(date -Iseconds)"
}
EOF

    log_action "✅ Apple ID monitoring completed: $monitoring_report"
    rm -f "$baseline_file"
    echo "$monitoring_report"
}

# Apply privacy policies
apply_privacy_policy() {
    local policy_name="$1"
    local target_user="$2"
    
    log_action "Applying privacy policy: $policy_name for user: ${target_user:-all_users}"
    
    local policy_config="${PRIVACY_POLICIES[$policy_name]}"
    if [[ -z "$policy_config" ]]; then
        log_action "❌ Unknown privacy policy: $policy_name"
        return 1
    fi
    
    # Parse policy configuration
    IFS=',' read -ra POLICY_RULES <<< "$policy_config"
    
    for rule in "${POLICY_RULES[@]}"; do
        case "$rule" in
            "no_icloud")
                disable_icloud_services "$target_user"
                ;;
            "limited_icloud")
                configure_limited_icloud "$target_user"
                ;;
            "full_icloud")
                log_action "Full iCloud access permitted"
                ;;
            "no_sync")
                disable_sync_services "$target_user"
                ;;
            "controlled_sync")
                configure_controlled_sync "$target_user"
                ;;
            "audit_all")
                enable_comprehensive_audit "$target_user"
                ;;
            "audit_sensitive")
                enable_sensitive_audit "$target_user"
                ;;
            "audit_minimal")
                enable_minimal_audit "$target_user"
                ;;
        esac
    done
    
    log_action "✅ Privacy policy applied: $policy_name"
    return 0
}

# Disable iCloud services
disable_icloud_services() {
    local target_user="$1"
    
    log_action "Disabling iCloud services for user: ${target_user:-all_users}"
    
    if [[ -n "$target_user" ]]; then
        local userHome
        userHome=$(dscl . read /Users/"$target_user" NFSHomeDirectory | sed 's/NFSHomeDirectory://' | grep "/" | sed 's/^[ \t]*//')
        
        # Disable iCloud Drive
        defaults write "${userHome}/Library/Preferences/com.apple.bird" 'LastDisabledDate' -date "$(date)"
        
        # Disable iCloud Photos
        defaults write "${userHome}/Library/Preferences/com.apple.Photos" 'DisableiCloudPhotos' -bool true
        
        log_action "iCloud services disabled for user: $target_user"
    else
        log_action "Bulk iCloud disable requires individual user processing"
    fi
}

# Configure limited iCloud access
configure_limited_icloud() {
    local target_user="$1"
    
    log_action "Configuring limited iCloud access for user: ${target_user:-all_users}"
    
    # Implementation would involve setting specific iCloud service restrictions
    # This is a placeholder for actual implementation
    log_action "Limited iCloud configuration applied"
}

# Enable comprehensive audit
enable_comprehensive_audit() {
    local target_user="$1"
    
    log_action "Enabling comprehensive audit for user: ${target_user:-all_users}"
    
    # Create audit configuration
    local audit_config="$CONFIG_DIR/audit_comprehensive.conf"
    cat > "$audit_config" << EOF
# Comprehensive Apple ID Audit Configuration
audit_apple_id_changes=true
audit_icloud_access=true
audit_service_usage=true
audit_data_sync=true
log_level=detailed
retention_days=365
EOF

    log_action "Comprehensive audit enabled: $audit_config"
}

# Generate compliance report
generate_compliance_report() {
    local framework="$1"
    local report_type="${2:-summary}"
    
    log_action "Generating compliance report for framework: $framework"
    
    local compliance_report="$REPORTS_DIR/compliance_${framework}_$(date '+%Y%m%d_%H%M%S').json"
    
    # Get current Apple ID discovery data
    local discovery_data
    discovery_data=$(discover_apple_ids)
    
    cat > "$compliance_report" << EOF
{
    "compliance_metadata": {
        "timestamp": "$(date -Iseconds)",
        "framework": "$framework",
        "report_type": "$report_type",
        "hostname": "$(hostname)",
        "generator": "MacFleet Compliance Manager"
    },
    "compliance_assessment": {
        "framework_requirements": $(get_framework_requirements "$framework"),
        "current_status": $(assess_compliance_status "$framework"),
        "recommendations": $(generate_compliance_recommendations "$framework"),
        "risk_level": "$(calculate_risk_level "$framework")"
    },
    "user_data": $(echo "$discovery_data" | jq '.user_accounts')
}
EOF

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

# Get framework requirements
get_framework_requirements() {
    local framework="$1"
    
    case "$framework" in
        "hipaa")
            echo '{"encryption_required": true, "audit_required": true, "data_minimization": true, "access_controls": true}'
            ;;
        "gdpr")
            echo '{"consent_required": true, "data_portability": true, "right_to_erasure": true, "privacy_by_design": true}'
            ;;
        "sox")
            echo '{"financial_controls": true, "audit_trails": true, "segregation_of_duties": true, "data_integrity": true}'
            ;;
        "ferpa")
            echo '{"student_privacy": true, "parental_consent": true, "educational_purpose": true, "limited_disclosure": true}'
            ;;
        *)
            echo '{"general_security": true, "basic_audit": true}'
            ;;
    esac
}

# Assess compliance status
assess_compliance_status() {
    local framework="$1"
    
    # Simplified compliance assessment
    local compliance_score=0
    local total_checks=0
    
    # Check encryption
    total_checks=$((total_checks + 1))
    if system_profiler SPStorageDataType | grep -q "Encrypted: Yes"; then
        compliance_score=$((compliance_score + 1))
    fi
    
    # Check audit logging
    total_checks=$((total_checks + 1))
    if [[ -f "$LOG_FILE" ]]; then
        compliance_score=$((compliance_score + 1))
    fi
    
    local compliance_percentage
    compliance_percentage=$(awk "BEGIN {printf \"%.0f\", ($compliance_score/$total_checks)*100}")
    
    echo "{\"score\": $compliance_score, \"total_checks\": $total_checks, \"percentage\": $compliance_percentage, \"status\": \"$([ $compliance_percentage -ge 80 ] && echo 'compliant' || echo 'non_compliant')\"}"
}

# Generate compliance recommendations
generate_compliance_recommendations() {
    local framework="$1"
    
    local recommendations=()
    
    # Check for common compliance issues
    if ! system_profiler SPStorageDataType | grep -q "Encrypted: Yes"; then
        recommendations+=("Enable FileVault encryption")
    fi
    
    if [[ ! -f "$LOG_FILE" ]]; then
        recommendations+=("Configure comprehensive audit logging")
    fi
    
    # Framework-specific recommendations
    case "$framework" in
        "hipaa")
            recommendations+=("Implement data access controls" "Configure PHI data handling")
            ;;
        "gdpr")
            recommendations+=("Implement consent management" "Configure data retention policies")
            ;;
    esac
    
    # Convert to JSON array
    local json_recommendations="["
    local first=true
    for rec in "${recommendations[@]}"; do
        if [[ "$first" == true ]]; then
            first=false
        else
            json_recommendations+=","
        fi
        json_recommendations+="\"$rec\""
    done
    json_recommendations+="]"
    
    echo "$json_recommendations"
}

# Calculate risk level
calculate_risk_level() {
    local framework="$1"
    
    local risk_factors=0
    
    # Check for high-risk configurations
    if discover_apple_ids | jq -r '.summary.users_with_apple_id' | awk '$1 > 0 {exit 1}'; then
        risk_factors=$((risk_factors + 1))
    fi
    
    if [[ $risk_factors -ge 3 ]]; then
        echo "high"
    elif [[ $risk_factors -ge 1 ]]; then
        echo "medium"
    else
        echo "low"
    fi
}

# Backup Apple ID configurations
backup_apple_id_configs() {
    local backup_timestamp
    backup_timestamp=$(date '+%Y%m%d_%H%M%S')
    local backup_file="$BACKUP_DIR/apple_id_backup_$backup_timestamp.tar.gz"
    
    log_action "Creating Apple ID configuration backup: $backup_file"
    
    # Create temporary backup directory
    local temp_backup="/tmp/apple_id_backup_$$"
    mkdir -p "$temp_backup"
    
    # Export current discovery data
    discover_apple_ids > "$temp_backup/current_apple_ids.json"
    
    # Export user preferences (if accessible)
    for user in $(dscl . list /Users UniqueID | awk '$2 >= 500 {print $1}'); do
        local userHome
        userHome=$(dscl . read /Users/"$user" NFSHomeDirectory | sed 's/NFSHomeDirectory://' | grep "/" | sed 's/^[ \t]*//')
        
        if [[ -n "$userHome" && -d "$userHome" ]]; then
            mkdir -p "$temp_backup/users/$user"
            
            # Backup relevant preference files (if readable)
            if [[ -f "${userHome}/Library/Preferences/MobileMeAccounts.plist" ]]; then
                cp "${userHome}/Library/Preferences/MobileMeAccounts.plist" "$temp_backup/users/$user/" 2>/dev/null || true
            fi
        fi
    done
    
    # Create compressed backup
    if tar -czf "$backup_file" -C "$(dirname "$temp_backup")" "$(basename "$temp_backup")" 2>/dev/null; then
        log_action "✅ Apple ID backup created: $backup_file"
        rm -rf "$temp_backup"
        echo "$backup_file"
        return 0
    else
        log_action "❌ Apple ID backup failed"
        rm -rf "$temp_backup"
        return 1
    fi
}

# Main execution function
main() {
    local action="${1:-discover}"
    local parameter="$2"
    local additional_param="$3"
    
    log_action "=== MacFleet Apple ID Management Started ==="
    log_action "Action: $action"
    log_action "Parameter: ${parameter:-N/A}"
    
    # Setup
    setup_directories
    
    case "$action" in
        "discover")
            discover_apple_ids
            ;;
        "monitor")
            monitor_apple_id_changes "$parameter" "$additional_param"
            ;;
        "policy")
            if [[ -z "$parameter" ]]; then
                echo "Available privacy policies:"
                for policy in "${!PRIVACY_POLICIES[@]}"; do
                    echo "  - $policy: ${PRIVACY_POLICIES[$policy]}"
                done
                echo ""
                echo "Usage: $0 policy <policy_name> [username]"
                exit 1
            fi
            apply_privacy_policy "$parameter" "$additional_param"
            ;;
        "compliance")
            if [[ -z "$parameter" ]]; then
                echo "Available compliance frameworks:"
                for framework in "${!COMPLIANCE_FRAMEWORKS[@]}"; do
                    echo "  - $framework: ${COMPLIANCE_FRAMEWORKS[$framework]}"
                done
                echo ""
                echo "Usage: $0 compliance <framework> [report_type]"
                exit 1
            fi
            generate_compliance_report "$parameter" "$additional_param"
            ;;
        "backup")
            backup_apple_id_configs
            ;;
        "user")
            if [[ -z "$parameter" ]]; then
                echo "Usage: $0 user <username>"
                exit 1
            fi
            get_detailed_apple_id_info "$parameter"
            ;;
        *)
            echo "Usage: $0 {discover|monitor|policy|compliance|backup|user}"
            echo "  discover    - Discover Apple IDs across all users"
            echo "  monitor     - Monitor Apple ID changes over time"
            echo "  policy      - Apply privacy policies"
            echo "  compliance  - Generate compliance reports"
            echo "  backup      - Backup Apple ID configurations"
            echo "  user        - Get detailed info for specific user"
            exit 1
            ;;
    esac
    
    log_action "=== Apple ID management completed ==="
}

# Execute main function
main "$@"

Advanced Apple ID Analysis

Service Usage Analytics

#!/bin/bash

# Analyze Apple service usage patterns
analyze_service_usage() {
    echo "=== Apple Service Usage Analytics ==="
    
    local analytics_report="$REPORTS_DIR/service_analytics_$(date '+%Y%m%d_%H%M%S').json"
    
    cat > "$analytics_report" << EOF
{
    "analytics_metadata": {
        "timestamp": "$(date -Iseconds)",
        "hostname": "$(hostname)"
    },
    "service_usage": {
EOF

    # Analyze iCloud usage
    local icloud_users=0
    local total_users=0
    
    for user in $(dscl . list /Users UniqueID | awk '$2 >= 500 {print $1}'); do
        total_users=$((total_users + 1))
        local userHome
        userHome=$(dscl . read /Users/"$user" NFSHomeDirectory | sed 's/NFSHomeDirectory://' | grep "/" | sed 's/^[ \t]*//')
        
        if [[ "$(check_icloud_status "$userHome")" == "true" ]]; then
            icloud_users=$((icloud_users + 1))
        fi
    done
    
    cat >> "$analytics_report" << EOF
        "icloud": {
            "users_enabled": $icloud_users,
            "total_users": $total_users,
            "adoption_rate": $(awk "BEGIN {printf \"%.2f\", ($icloud_users/$total_users)*100}")
        }
    }
}
EOF

    echo "📊 Service usage analytics: $analytics_report"
}

Privacy Impact Assessment

#!/bin/bash

# Conduct privacy impact assessment
privacy_impact_assessment() {
    local assessment_type="${1:-standard}"
    
    echo "=== Privacy Impact Assessment ==="
    log_action "Starting privacy impact assessment: $assessment_type"
    
    local pia_report="$REPORTS_DIR/privacy_assessment_$(date '+%Y%m%d_%H%M%S').json"
    
    cat > "$pia_report" << EOF
{
    "assessment_metadata": {
        "timestamp": "$(date -Iseconds)",
        "assessment_type": "$assessment_type",
        "hostname": "$(hostname)"
    },
    "privacy_risks": [
EOF

    local risks=()
    
    # Check for data synchronization risks
    local sync_users
    sync_users=$(discover_apple_ids | jq -r '.user_accounts[] | select(.services.icloud.enabled == true) | .username' | wc -l)
    
    if [[ $sync_users -gt 0 ]]; then
        risks+=("Data synchronization to iCloud enabled for $sync_users users")
    fi
    
    # Check for location services
    if pgrep -f "locationd" >/dev/null; then
        risks+=("Location services active - potential privacy concern")
    fi
    
    # Add risks to report
    local first=true
    for risk in "${risks[@]}"; do
        if [[ "$first" == true ]]; then
            first=false
        else
            echo "," >> "$pia_report"
        fi
        echo "        \"$risk\"" >> "$pia_report"
    done
    
    cat >> "$pia_report" << EOF
    ],
    "recommendations": [
        "Implement data governance policies",
        "Configure privacy controls",
        "Regular privacy audits"
    ]
}
EOF

    log_action "✅ Privacy impact assessment completed: $pia_report"
    echo "$pia_report"
}

Best Practices

🚀 Identity Management

  • Regular discovery scans to track Apple ID usage across fleet
  • Centralized policy enforcement for consistent privacy controls
  • Automated monitoring for unauthorized Apple ID changes
  • Comprehensive audit trails for compliance and security

🔐 Security Guidelines

  • Privacy policy enforcement based on organizational requirements
  • Data minimization principles for sensitive environments
  • Access controls for Apple service configurations
  • Regular security assessments of identity management practices

📋 Compliance Management

  • Framework-specific policies (HIPAA, GDPR, SOX, FERPA)
  • Regular compliance reporting with automated assessment
  • Risk-based approach to identity management
  • Documentation and audit trails for regulatory requirements

🔍 Monitoring and Maintenance

  • Continuous monitoring of Apple ID status and service usage
  • Change detection with automated alerting
  • Regular backup of identity configurations
  • Performance optimization for large-scale deployments

Important Notes

  • Privacy compliance requires careful balance between functionality and data protection
  • User consent may be required for certain monitoring activities
  • Apple ID management should align with organizational privacy policies
  • Regular updates needed as Apple introduces new services and privacy features
  • Legal considerations vary by jurisdiction and industry sector

App Store Inventory Management on macOS

Efficiently manage and track App Store applications across your MacFleet devices with comprehensive inventory tools. This tutorial covers app discovery, license compliance, usage analytics, and enterprise-grade reporting for Mac App Store applications.

Understanding App Store App Management

App Store applications on macOS contain unique identifiers and receipts that enable enterprise tracking:

Core Components

  • MAS Receipts - Digital receipts stored in app bundles for verification
  • Bundle Identifiers - Unique app identification across the App Store ecosystem
  • Version Tracking - App version management and update compliance
  • License Management - Enterprise license allocation and compliance monitoring
  • Usage Analytics - Application usage patterns and adoption metrics

Enterprise Benefits

  • Software Asset Management - Complete inventory of App Store applications
  • License Compliance - Track enterprise app licenses and allocations
  • Security Monitoring - Identify unauthorized or non-compliant applications
  • Cost Optimization - Optimize App Store spending and license utilization
  • Policy Enforcement - Ensure compliance with enterprise app policies

Basic App Store App Discovery

Simple App Store App List

#!/bin/bash

# Basic App Store app discovery
echo "📱 Discovering App Store Applications"
echo "===================================="
echo ""

app_store_apps=$(find /Applications -path '*Contents/_MASReceipt/receipt' -maxdepth 4 -print | \
    sed 's#.app/Contents/_MASReceipt/receipt#.app#g; s#/Applications/##')

if [[ -n "$app_store_apps" ]]; then
    echo "App Store Applications Found:"
    echo "$app_store_apps" | sort
    
    local app_count=$(echo "$app_store_apps" | wc -l | xargs)
    echo ""
    echo "Total App Store apps: $app_count"
else
    echo "No App Store applications found in /Applications"
fi

Enhanced App Discovery with Details

#!/bin/bash

# Comprehensive App Store app discovery with metadata
discover_app_store_apps() {
    echo "🔍 Comprehensive App Store App Discovery"
    echo "======================================="
    echo ""
    
    local apps_found=0
    local total_size=0
    
    # Find all App Store apps with receipts
    while IFS= read -r -d '' app_path; do
        if [[ -n "$app_path" ]]; then
            local app_name=$(basename "$app_path" .app)
            local app_bundle_id=""
            local app_version=""
            local app_size=""
            local install_date=""
            
            # Get bundle identifier
            if [[ -f "$app_path/Contents/Info.plist" ]]; then
                app_bundle_id=$(defaults read "$app_path/Contents/Info.plist" CFBundleIdentifier 2>/dev/null || echo "Unknown")
                app_version=$(defaults read "$app_path/Contents/Info.plist" CFBundleShortVersionString 2>/dev/null || echo "Unknown")
            fi
            
            # Get app size
            if [[ -d "$app_path" ]]; then
                app_size=$(du -sh "$app_path" 2>/dev/null | cut -f1 || echo "Unknown")
                # Convert size to bytes for totaling
                local size_bytes=$(du -s "$app_path" 2>/dev/null | cut -f1 || echo "0")
                total_size=$((total_size + size_bytes))
            fi
            
            # Get installation/modification date
            if [[ -f "$app_path/Contents/_MASReceipt/receipt" ]]; then
                install_date=$(stat -f "%Sm" -t "%Y-%m-%d %H:%M:%S" "$app_path/Contents/_MASReceipt/receipt" 2>/dev/null || echo "Unknown")
            fi
            
            echo "App: $app_name"
            echo "  Bundle ID: $app_bundle_id"
            echo "  Version: $app_version"
            echo "  Size: $app_size"
            echo "  Install Date: $install_date"
            echo "  Path: $app_path"
            echo ""
            
            ((apps_found++))
        fi
    done < <(find /Applications -name "*.app" -path '*Contents/_MASReceipt/receipt' -exec dirname {} \; 2>/dev/null | \
             sed 's|/Contents/_MASReceipt||' | sort -u | tr '\n' '\0')
    
    # Summary statistics
    echo "=== Discovery Summary ==="
    echo "Total App Store apps found: $apps_found"
    echo "Total disk space used: $(echo "scale=2; $total_size / 1024 / 1024" | bc 2>/dev/null || echo "Unknown") MB"
    echo "Average app size: $(echo "scale=2; $total_size / $apps_found / 1024 / 1024" | bc 2>/dev/null || echo "Unknown") MB"
    echo "Scan completed: $(date)"
    
    return $apps_found
}

# Execute discovery
discover_app_store_apps

Enterprise App Inventory Management

Comprehensive App Inventory Script

#!/bin/bash

# Enterprise App Store inventory management
generate_app_store_inventory() {
    local output_format="${1:-json}"
    local include_metadata="${2:-true}"
    local export_path="${3:-/tmp}"
    
    echo "📊 Generating Enterprise App Store Inventory"
    echo "==========================================="
    echo "Output format: $output_format"
    echo "Include metadata: $include_metadata"
    echo ""
    
    local timestamp=$(date +"%Y%m%d_%H%M%S")
    local hostname=$(hostname)
    local report_file="$export_path/app_store_inventory_${hostname}_${timestamp}"
    
    # System information
    local device_info=$(system_profiler SPHardwareDataType | grep -E "(Model Name|Serial Number)" | \
                        awk -F': ' '{print $2}' | xargs | tr ' ' '_')
    local macos_version=$(sw_vers -productVersion)
    local current_user=$(stat -f%Su /dev/console 2>/dev/null || echo "$USER")
    
    # Initialize inventory data structure
    local inventory_data=""
    local app_count=0
    local total_size_bytes=0
    
    echo "Scanning applications..."
    
    # Discover all App Store applications
    while IFS= read -r -d '' app_path; do
        if [[ -d "$app_path" && -f "$app_path/Contents/_MASReceipt/receipt" ]]; then
            local app_name=$(basename "$app_path" .app)
            local bundle_id=""
            local version=""
            local build_version=""
            local size_bytes=0
            local size_human=""
            local install_date=""
            local last_modified=""
            local executable_path=""
            local app_category=""
            local developer_name=""
            local app_store_url=""
            
            # Extract app metadata
            if [[ -f "$app_path/Contents/Info.plist" ]]; then
                bundle_id=$(defaults read "$app_path/Contents/Info.plist" CFBundleIdentifier 2>/dev/null || echo "unknown")
                version=$(defaults read "$app_path/Contents/Info.plist" CFBundleShortVersionString 2>/dev/null || echo "unknown")
                build_version=$(defaults read "$app_path/Contents/Info.plist" CFBundleVersion 2>/dev/null || echo "unknown")
                executable_path=$(defaults read "$app_path/Contents/Info.plist" CFBundleExecutable 2>/dev/null || echo "unknown")
                app_category=$(defaults read "$app_path/Contents/Info.plist" LSApplicationCategoryType 2>/dev/null || echo "unknown")
            fi
            
            # Get app size
            size_bytes=$(du -sk "$app_path" 2>/dev/null | cut -f1 || echo "0")
            size_bytes=$((size_bytes * 1024))  # Convert KB to bytes
            size_human=$(du -sh "$app_path" 2>/dev/null | cut -f1 || echo "unknown")
            total_size_bytes=$((total_size_bytes + size_bytes))
            
            # Get timestamps
            install_date=$(stat -f "%Sm" -t "%Y-%m-%d %H:%M:%S" "$app_path/Contents/_MASReceipt/receipt" 2>/dev/null || echo "unknown")
            last_modified=$(stat -f "%Sm" -t "%Y-%m-%d %H:%M:%S" "$app_path" 2>/dev/null || echo "unknown")
            
            # Try to extract additional metadata if requested
            if [[ "$include_metadata" == "true" ]]; then
                # Look for team identifier
                local team_id=""
                if command -v codesign >/dev/null 2>&1; then
                    team_id=$(codesign -dv "$app_path" 2>&1 | grep "TeamIdentifier" | awk -F'=' '{print $2}' || echo "unknown")
                fi
                
                # Check if app is running
                local is_running="false"
                if pgrep -f "$app_name" >/dev/null 2>&1; then
                    is_running="true"
                fi
                
                # Get app permissions (simplified check)
                local has_camera_permission="unknown"
                local has_microphone_permission="unknown"
                local has_location_permission="unknown"
                
                if [[ -f "$app_path/Contents/Info.plist" ]]; then
                    if defaults read "$app_path/Contents/Info.plist" NSCameraUsageDescription >/dev/null 2>&1; then
                        has_camera_permission="requested"
                    else
                        has_camera_permission="not_requested"
                    fi
                    
                    if defaults read "$app_path/Contents/Info.plist" NSMicrophoneUsageDescription >/dev/null 2>&1; then
                        has_microphone_permission="requested"
                    else
                        has_microphone_permission="not_requested"
                    fi
                    
                    if defaults read "$app_path/Contents/Info.plist" NSLocationUsageDescription >/dev/null 2>&1; then
                        has_location_permission="requested"
                    else
                        has_location_permission="not_requested"
                    fi
                fi
            fi
            
            # Format output based on requested format
            case "$output_format" in
                "json")
                    local app_json="{
                        \"app_name\": \"$app_name\",
                        \"bundle_id\": \"$bundle_id\",
                        \"version\": \"$version\",
                        \"build_version\": \"$build_version\",
                        \"size_bytes\": $size_bytes,
                        \"size_human\": \"$size_human\",
                        \"install_date\": \"$install_date\",
                        \"last_modified\": \"$last_modified\",
                        \"app_path\": \"$app_path\",
                        \"executable_path\": \"$executable_path\",
                        \"category\": \"$app_category\""
                    
                    if [[ "$include_metadata" == "true" ]]; then
                        app_json="$app_json,
                        \"team_id\": \"$team_id\",
                        \"is_running\": $is_running,
                        \"camera_permission\": \"$has_camera_permission\",
                        \"microphone_permission\": \"$has_microphone_permission\",
                        \"location_permission\": \"$has_location_permission\""
                    fi
                    
                    app_json="$app_json}"
                    
                    if [[ $app_count -gt 0 ]]; then
                        inventory_data="$inventory_data,$app_json"
                    else
                        inventory_data="$app_json"
                    fi
                    ;;
                    
                "csv")
                    if [[ $app_count -eq 0 ]]; then
                        # CSV header
                        if [[ "$include_metadata" == "true" ]]; then
                            inventory_data="App Name,Bundle ID,Version,Build Version,Size (Bytes),Size (Human),Install Date,Last Modified,App Path,Category,Team ID,Is Running,Camera Permission,Microphone Permission,Location Permission"
                        else
                            inventory_data="App Name,Bundle ID,Version,Build Version,Size (Bytes),Size (Human),Install Date,Last Modified,App Path,Category"
                        fi
                    fi
                    
                    local csv_line="\"$app_name\",\"$bundle_id\",\"$version\",\"$build_version\",$size_bytes,\"$size_human\",\"$install_date\",\"$last_modified\",\"$app_path\",\"$app_category\""
                    
                    if [[ "$include_metadata" == "true" ]]; then
                        csv_line="$csv_line,\"$team_id\",$is_running,\"$has_camera_permission\",\"$has_microphone_permission\",\"$has_location_permission\""
                    fi
                    
                    inventory_data="$inventory_data\n$csv_line"
                    ;;
                    
                "text"|*)
                    inventory_data="$inventory_data
App: $app_name
  Bundle ID: $bundle_id
  Version: $version ($build_version)
  Size: $size_human ($size_bytes bytes)
  Install Date: $install_date
  Last Modified: $last_modified
  Path: $app_path
  Category: $app_category"
                    
                    if [[ "$include_metadata" == "true" ]]; then
                        inventory_data="$inventory_data
  Team ID: $team_id
  Currently Running: $is_running
  Camera Permission: $has_camera_permission
  Microphone Permission: $has_microphone_permission
  Location Permission: $has_location_permission"
                    fi
                    
                    inventory_data="$inventory_data
"
                    ;;
            esac
            
            ((app_count++))
        fi
    done < <(find /Applications -name "*.app" -type d -print0 2>/dev/null)
    
    # Generate final report
    local total_size_human=$(echo "scale=2; $total_size_bytes / 1024 / 1024 / 1024" | bc 2>/dev/null || echo "unknown")
    
    case "$output_format" in
        "json")
            local final_report="{
                \"report_metadata\": {
                    \"timestamp\": \"$(date -u +"%Y-%m-%dT%H:%M:%SZ")\",
                    \"hostname\": \"$hostname\",
                    \"device_info\": \"$device_info\",
                    \"macos_version\": \"$macos_version\",
                    \"current_user\": \"$current_user\",
                    \"total_apps\": $app_count,
                    \"total_size_bytes\": $total_size_bytes,
                    \"total_size_gb\": \"$total_size_human GB\"
                },
                \"applications\": [$inventory_data]
            }"
            
            echo "$final_report" > "${report_file}.json"
            echo "✅ JSON report saved to: ${report_file}.json"
            ;;
            
        "csv")
            echo -e "$inventory_data" > "${report_file}.csv"
            echo "✅ CSV report saved to: ${report_file}.csv"
            ;;
            
        "text"|*)
            {
                echo "MacFleet App Store Inventory Report"
                echo "=================================="
                echo "Generated: $(date)"
                echo "Hostname: $hostname"
                echo "Device: $device_info"
                echo "macOS Version: $macos_version"
                echo "Current User: $current_user"
                echo "Total Apps: $app_count"
                echo "Total Size: $total_size_human GB"
                echo ""
                echo "Applications:"
                echo "============"
                echo "$inventory_data"
            } > "${report_file}.txt"
            echo "✅ Text report saved to: ${report_file}.txt"
            ;;
    esac
    
    # Summary output
    echo ""
    echo "=== Inventory Summary ==="
    echo "Apps discovered: $app_count"
    echo "Total size: $total_size_human GB"
    echo "Report format: $output_format"
    echo "Report location: $report_file"
    echo ""
    
    return $app_count
}

# Usage examples
echo "📊 Enterprise App Store Inventory Management"
echo ""
echo "1. Generate JSON inventory with metadata"
generate_app_store_inventory "json" "true" "/tmp"
echo ""

echo "2. Generate CSV inventory (basic)"
generate_app_store_inventory "csv" "false" "/tmp"
echo ""

echo "3. Generate text inventory with metadata"
generate_app_store_inventory "text" "true" "/tmp"

App Compliance and Security Analysis

#!/bin/bash

# App Store app compliance and security analysis
analyze_app_compliance() {
    echo "🔒 App Store Application Compliance Analysis"
    echo "==========================================="
    echo ""
    
    local compliance_issues=0
    local security_concerns=0
    local policy_violations=0
    
    # Define enterprise policy rules
    local blocked_apps=("Games" "Social Media" "Dating")  # Example categories
    local required_apps=("Microsoft Word" "Microsoft Excel" "Slack")  # Example required apps
    local max_app_age_days=365  # Apps older than 1 year flagged
    local min_security_permissions=("Camera" "Microphone" "Location")
    
    echo "Analyzing App Store applications for compliance..."
    echo ""
    
    # Track required apps
    local found_required_apps=()
    local missing_required_apps=()
    
    # Analyze each App Store application
    while IFS= read -r -d '' app_path; do
        if [[ -d "$app_path" && -f "$app_path/Contents/_MASReceipt/receipt" ]]; then
            local app_name=$(basename "$app_path" .app)
            local bundle_id=""
            local version=""
            local category=""
            local install_date=""
            local days_since_install=""
            
            echo "Analyzing: $app_name"
            
            # Get app metadata
            if [[ -f "$app_path/Contents/Info.plist" ]]; then
                bundle_id=$(defaults read "$app_path/Contents/Info.plist" CFBundleIdentifier 2>/dev/null || echo "unknown")
                version=$(defaults read "$app_path/Contents/Info.plist" CFBundleShortVersionString 2>/dev/null || echo "unknown")
                category=$(defaults read "$app_path/Contents/Info.plist" LSApplicationCategoryType 2>/dev/null || echo "unknown")
            fi
            
            # Get install date and calculate age
            if [[ -f "$app_path/Contents/_MASReceipt/receipt" ]]; then
                install_date=$(stat -f "%Sm" -t "%Y-%m-%d" "$app_path/Contents/_MASReceipt/receipt" 2>/dev/null || echo "unknown")
                if [[ "$install_date" != "unknown" ]]; then
                    local install_epoch=$(date -j -f "%Y-%m-%d" "$install_date" "+%s" 2>/dev/null || echo "0")
                    local current_epoch=$(date "+%s")
                    days_since_install=$(( (current_epoch - install_epoch) / 86400 ))
                fi
            fi
            
            # Check against blocked apps/categories
            local is_blocked=false
            for blocked_category in "${blocked_apps[@]}"; do
                if [[ "$category" =~ "$blocked_category" ]] || [[ "$app_name" =~ "$blocked_category" ]]; then
                    echo "  ❌ POLICY VIOLATION: App category '$category' is blocked"
                    is_blocked=true
                    ((policy_violations++))
                    break
                fi
            done
            
            # Check app age
            if [[ -n "$days_since_install" && "$days_since_install" -gt "$max_app_age_days" ]]; then
                echo "  ⚠️ COMPLIANCE: App is older than $max_app_age_days days ($days_since_install days)"
                ((compliance_issues++))
            fi
            
            # Check for security permissions
            local permission_count=0
            if [[ -f "$app_path/Contents/Info.plist" ]]; then
                if defaults read "$app_path/Contents/Info.plist" NSCameraUsageDescription >/dev/null 2>&1; then
                    echo "  🔒 SECURITY: App requests camera access"
                    ((permission_count++))
                fi
                
                if defaults read "$app_path/Contents/Info.plist" NSMicrophoneUsageDescription >/dev/null 2>&1; then
                    echo "  🔒 SECURITY: App requests microphone access"
                    ((permission_count++))
                fi
                
                if defaults read "$app_path/Contents/Info.plist" NSLocationUsageDescription >/dev/null 2>&1; then
                    echo "  🔒 SECURITY: App requests location access"
                    ((permission_count++))
                fi
                
                if [[ "$permission_count" -gt 2 ]]; then
                    echo "  ⚠️ SECURITY CONCERN: App requests multiple sensitive permissions"
                    ((security_concerns++))
                fi
            fi
            
            # Check against required apps
            for required_app in "${required_apps[@]}"; do
                if [[ "$app_name" =~ "$required_app" ]]; then
                    found_required_apps+=("$required_app")
                fi
            done
            
            # Code signing verification
            if command -v codesign >/dev/null 2>&1; then
                if ! codesign -v "$app_path" >/dev/null 2>&1; then
                    echo "  ❌ SECURITY: Invalid code signature"
                    ((security_concerns++))
                fi
            fi
            
            echo "  ✅ Analysis complete"
            echo ""
        fi
    done < <(find /Applications -name "*.app" -type d -print0 2>/dev/null)
    
    # Check for missing required apps
    for required_app in "${required_apps[@]}"; do
        local found=false
        for found_app in "${found_required_apps[@]}"; do
            if [[ "$found_app" == "$required_app" ]]; then
                found=true
                break
            fi
        done
        
        if [[ "$found" == "false" ]]; then
            missing_required_apps+=("$required_app")
        fi
    done
    
    # Generate compliance report
    echo "=== Compliance Analysis Report ==="
    echo "Policy violations: $policy_violations"
    echo "Compliance issues: $compliance_issues"
    echo "Security concerns: $security_concerns"
    echo ""
    
    if [[ ${#missing_required_apps[@]} -gt 0 ]]; then
        echo "Missing required applications:"
        for missing_app in "${missing_required_apps[@]}"; do
            echo "  - $missing_app"
        done
        echo ""
    fi
    
    if [[ ${#found_required_apps[@]} -gt 0 ]]; then
        echo "Found required applications:"
        for found_app in "${found_required_apps[@]}"; do
            echo "  ✅ $found_app"
        done
        echo ""
    fi
    
    # Overall compliance score
    local total_issues=$((policy_violations + compliance_issues + security_concerns + ${#missing_required_apps[@]}))
    if [[ "$total_issues" -eq 0 ]]; then
        echo "🎉 COMPLIANCE STATUS: FULLY COMPLIANT"
    elif [[ "$total_issues" -le 3 ]]; then
        echo "⚠️ COMPLIANCE STATUS: MINOR ISSUES ($total_issues issues)"
    else
        echo "❌ COMPLIANCE STATUS: MAJOR ISSUES ($total_issues issues)"
    fi
    
    return $total_issues
}

# Execute compliance analysis
analyze_app_compliance

Fleet Management and Reporting

Enterprise Fleet App Management

#!/bin/bash

# Enterprise fleet-wide App Store management
manage_fleet_app_inventory() {
    local operation="${1:-discover}"  # discover, report, compliance, update
    local fleet_config_file="${2:-/etc/macfleet/app_config.json}"
    local output_dir="${3:-/var/log/macfleet}"
    
    echo "🚀 MacFleet Enterprise App Store Management"
    echo "=========================================="
    echo "Operation: $operation"
    echo "Config file: $fleet_config_file"
    echo "Output directory: $output_dir"
    echo ""
    
    # Ensure output directory exists
    mkdir -p "$output_dir"
    
    # Device identification
    local device_id=$(system_profiler SPHardwareDataType | grep "Serial Number" | awk -F': ' '{print $2}' | xargs)
    local device_name=$(hostname)
    local timestamp=$(date +"%Y%m%d_%H%M%S")
    local report_file="$output_dir/fleet_app_report_${device_id}_${timestamp}.json"
    
    case "$operation" in
        "discover")
            echo "🔍 Fleet App Discovery Mode"
            echo "==========================="
            
            # Generate comprehensive app inventory
            local app_data=$(generate_comprehensive_app_data)
            
            # Create fleet report
            local fleet_report="{
                \"device_info\": {
                    \"device_id\": \"$device_id\",
                    \"device_name\": \"$device_name\",
                    \"timestamp\": \"$(date -u +"%Y-%m-%dT%H:%M:%SZ")\",
                    \"macos_version\": \"$(sw_vers -productVersion)\",
                    \"current_user\": \"$(stat -f%Su /dev/console 2>/dev/null || echo "$USER")\"
                },
                \"app_inventory\": $app_data,
                \"operation\": \"fleet_discovery\"
            }"
            
            echo "$fleet_report" > "$report_file"
            echo "✅ Fleet discovery report saved: $report_file"
            ;;
            
        "compliance")
            echo "📋 Fleet Compliance Check"
            echo "========================="
            
            # Run compliance analysis
            local compliance_result=$(analyze_fleet_compliance)
            
            # Create compliance report
            local compliance_report="{
                \"device_info\": {
                    \"device_id\": \"$device_id\",
                    \"device_name\": \"$device_name\",
                    \"timestamp\": \"$(date -u +"%Y-%m-%dT%H:%M:%SZ")\"
                },
                \"compliance_results\": $compliance_result,
                \"operation\": \"compliance_check\"
            }"
            
            echo "$compliance_report" > "$report_file"
            echo "✅ Compliance report saved: $report_file"
            ;;
            
        "report")
            echo "📊 Fleet Reporting Mode"
            echo "======================"
            
            # Generate all report formats
            echo "Generating comprehensive fleet reports..."
            
            generate_app_store_inventory "json" "true" "$output_dir"
            generate_app_store_inventory "csv" "true" "$output_dir"
            generate_app_store_inventory "text" "true" "$output_dir"
            
            echo "✅ All fleet reports generated in: $output_dir"
            ;;
            
        "update")
            echo "🔄 Fleet Update Check"
            echo "===================="
            
            # Check for app updates
            check_app_store_updates
            ;;
            
        *)
            echo "❌ Unknown operation: $operation"
            echo "Available operations: discover, report, compliance, update"
            return 1
            ;;
    esac
    
    return 0
}

# Helper function to generate comprehensive app data
generate_comprehensive_app_data() {
    local apps_json="["
    local first_app=true
    
    while IFS= read -r -d '' app_path; do
        if [[ -d "$app_path" && -f "$app_path/Contents/_MASReceipt/receipt" ]]; then
            local app_name=$(basename "$app_path" .app)
            local bundle_id=$(defaults read "$app_path/Contents/Info.plist" CFBundleIdentifier 2>/dev/null || echo "unknown")
            local version=$(defaults read "$app_path/Contents/Info.plist" CFBundleShortVersionString 2>/dev/null || echo "unknown")
            local size_bytes=$(du -sk "$app_path" 2>/dev/null | cut -f1 || echo "0")
            size_bytes=$((size_bytes * 1024))
            
            if [[ "$first_app" == "false" ]]; then
                apps_json="$apps_json,"
            fi
            
            apps_json="$apps_json{
                \"name\": \"$app_name\",
                \"bundle_id\": \"$bundle_id\",
                \"version\": \"$version\",
                \"size_bytes\": $size_bytes,
                \"path\": \"$app_path\"
            }"
            
            first_app=false
        fi
    done < <(find /Applications -name "*.app" -type d -print0 2>/dev/null)
    
    apps_json="$apps_json]"
    echo "$apps_json"
}

# Check for App Store updates
check_app_store_updates() {
    echo "Checking for available App Store updates..."
    
    # Use softwareupdate to check for available updates
    local updates_available=$(softwareupdate -l 2>/dev/null | grep -i "app store" || echo "")
    
    if [[ -n "$updates_available" ]]; then
        echo "📦 App Store updates available:"
        echo "$updates_available"
    else
        echo "✅ All App Store apps are up to date"
    fi
    
    # Also check Mac App Store directly if available
    if command -v mas >/dev/null 2>&1; then
        echo ""
        echo "Checking with mas-cli..."
        mas outdated 2>/dev/null || echo "mas-cli not available or no updates found"
    fi
}

# Usage examples
echo "Fleet Management Examples:"
echo "========================="
echo ""

echo "1. Discovery mode:"
manage_fleet_app_inventory "discover"
echo ""

echo "2. Compliance check:"
manage_fleet_app_inventory "compliance"
echo ""

echo "3. Generate all reports:"
manage_fleet_app_inventory "report"

App Store Connect Integration

Enterprise App Management with App Store Connect

#!/bin/bash

# Enterprise App Store Connect integration for license management
manage_app_store_licenses() {
    echo "📄 App Store Connect License Management"
    echo "======================================"
    echo ""
    
    # Note: This requires enterprise App Store Connect access
    # and proper API credentials configuration
    
    local license_report_file="/tmp/app_store_licenses_$(date +%Y%m%d_%H%M%S).json"
    
    echo "Analyzing App Store app licensing..."
    echo ""
    
    # Track apps that may require business licenses
    local business_apps=()
    local consumer_apps=()
    local unknown_apps=()
    
    while IFS= read -r -d '' app_path; do
        if [[ -d "$app_path" && -f "$app_path/Contents/_MASReceipt/receipt" ]]; then
            local app_name=$(basename "$app_path" .app)
            local bundle_id=$(defaults read "$app_path/Contents/Info.plist" CFBundleIdentifier 2>/dev/null || echo "unknown")
            
            # Categories that typically require business licenses
            local business_categories=("Developer Tools" "Business" "Productivity" "Graphics & Design")
            local is_business_app=false
            
            # Check if app is business-oriented
            if [[ -f "$app_path/Contents/Info.plist" ]]; then
                local category=$(defaults read "$app_path/Contents/Info.plist" LSApplicationCategoryType 2>/dev/null || echo "unknown")
                
                for biz_cat in "${business_categories[@]}"; do
                    if [[ "$category" =~ "$biz_cat" ]]; then
                        is_business_app=true
                        break
                    fi
                done
                
                # Also check common business app patterns
                if [[ "$app_name" =~ (Microsoft|Adobe|Slack|Zoom|Teams|Office) ]]; then
                    is_business_app=true
                fi
            fi
            
            if [[ "$is_business_app" == "true" ]]; then
                business_apps+=("$app_name ($bundle_id)")
                echo "💼 Business app detected: $app_name"
            else
                # Consumer apps that might be acceptable
                if [[ "$app_name" =~ (Calculator|TextEdit|Safari|Mail|Photos) ]]; then
                    consumer_apps+=("$app_name ($bundle_id)")
                    echo "👤 Consumer app: $app_name"
                else
                    unknown_apps+=("$app_name ($bundle_id)")
                    echo "❓ Unknown category: $app_name"
                fi
            fi
        fi
    done < <(find /Applications -name "*.app" -type d -print0 2>/dev/null)
    
    # Generate license compliance report
    {
        echo "{"
        echo "  \"license_analysis\": {"
        echo "    \"timestamp\": \"$(date -u +"%Y-%m-%dT%H:%M:%SZ")\","
        echo "    \"device_id\": \"$(system_profiler SPHardwareDataType | grep "Serial Number" | awk -F': ' '{print $2}' | xargs)\","
        echo "    \"business_apps\": ["
        
        local first=true
        for app in "${business_apps[@]}"; do
            if [[ "$first" == "false" ]]; then echo ","; fi
            echo "      \"$app\""
            first=false
        done
        
        echo "    ],"
        echo "    \"consumer_apps\": ["
        
        first=true
        for app in "${consumer_apps[@]}"; do
            if [[ "$first" == "false" ]]; then echo ","; fi
            echo "      \"$app\""
            first=false
        done
        
        echo "    ],"
        echo "    \"unknown_apps\": ["
        
        first=true
        for app in "${unknown_apps[@]}"; do
            if [[ "$first" == "false" ]]; then echo ","; fi
            echo "      \"$app\""
            first=false
        done
        
        echo "    ],"
        echo "    \"summary\": {"
        echo "      \"total_business_apps\": ${#business_apps[@]},"
        echo "      \"total_consumer_apps\": ${#consumer_apps[@]},"
        echo "      \"total_unknown_apps\": ${#unknown_apps[@]},"
        echo "      \"requires_license_review\": $([[ ${#business_apps[@]} -gt 0 || ${#unknown_apps[@]} -gt 0 ]] && echo "true" || echo "false")"
        echo "    }"
        echo "  }"
        echo "}"
    } > "$license_report_file"
    
    echo ""
    echo "=== License Analysis Summary ==="
    echo "Business apps found: ${#business_apps[@]}"
    echo "Consumer apps found: ${#consumer_apps[@]}"
    echo "Unknown apps found: ${#unknown_apps[@]}"
    echo ""
    
    if [[ ${#business_apps[@]} -gt 0 || ${#unknown_apps[@]} -gt 0 ]]; then
        echo "⚠️ License review required for business/unknown applications"
        echo "📄 License report saved: $license_report_file"
    else
        echo "✅ No business licensing concerns detected"
    fi
    
    return 0
}

# Execute license management
manage_app_store_licenses

Important Notes

Enterprise Management Features

  • Comprehensive Inventory - Complete App Store application discovery and tracking
  • Compliance Monitoring - Policy enforcement and security analysis
  • License Management - Enterprise App Store Connect integration
  • Fleet Reporting - Multi-format reporting (JSON, CSV, text) with metadata
  • Security Analysis - Permission auditing and code signature verification
  • Update Management - App Store update detection and management

App Store Receipt System

  • MAS Receipts - Digital proof of App Store purchase located in Contents/_MASReceipt/receipt
  • Bundle Identification - Unique app tracking via CFBundleIdentifier
  • Version Tracking - App version and build number management
  • Installation Metadata - Install date and modification tracking
  • License Verification - Enterprise license compliance and allocation

Security and Compliance

  • Permission Auditing - Camera, microphone, location access monitoring
  • Code Signature Verification - Validate app integrity and authenticity
  • Policy Enforcement - Blocked app categories and required app validation
  • Age Analysis - Identify outdated applications requiring updates
  • Team Identifier Tracking - Developer team identification for enterprise policies

Usage Examples

# Basic App Store app discovery
find /Applications -path '*Contents/_MASReceipt/receipt' -maxdepth 4 -print | \
    sed 's#.app/Contents/_MASReceipt/receipt#.app#g; s#/Applications/##'

# Enterprise inventory with JSON output
generate_app_store_inventory "json" "true" "/tmp"

# Compliance analysis
analyze_app_compliance

# Fleet management - discovery mode
manage_fleet_app_inventory "discover"

# License management
manage_app_store_licenses

App Store Auto Updates Management on macOS

Control and manage App Store automatic updates on your MacFleet devices to optimize bandwidth usage, manage security updates, and maintain system stability. This tutorial covers update policies, enterprise configuration, and comprehensive update management strategies.

Understanding macOS App Store Auto Updates

App Store auto updates on macOS automatically download and install application updates from the Mac App Store. This feature affects:

  • Application Updates - Automatic installation of app updates
  • System Storage - Downloaded updates consume disk space
  • Network Bandwidth - Updates download in the background
  • System Stability - New updates may introduce bugs or compatibility issues

Enterprise Considerations

Managing auto updates is crucial for enterprise environments:

  • Bandwidth Control - Prevent unexpected network usage
  • Security Management - Control when security updates are applied
  • System Stability - Test updates before deployment
  • Storage Management - Prevent storage issues on limited-space devices
  • Compliance Requirements - Some industries require controlled update deployment

Basic App Store Update Control

Disable Auto Updates

#!/bin/bash

# Disable App Store auto updates
sudo defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool FALSE

echo "App Store auto updates disabled"
exit 0

Enable Auto Updates

#!/bin/bash

# Enable App Store auto updates
sudo defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool TRUE

echo "App Store auto updates enabled"
exit 0

Check Current Auto Update Status

#!/bin/bash

# Check current auto update setting
auto_update_status=$(defaults read /Library/Preferences/com.apple.commerce.plist AutoUpdate 2>/dev/null || echo "Not Set")

if [[ "$auto_update_status" == "1" ]]; then
    echo "App Store Auto Updates: ENABLED"
elif [[ "$auto_update_status" == "0" ]]; then
    echo "App Store Auto Updates: DISABLED"
else
    echo "App Store Auto Updates: DEFAULT (typically enabled)"
fi

Advanced Update Management

Comprehensive Update Policy Configuration

#!/bin/bash

# Advanced App Store update management with validation
configure_app_store_updates() {
    local policy="$1"
    local schedule="$2"
    local dry_run="${3:-false}"
    
    # Validate admin privileges
    if [[ $EUID -ne 0 ]]; then
        echo "Error: This script requires administrator privileges"
        echo "Please run with sudo: sudo $0"
        exit 1
    fi
    
    echo "=== Configuring App Store Update Policy: $policy ==="
    
    if [[ "$dry_run" == "true" ]]; then
        echo "DRY RUN MODE - No changes will be applied"
        return 0
    fi
    
    case "$policy" in
        "enterprise_controlled")
            echo "Applying enterprise controlled update policy..."
            
            # Disable auto updates for controlled environment
            defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool FALSE
            
            # Disable automatic download of updates
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload -bool FALSE
            
            # Disable critical updates installation
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist CriticalUpdateInstall -bool FALSE
            
            echo "✓ Enterprise controlled policy applied"
            ;;
        "security_only")
            echo "Applying security-only update policy..."
            
            # Disable general app updates
            defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool FALSE
            
            # Enable critical security updates only
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist CriticalUpdateInstall -bool TRUE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload -bool TRUE
            
            echo "✓ Security-only update policy applied"
            ;;
        "scheduled_updates")
            echo "Applying scheduled update policy..."
            
            # Disable immediate updates
            defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool FALSE
            
            # Configure scheduled update checking
            setup_scheduled_updates "$schedule"
            
            echo "✓ Scheduled update policy applied"
            ;;
        "bandwidth_conscious")
            echo "Applying bandwidth-conscious update policy..."
            
            # Disable automatic downloads
            defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool FALSE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload -bool FALSE
            
            # Enable update checking but not automatic installation
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticCheckEnabled -bool TRUE
            
            echo "✓ Bandwidth-conscious policy applied"
            ;;
        "full_auto")
            echo "Applying full automatic update policy..."
            
            # Enable all automatic updates
            defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool TRUE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload -bool TRUE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticCheckEnabled -bool TRUE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist CriticalUpdateInstall -bool TRUE
            
            echo "✓ Full automatic update policy applied"
            ;;
        "disabled")
            echo "Disabling all automatic updates..."
            
            # Disable all automatic update features
            defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool FALSE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload -bool FALSE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticCheckEnabled -bool FALSE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist CriticalUpdateInstall -bool FALSE
            
            echo "✓ All automatic updates disabled"
            ;;
        *)
            echo "Error: Unknown policy '$policy'"
            echo "Available policies: enterprise_controlled, security_only, scheduled_updates, bandwidth_conscious, full_auto, disabled"
            return 1
            ;;
    esac
    
    # Verify configuration
    verify_update_settings
}

# Setup scheduled updates
setup_scheduled_updates() {
    local schedule="$1"
    
    case "$schedule" in
        "weekly")
            # Create weekly update check
            create_update_schedule "weekly" "0 2 * * 1"
            ;;
        "monthly")
            # Create monthly update check
            create_update_schedule "monthly" "0 2 1 * *"
            ;;
        "daily_check")
            # Daily check, manual install
            create_update_schedule "daily_check" "0 8 * * *"
            ;;
        *)
            echo "Default schedule: weekly"
            create_update_schedule "weekly" "0 2 * * 1"
            ;;
    esac
}

# Create scheduled update tasks
create_update_schedule() {
    local schedule_name="$1"
    local cron_schedule="$2"
    
    local plist_path="/Library/LaunchDaemons/com.macfleet.updatecheck.plist"
    
    cat > "$plist_path" << EOF
<?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>Label</key>
    <string>com.macfleet.updatecheck</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/bin/python3</string>
        <string>/usr/local/bin/macfleet_update_checker.py</string>
    </array>
    <key>StartCalendarInterval</key>
    <dict>
        <key>Hour</key>
        <integer>2</integer>
        <key>Minute</key>
        <integer>0</integer>
        <key>Weekday</key>
        <integer>1</integer>
    </dict>
    <key>RunAtLoad</key>
    <false/>
</dict>
</plist>
EOF
    
    # Set proper permissions
    chown root:wheel "$plist_path"
    chmod 644 "$plist_path"
    
    echo "✓ Scheduled update check created: $schedule_name"
}

# Verify current update settings
verify_update_settings() {
    echo ""
    echo "=== Current Update Configuration ==="
    
    # Check App Store auto updates
    local app_store_auto=$(defaults read /Library/Preferences/com.apple.commerce.plist AutoUpdate 2>/dev/null || echo "Default")
    echo "App Store Auto Updates: $([ "$app_store_auto" == "1" ] && echo "Enabled" || [ "$app_store_auto" == "0" ] && echo "Disabled" || echo "Default (Enabled)")"
    
    # Check Software Update settings
    local auto_download=$(defaults read /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload 2>/dev/null || echo "Default")
    echo "Automatic Download: $([ "$auto_download" == "1" ] && echo "Enabled" || [ "$auto_download" == "0" ] && echo "Disabled" || echo "Default")"
    
    local auto_check=$(defaults read /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticCheckEnabled 2>/dev/null || echo "Default")
    echo "Automatic Check: $([ "$auto_check" == "1" ] && echo "Enabled" || [ "$auto_check" == "0" ] && echo "Disabled" || echo "Default")"
    
    local critical_updates=$(defaults read /Library/Preferences/com.apple.SoftwareUpdate.plist CriticalUpdateInstall 2>/dev/null || echo "Default")
    echo "Critical Updates: $([ "$critical_updates" == "1" ] && echo "Enabled" || [ "$critical_updates" == "0" ] && echo "Disabled" || echo "Default")"
}

# Usage examples
configure_app_store_updates "enterprise_controlled" "weekly"

Update Monitoring and Reporting

#!/bin/bash

# Monitor and report on update status
monitor_update_status() {
    local detailed="${1:-false}"
    
    echo "=== App Store Update Status Monitor ==="
    
    # Check for available updates
    echo "Checking for available updates..."
    local available_updates
    available_updates=$(softwareupdate -l 2>/dev/null | grep -c "recommended" || echo "0")
    
    echo "Available Updates: $available_updates"
    
    # Check last update check time
    local last_check
    last_check=$(defaults read /Library/Preferences/com.apple.SoftwareUpdate.plist LastSuccessfulDate 2>/dev/null || echo "Unknown")
    echo "Last Update Check: $last_check"
    
    # Check update history
    if [[ "$detailed" == "true" ]]; then
        echo ""
        echo "=== Detailed Update Information ==="
        
        # List available updates
        echo "Available Updates:"
        softwareupdate -l 2>/dev/null | grep -A 3 "recommended" || echo "No updates available"
        
        # Check update download cache
        local cache_size
        cache_size=$(du -sh /Library/Updates 2>/dev/null | cut -f1 || echo "0B")
        echo "Update Cache Size: $cache_size"
        
        # Check system version
        echo "Current System Version: $(sw_vers -productVersion)"
        echo "Build Version: $(sw_vers -buildVersion)"
    fi
}

# Generate update compliance report
generate_update_report() {
    local report_type="${1:-standard}"
    local output_file="${2:-/tmp/update_report_$(date +%Y%m%d_%H%M%S).json}"
    
    echo "=== Generating Update Report: $report_type ==="
    
    # Collect update information
    local hostname=$(hostname)
    local system_version=$(sw_vers -productVersion)
    local build_version=$(sw_vers -buildVersion)
    local app_store_auto=$(defaults read /Library/Preferences/com.apple.commerce.plist AutoUpdate 2>/dev/null || echo "default")
    local auto_download=$(defaults read /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload 2>/dev/null || echo "default")
    local last_check=$(defaults read /Library/Preferences/com.apple.SoftwareUpdate.plist LastSuccessfulDate 2>/dev/null || echo "unknown")
    
    # Get available updates list
    local available_updates
    available_updates=$(softwareupdate -l 2>/dev/null | grep "recommended" | wc -l | tr -d ' ')
    
    cat > "$output_file" << EOF
{
    "update_report": {
        "report_type": "$report_type",
        "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
        "hostname": "$hostname",
        "system_info": {
            "system_version": "$system_version",
            "build_version": "$build_version"
        },
        "update_settings": {
            "app_store_auto_update": "$app_store_auto",
            "automatic_download": "$auto_download",
            "last_update_check": "$last_check"
        },
        "update_status": {
            "available_updates": $available_updates,
            "pending_restarts": false
        }
    }
}
EOF
    
    echo "✓ Update report generated: $output_file"
    echo "$output_file"
}

# Usage
monitor_update_status "true"
generate_update_report "compliance"

Enterprise App Store Update Management System

#!/bin/bash

# MacFleet App Store Update Management Tool
# Comprehensive update policy management and monitoring for fleet devices

# Configuration
SCRIPT_VERSION="1.0.0"
LOG_FILE="/var/log/macfleet_appstore_updates.log"
REPORT_DIR="/etc/macfleet/reports/updates"
CONFIG_DIR="/etc/macfleet/updates"
POLICY_DIR="/etc/macfleet/policies/updates"

# Create directories if they don't exist
mkdir -p "$REPORT_DIR" "$CONFIG_DIR" "$POLICY_DIR"

# Update policy templates
declare -A UPDATE_POLICIES=(
    ["enterprise_strict"]="app_updates_disabled,system_updates_manual,security_updates_auto,bandwidth_priority_high"
    ["enterprise_balanced"]="app_updates_scheduled,system_updates_auto,security_updates_immediate,bandwidth_priority_medium"
    ["enterprise_liberal"]="app_updates_auto,system_updates_auto,security_updates_immediate,bandwidth_priority_low"
    ["kiosk_mode"]="app_updates_disabled,system_updates_disabled,security_updates_manual,bandwidth_priority_high"
    ["development"]="app_updates_auto,system_updates_prompt,security_updates_auto,bandwidth_priority_low"
    ["education"]="app_updates_scheduled,system_updates_scheduled,security_updates_auto,bandwidth_priority_medium"
    ["healthcare"]="app_updates_manual,system_updates_manual,security_updates_immediate,bandwidth_priority_high"
    ["financial"]="app_updates_disabled,system_updates_manual,security_updates_immediate,bandwidth_priority_high"
    ["retail"]="app_updates_scheduled,system_updates_auto,security_updates_auto,bandwidth_priority_medium"
    ["remote_work"]="app_updates_auto,system_updates_prompt,security_updates_auto,bandwidth_priority_medium"
)

# Update schedules for different scenarios
declare -A UPDATE_SCHEDULES=(
    ["business_hours"]="weekdays_evening,09:00-17:00_block"
    ["maintenance_window"]="weekend_only,saturday_2am"
    ["off_peak"]="overnight,02:00-05:00"
    ["immediate"]="real_time,no_delay"
    ["weekly_batch"]="sunday_night,sunday_23:00"
    ["monthly_patch"]="first_sunday,monthly_02:00"
)

# Bandwidth management profiles
declare -A BANDWIDTH_PROFILES=(
    ["conservative"]="max_5mbps,off_peak_only,cellular_disabled"
    ["balanced"]="max_20mbps,business_hours_limited,cellular_security_only"
    ["unlimited"]="no_throttle,anytime,cellular_enabled"
    ["emergency_only"]="max_1mbps,security_updates_only,cellular_emergency"
)

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

# Advanced update policy enforcement
enforce_update_policy() {
    local policy_name="$1"
    local environment_type="${2:-enterprise}"
    local bandwidth_profile="${3:-balanced}"
    local dry_run="${4:-false}"
    
    log_action "Enforcing update policy: $policy_name (environment: $environment_type, bandwidth: $bandwidth_profile, dry_run: $dry_run)"
    
    if [[ -z "${UPDATE_POLICIES[$policy_name]}" ]]; then
        log_action "ERROR: Unknown policy '$policy_name'"
        echo "Available policies: ${!UPDATE_POLICIES[*]}"
        return 1
    fi
    
    # Parse policy configuration
    IFS=',' read -ra POLICY_PARTS <<< "${UPDATE_POLICIES[$policy_name]}"
    local app_updates="${POLICY_PARTS[0]}"
    local system_updates="${POLICY_PARTS[1]}"
    local security_updates="${POLICY_PARTS[2]}"
    local bandwidth_priority="${POLICY_PARTS[3]}"
    
    echo "=== Enforcing Update Policy: $policy_name ==="
    echo "App Updates: $app_updates"
    echo "System Updates: $system_updates"
    echo "Security Updates: $security_updates"
    echo "Bandwidth Priority: $bandwidth_priority"
    echo "Environment: $environment_type"
    
    if [[ "$dry_run" == "true" ]]; then
        echo "DRY RUN MODE - No changes will be applied"
        return 0
    fi
    
    # Apply app update settings
    apply_app_update_policy "$app_updates"
    
    # Apply system update settings
    apply_system_update_policy "$system_updates"
    
    # Apply security update settings
    apply_security_update_policy "$security_updates"
    
    # Apply bandwidth management
    apply_bandwidth_management "$bandwidth_profile"
    
    # Configure environment-specific settings
    configure_environment_settings "$environment_type"
    
    # Generate policy compliance report
    local report_file="$REPORT_DIR/policy_enforcement_${policy_name}_$(date +%Y%m%d_%H%M%S).json"
    generate_comprehensive_report "$policy_name" "$report_file"
    
    log_action "Update policy enforcement completed: $report_file"
    echo "$report_file"
}

# Apply app update policy settings
apply_app_update_policy() {
    local policy="$1"
    
    case "$policy" in
        "app_updates_disabled")
            defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool FALSE
            echo "✓ App Store auto updates disabled"
            ;;
        "app_updates_auto")
            defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool TRUE
            echo "✓ App Store auto updates enabled"
            ;;
        "app_updates_scheduled")
            defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool FALSE
            setup_scheduled_app_updates "weekly"
            echo "✓ App Store updates scheduled for weekly maintenance window"
            ;;
        "app_updates_manual")
            defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool FALSE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticCheckEnabled -bool TRUE
            echo "✓ App Store updates set to manual with automatic checking"
            ;;
    esac
}

# Apply system update policy settings
apply_system_update_policy() {
    local policy="$1"
    
    case "$policy" in
        "system_updates_disabled")
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticCheckEnabled -bool FALSE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload -bool FALSE
            echo "✓ System updates completely disabled"
            ;;
        "system_updates_auto")
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticCheckEnabled -bool TRUE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload -bool TRUE
            echo "✓ System updates fully automated"
            ;;
        "system_updates_manual")
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticCheckEnabled -bool TRUE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload -bool FALSE
            echo "✓ System updates set to manual installation"
            ;;
        "system_updates_prompt")
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticCheckEnabled -bool TRUE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload -bool TRUE
            # Configure user prompts for installation
            echo "✓ System updates set to prompt user for installation"
            ;;
        "system_updates_scheduled")
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticCheckEnabled -bool TRUE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload -bool TRUE
            setup_scheduled_system_updates "monthly"
            echo "✓ System updates scheduled for monthly maintenance"
            ;;
    esac
}

# Apply security update policy settings
apply_security_update_policy() {
    local policy="$1"
    
    case "$policy" in
        "security_updates_immediate")
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist CriticalUpdateInstall -bool TRUE
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticCheckEnabled -bool TRUE
            echo "✓ Security updates set to immediate installation"
            ;;
        "security_updates_auto")
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist CriticalUpdateInstall -bool TRUE
            echo "✓ Security updates enabled for automatic installation"
            ;;
        "security_updates_manual")
            defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist CriticalUpdateInstall -bool FALSE
            echo "✓ Security updates set to manual installation"
            ;;
    esac
}

# Apply bandwidth management settings
apply_bandwidth_management() {
    local profile="$1"
    
    if [[ -z "${BANDWIDTH_PROFILES[$profile]}" ]]; then
        echo "Warning: Unknown bandwidth profile '$profile', using default"
        profile="balanced"
    fi
    
    # Parse bandwidth configuration
    IFS=',' read -ra BANDWIDTH_PARTS <<< "${BANDWIDTH_PROFILES[$profile]}"
    local max_bandwidth="${BANDWIDTH_PARTS[0]}"
    local time_restrictions="${BANDWIDTH_PARTS[1]}"
    local cellular_policy="${BANDWIDTH_PARTS[2]}"
    
    echo "✓ Bandwidth management applied: $profile"
    echo "  Max Bandwidth: $max_bandwidth"
    echo "  Time Restrictions: $time_restrictions"
    echo "  Cellular Policy: $cellular_policy"
    
    # Configure bandwidth throttling (implementation would depend on network tools)
    configure_bandwidth_throttling "$max_bandwidth" "$time_restrictions"
}

# Configure environment-specific settings
configure_environment_settings() {
    local environment="$1"
    
    case "$environment" in
        "healthcare")
            # HIPAA compliance settings
            configure_hipaa_update_compliance
            echo "✓ Healthcare/HIPAA update compliance configured"
            ;;
        "financial")
            # Financial services compliance
            configure_financial_update_compliance
            echo "✓ Financial services update compliance configured"
            ;;
        "education")
            # Educational institution settings
            configure_education_update_settings
            echo "✓ Educational environment update settings configured"
            ;;
        "kiosk")
            # Kiosk-specific restrictions
            configure_kiosk_update_restrictions
            echo "✓ Kiosk update restrictions configured"
            ;;
        "enterprise")
            # Standard enterprise settings
            configure_enterprise_update_settings
            echo "✓ Enterprise update settings configured"
            ;;
    esac
}

# Setup scheduled app updates
setup_scheduled_app_updates() {
    local frequency="$1"
    
    local script_path="/usr/local/bin/macfleet_scheduled_app_updates.sh"
    
    cat > "$script_path" << 'EOF'
#!/bin/bash
# MacFleet Scheduled App Updates
LOG_FILE="/var/log/macfleet_scheduled_updates.log"

echo "$(date): Starting scheduled app update check" >> "$LOG_FILE"

# Check for app updates
available_updates=$(softwareupdate -l 2>/dev/null | grep -c "recommended" || echo "0")

if [[ "$available_updates" -gt 0 ]]; then
    echo "$(date): Found $available_updates available updates" >> "$LOG_FILE"
    
    # Download updates but don't install (for approval process)
    softwareupdate -d -a >> "$LOG_FILE" 2>&1
    
    # Notify administrators
    echo "$(date): Updates downloaded, awaiting approval" >> "$LOG_FILE"
else
    echo "$(date): No updates available" >> "$LOG_FILE"
fi
EOF
    
    chmod +x "$script_path"
    
    # Create launchd job based on frequency
    create_update_launchd_job "$frequency" "$script_path"
}

# Generate comprehensive update report
generate_comprehensive_report() {
    local policy_name="$1"
    local report_file="$2"
    
    # Collect comprehensive update information
    local hostname=$(hostname)
    local system_version=$(sw_vers -productVersion)
    local build_version=$(sw_vers -buildVersion)
    local uptime=$(uptime | awk '{print $3,$4}' | sed 's/,//')
    
    # Get current settings
    local app_store_auto=$(defaults read /Library/Preferences/com.apple.commerce.plist AutoUpdate 2>/dev/null || echo "default")
    local auto_download=$(defaults read /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload 2>/dev/null || echo "default")
    local auto_check=$(defaults read /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticCheckEnabled 2>/dev/null || echo "default")
    local critical_updates=$(defaults read /Library/Preferences/com.apple.SoftwareUpdate.plist CriticalUpdateInstall 2>/dev/null || echo "default")
    
    # Get update status
    local available_updates=$(softwareupdate -l 2>/dev/null | grep -c "recommended" || echo "0")
    local last_check=$(defaults read /Library/Preferences/com.apple.SoftwareUpdate.plist LastSuccessfulDate 2>/dev/null || echo "unknown")
    local cache_size=$(du -sh /Library/Updates 2>/dev/null | cut -f1 || echo "0B")
    
    cat > "$report_file" << EOF
{
    "comprehensive_update_report": {
        "policy_name": "$policy_name",
        "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
        "hostname": "$hostname",
        "script_version": "$SCRIPT_VERSION",
        "system_info": {
            "system_version": "$system_version",
            "build_version": "$build_version",
            "uptime": "$uptime"
        },
        "update_settings": {
            "app_store_auto_update": "$app_store_auto",
            "automatic_download": "$auto_download",
            "automatic_check": "$auto_check",
            "critical_updates": "$critical_updates"
        },
        "update_status": {
            "available_updates": $available_updates,
            "last_check": "$last_check",
            "cache_size": "$cache_size"
        },
        "compliance_status": "compliant",
        "policy_enforcement_date": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
    }
}
EOF
    
    log_action "Comprehensive update report generated: $report_file"
}

# Monitor update compliance across fleet
monitor_fleet_update_compliance() {
    local compliance_type="${1:-standard}"
    
    echo "=== Fleet Update Compliance Monitor ==="
    
    # Check overall compliance status
    local policy_violations=0
    local total_checks=0
    
    # Verify App Store settings
    local app_store_setting=$(defaults read /Library/Preferences/com.apple.commerce.plist AutoUpdate 2>/dev/null || echo "default")
    ((total_checks++))
    
    # Check for pending updates that violate policy
    local pending_updates=$(softwareupdate -l 2>/dev/null | grep -c "recommended" || echo "0")
    
    if [[ "$pending_updates" -gt 0 && "$compliance_type" == "strict" ]]; then
        ((policy_violations++))
        echo "⚠️ Policy Violation: Pending updates found in strict compliance mode"
    fi
    
    # Calculate compliance score
    local compliance_score=$((100 - (policy_violations * 100 / total_checks)))
    
    echo "Compliance Score: $compliance_score%"
    echo "Policy Violations: $policy_violations"
    echo "Total Checks: $total_checks"
    echo "Pending Updates: $pending_updates"
    
    # Generate compliance summary
    local compliance_file="$REPORT_DIR/fleet_compliance_$(date +%Y%m%d_%H%M%S).json"
    cat > "$compliance_file" << EOF
{
    "fleet_compliance": {
        "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
        "compliance_type": "$compliance_type",
        "compliance_score": $compliance_score,
        "policy_violations": $policy_violations,
        "total_checks": $total_checks,
        "pending_updates": $pending_updates,
        "hostname": "$(hostname)"
    }
}
EOF
    
    echo "✓ Fleet compliance report: $compliance_file"
}

# Main execution function
main() {
    local action="${1:-status}"
    local param1="${2:-}"
    local param2="${3:-}"
    local param3="${4:-}"
    local param4="${5:-}"
    
    log_action "=== MacFleet App Store Update Management Started ==="
    log_action "Action: $action"
    
    # Ensure required privileges for configuration changes
    if [[ "$action" != "status" && "$action" != "help" && "$action" != "report" && $EUID -ne 0 ]]; then
        echo "Error: This action requires administrator privileges"
        echo "Please run with sudo: sudo $0 $*"
        exit 1
    fi
    
    case "$action" in
        "policy")
            if [[ -z "$param1" ]]; then
                echo "Available policies: ${!UPDATE_POLICIES[*]}"
                exit 1
            fi
            enforce_update_policy "$param1" "$param2" "$param3" "$param4"
            ;;
        "enable")
            defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool TRUE
            echo "✓ App Store auto updates enabled"
            ;;
        "disable")
            defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool FALSE
            echo "✓ App Store auto updates disabled"
            ;;
        "check")
            echo "Checking for available updates..."
            softwareupdate -l
            ;;
        "install")
            if [[ -n "$param1" ]]; then
                echo "Installing specific update: $param1"
                softwareupdate -i "$param1"
            else
                echo "Installing all available updates..."
                softwareupdate -i -a
            fi
            ;;
        "status")
            verify_update_settings
            if [[ "$param1" == "detailed" ]]; then
                monitor_update_status "true"
            fi
            ;;
        "report")
            generate_comprehensive_report "${param1:-current}" "${param2:-/tmp/update_report_$(date +%Y%m%d_%H%M%S).json}"
            ;;
        "compliance")
            monitor_fleet_update_compliance "$param1"
            ;;
        "reset")
            echo "Resetting App Store update settings to defaults..."
            defaults delete /Library/Preferences/com.apple.commerce.plist AutoUpdate 2>/dev/null || true
            defaults delete /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload 2>/dev/null || true
            defaults delete /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticCheckEnabled 2>/dev/null || true
            defaults delete /Library/Preferences/com.apple.SoftwareUpdate.plist CriticalUpdateInstall 2>/dev/null || true
            echo "✓ Update settings reset to system defaults"
            ;;
        "help")
            echo "Usage: $0 [action] [options...]"
            echo "Actions:"
            echo "  policy <policy_name> [environment] [bandwidth] [dry_run] - Apply update policy"
            echo "  enable - Enable App Store auto updates"
            echo "  disable - Disable App Store auto updates"
            echo "  check - Check for available updates"
            echo "  install [update_name] - Install updates (all or specific)"
            echo "  status [detailed] - Show current update configuration"
            echo "  report [policy_name] [output_file] - Generate update report"
            echo "  compliance [type] - Check fleet compliance"
            echo "  reset - Reset to system defaults"
            echo "  help - Show this help"
            echo ""
            echo "Policies: ${!UPDATE_POLICIES[*]}"
            echo "Schedules: ${!UPDATE_SCHEDULES[*]}"
            echo "Bandwidth Profiles: ${!BANDWIDTH_PROFILES[*]}"
            ;;
        *)
            log_action "ERROR: Unknown action: $action"
            echo "Use '$0 help' for usage information"
            exit 1
            ;;
    esac
    
    log_action "=== App Store update management completed ==="
}

# Execute main function
main "$@"

Update Security and Compliance

Healthcare/HIPAA Compliance

#!/bin/bash

# Configure HIPAA-compliant update management
configure_hipaa_update_compliance() {
    echo "=== Configuring HIPAA Update Compliance ==="
    
    # Disable automatic updates for compliance control
    defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool FALSE
    defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload -bool FALSE
    
    # Enable security updates only
    defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist CriticalUpdateInstall -bool TRUE
    
    # Configure audit logging
    setup_update_audit_logging "hipaa"
    
    echo "✓ HIPAA update compliance configured"
}

# Setup audit logging for compliance
setup_update_audit_logging() {
    local compliance_type="$1"
    local audit_file="/var/log/macfleet_update_audit.log"
    
    # Create audit script
    cat > "/usr/local/bin/macfleet_update_audit.sh" << 'EOF'
#!/bin/bash
AUDIT_LOG="/var/log/macfleet_update_audit.log"

log_update_event() {
    local event_type="$1"
    local details="$2"
    echo "$(date -u +%Y-%m-%dT%H:%M:%SZ) | $event_type | $(whoami) | $details" >> "$AUDIT_LOG"
}

# Monitor for update events
log_update_event "AUDIT_START" "Update audit monitoring started"
EOF
    
    chmod +x "/usr/local/bin/macfleet_update_audit.sh"
    echo "✓ Update audit logging configured for $compliance_type"
}

configure_hipaa_update_compliance

Financial Services Compliance

#!/bin/bash

# Configure financial services update compliance
configure_financial_update_compliance() {
    echo "=== Configuring Financial Services Update Compliance ==="
    
    # Strict update control for financial compliance
    defaults write /Library/Preferences/com.apple.commerce.plist AutoUpdate -bool FALSE
    defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticDownload -bool FALSE
    defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist AutomaticCheckEnabled -bool TRUE
    
    # Security updates only with manual approval
    defaults write /Library/Preferences/com.apple.SoftwareUpdate.plist CriticalUpdateInstall -bool FALSE
    
    # Configure change management integration
    setup_change_management_integration "financial"
    
    echo "✓ Financial services update compliance configured"
}

configure_financial_update_compliance

Troubleshooting and Maintenance

Update System Health Check

#!/bin/bash

# Comprehensive update system health check
perform_update_health_check() {
    echo "=== Update System Health Check ==="
    
    # Check update service status
    local update_service_status
    update_service_status=$(launchctl list | grep -c "com.apple.softwareupdated" || echo "0")
    echo "Software Update Service: $([ "$update_service_status" -gt 0 ] && echo "Running" || echo "Not Running")"
    
    # Check update cache
    local cache_path="/Library/Updates"
    if [[ -d "$cache_path" ]]; then
        local cache_size=$(du -sh "$cache_path" | cut -f1)
        local cache_files=$(find "$cache_path" -type f | wc -l | tr -d ' ')
        echo "Update Cache: $cache_size ($cache_files files)"
    else
        echo "Update Cache: Not present"
    fi
    
    # Check for corrupted preferences
    local commerce_plist="/Library/Preferences/com.apple.commerce.plist"
    local softwareupdate_plist="/Library/Preferences/com.apple.SoftwareUpdate.plist"
    
    if plutil -lint "$commerce_plist" &>/dev/null; then
        echo "Commerce Preferences: Valid"
    else
        echo "⚠️ Commerce Preferences: Corrupted or missing"
    fi
    
    if plutil -lint "$softwareupdate_plist" &>/dev/null; then
        echo "Software Update Preferences: Valid"
    else
        echo "⚠️ Software Update Preferences: Corrupted or missing"
    fi
    
    # Check network connectivity for updates
    if curl -s --connect-timeout 5 "https://swscan.apple.com/" &>/dev/null; then
        echo "Apple Update Servers: Accessible"
    else
        echo "⚠️ Apple Update Servers: Not accessible"
    fi
}

perform_update_health_check

Important Notes

  • Administrator privileges required for update configuration changes
  • Restart requirements - Some settings take effect after restart
  • Network impact - Consider bandwidth usage for automatic updates
  • Security implications - Balance automation with security control
  • Compliance requirements - Some industries require manual update approval
  • Storage considerations - Downloaded updates consume disk space
  • Testing recommendations - Test update policies on staging devices first
  • Monitoring importance - Regular compliance checking prevents policy drift

View Last Opened Time of Apps and Files on macOS

This comprehensive guide demonstrates how to track when applications and files were last accessed on macOS devices, providing essential insights for Mac fleet management and usage monitoring.

Overview

Monitoring app and file access patterns is crucial for:

  • Performance optimization: Identifying resource-intensive applications
  • License management: Tracking software usage for compliance
  • Security auditing: Monitoring file access for security compliance
  • Storage optimization: Finding unused applications and files
  • User behavior analysis: Understanding work patterns and productivity

Basic Last Opened Time Script

Simple App/File Check

Create a basic script to check when an app or file was last opened:

#!/bin/bash

# Basic script to get last opened time of an app or file
# Usage: ./last_opened.sh "/path/to/app/or/file"

if [ $# -eq 0 ]; then
    echo "Usage: $0 <file_path>"
    echo "Example: $0 '/Applications/Safari.app'"
    exit 1
fi

file_path="$1"

# Check if file exists
if [ ! -e "$file_path" ]; then
    echo "Error: File or application not found: $file_path"
    exit 1
fi

# Get last opened time using mdls
datetime=$(mdls "$file_path" -name kMDItemLastUsedDate | awk '{print $3,$4}')

if [ "$datetime" = "(null)" ]; then
    echo "'$file_path' has never been opened or last opened time is not available"
    exit 0
fi

echo "'$file_path' was last opened on (UTC):"
echo "$datetime"
echo "'$file_path' was last opened on (Local Time):"
echo "$(date -jf "%Y-%m-%d %H:%M:%S %z" "$datetime +0000" +"%Y-%m-%d %H:%M:%S")"

Enhanced Script with Error Handling

#!/bin/bash

# Enhanced script with comprehensive error handling and formatting
# Usage: ./enhanced_last_opened.sh "/path/to/app/or/file"

check_last_opened() {
    local file_path="$1"
    local file_name=$(basename "$file_path")
    
    # Validate input
    if [ -z "$file_path" ]; then
        echo "Error: No file path provided"
        return 1
    fi
    
    # Check if file exists
    if [ ! -e "$file_path" ]; then
        echo "Error: File not found: $file_path"
        return 1
    fi
    
    # Get metadata
    local datetime=$(mdls "$file_path" -name kMDItemLastUsedDate 2>/dev/null | awk '{print $3,$4}')
    local creation_date=$(mdls "$file_path" -name kMDItemContentCreationDate 2>/dev/null | awk '{print $3,$4}')
    local modification_date=$(mdls "$file_path" -name kMDItemContentModificationDate 2>/dev/null | awk '{print $3,$4}')
    
    echo "=== File Information ==="
    echo "File: $file_name"
    echo "Path: $file_path"
    echo ""
    
    # Last opened time
    if [ "$datetime" = "(null)" ] || [ -z "$datetime" ]; then
        echo "Last Opened: Never opened or information not available"
    else
        echo "Last Opened (UTC): $datetime"
        local local_time=$(date -jf "%Y-%m-%d %H:%M:%S %z" "$datetime +0000" +"%Y-%m-%d %H:%M:%S" 2>/dev/null)
        if [ $? -eq 0 ]; then
            echo "Last Opened (Local): $local_time"
        else
            echo "Last Opened (Local): Unable to convert time"
        fi
    fi
    
    # Creation date
    if [ "$creation_date" != "(null)" ] && [ -n "$creation_date" ]; then
        echo "Created (UTC): $creation_date"
    fi
    
    # Modification date
    if [ "$modification_date" != "(null)" ] && [ -n "$modification_date" ]; then
        echo "Modified (UTC): $modification_date"
    fi
    
    echo "========================"
    echo ""
}

# Main execution
if [ $# -eq 0 ]; then
    echo "Usage: $0 <file_path>"
    echo "Example: $0 '/Applications/Safari.app'"
    exit 1
fi

check_last_opened "$1"

Advanced Application Monitoring

Bulk Application Scanner

#!/bin/bash

# Bulk application scanner with detailed reporting
# Usage: ./bulk_app_scanner.sh

scan_applications() {
    local output_file="app_usage_report_$(date +%Y%m%d_%H%M%S).txt"
    
    echo "MacFleet Application Usage Report" > "$output_file"
    echo "Generated: $(date)" >> "$output_file"
    echo "Device: $(scutil --get ComputerName)" >> "$output_file"
    echo "User: $(whoami)" >> "$output_file"
    echo "=======================================" >> "$output_file"
    echo "" >> "$output_file"
    
    # Scan Applications folder
    echo "Scanning /Applications..."
    find /Applications -maxdepth 2 -name "*.app" -type d | while read app_path; do
        app_name=$(basename "$app_path" .app)
        
        # Get last opened time
        datetime=$(mdls "$app_path" -name kMDItemLastUsedDate 2>/dev/null | awk '{print $3,$4}')
        
        if [ "$datetime" = "(null)" ] || [ -z "$datetime" ]; then
            last_opened="Never opened"
        else
            last_opened=$(date -jf "%Y-%m-%d %H:%M:%S %z" "$datetime +0000" +"%Y-%m-%d %H:%M:%S" 2>/dev/null)
            if [ $? -ne 0 ]; then
                last_opened="$datetime (UTC)"
            fi
        fi
        
        # Get app version
        app_version=$(mdls "$app_path" -name kMDItemVersion 2>/dev/null | awk -F'"' '{print $2}')
        if [ "$app_version" = "(null)" ] || [ -z "$app_version" ]; then
            app_version="Unknown"
        fi
        
        # Get app size
        app_size=$(du -sh "$app_path" 2>/dev/null | cut -f1)
        if [ -z "$app_size" ]; then
            app_size="Unknown"
        fi
        
        echo "App: $app_name" >> "$output_file"
        echo "  Version: $app_version" >> "$output_file"
        echo "  Size: $app_size" >> "$output_file"
        echo "  Last Opened: $last_opened" >> "$output_file"
        echo "  Path: $app_path" >> "$output_file"
        echo "" >> "$output_file"
        
        # Progress indicator
        echo "Processed: $app_name"
    done
    
    echo "Report saved to: $output_file"
}

# Execute scan
scan_applications

Recently Used Applications Filter

#!/bin/bash

# Filter applications by recent usage
# Usage: ./recent_apps.sh [days]

filter_recent_apps() {
    local days_threshold=${1:-7}  # Default to 7 days
    local cutoff_date=$(date -v -${days_threshold}d +%Y-%m-%d)
    
    echo "Applications used in the last $days_threshold days:"
    echo "Cutoff date: $cutoff_date"
    echo "=================================="
    
    find /Applications -maxdepth 2 -name "*.app" -type d | while read app_path; do
        app_name=$(basename "$app_path" .app)
        
        # Get last opened time
        datetime=$(mdls "$app_path" -name kMDItemLastUsedDate 2>/dev/null | awk '{print $3,$4}')
        
        if [ "$datetime" != "(null)" ] && [ -n "$datetime" ]; then
            # Convert to comparable format
            app_date=$(echo "$datetime" | cut -d' ' -f1)
            
            # Compare dates
            if [[ "$app_date" > "$cutoff_date" ]]; then
                local_time=$(date -jf "%Y-%m-%d %H:%M:%S %z" "$datetime +0000" +"%Y-%m-%d %H:%M:%S" 2>/dev/null)
                if [ $? -eq 0 ]; then
                    echo "$app_name - Last used: $local_time"
                else
                    echo "$app_name - Last used: $datetime (UTC)"
                fi
            fi
        fi
    done | sort
}

# Main execution
if [ $# -gt 1 ]; then
    echo "Usage: $0 [days]"
    echo "Example: $0 30  # Show apps used in last 30 days"
    exit 1
fi

filter_recent_apps "$1"

Enterprise File Monitoring

Document Access Tracker

#!/bin/bash

# Track document access patterns across common file types
# Usage: ./document_tracker.sh "/path/to/documents"

track_document_access() {
    local base_path=${1:-"$HOME/Documents"}
    local output_file="document_access_$(date +%Y%m%d_%H%M%S).json"
    
    echo "Tracking document access in: $base_path"
    
    # Create JSON report
    cat > "$output_file" << EOF
{
  "report_info": {
    "generated": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
    "device": "$(scutil --get ComputerName)",
    "user": "$(whoami)",
    "scan_path": "$base_path",
    "macfleet_version": "1.0"
  },
  "documents": [
EOF
    
    local first_entry=true
    
    # Common document types
    local file_types=("*.pdf" "*.doc" "*.docx" "*.xls" "*.xlsx" "*.ppt" "*.pptx" "*.txt" "*.rtf" "*.pages" "*.numbers" "*.keynote")
    
    for pattern in "${file_types[@]}"; do
        find "$base_path" -name "$pattern" -type f 2>/dev/null | while read file_path; do
            # Get file metadata
            local filename=$(basename "$file_path")
            local extension="${filename##*.}"
            local size=$(stat -f%z "$file_path" 2>/dev/null || echo "0")
            
            # Get timestamps
            local last_used=$(mdls "$file_path" -name kMDItemLastUsedDate 2>/dev/null | awk '{print $3,$4}')
            local created=$(mdls "$file_path" -name kMDItemContentCreationDate 2>/dev/null | awk '{print $3,$4}')
            local modified=$(mdls "$file_path" -name kMDItemContentModificationDate 2>/dev/null | awk '{print $3,$4}')
            
            # Format for JSON
            if [ "$last_used" = "(null)" ] || [ -z "$last_used" ]; then
                last_used="null"
            else
                last_used="\"$last_used\""
            fi
            
            if [ "$created" = "(null)" ] || [ -z "$created" ]; then
                created="null"
            else
                created="\"$created\""
            fi
            
            if [ "$modified" = "(null)" ] || [ -z "$modified" ]; then
                modified="null"
            else
                modified="\"$modified\""
            fi
            
            # Add comma if not first entry
            if [ "$first_entry" = false ]; then
                echo "," >> "$output_file"
            fi
            first_entry=false
            
            # Add document entry
            cat >> "$output_file" << EOF
    {
      "filename": "$filename",
      "extension": "$extension",
      "size_bytes": $size,
      "path": "$file_path",
      "last_used": $last_used,
      "created": $created,
      "modified": $modified
    }EOF
        done
    done
    
    # Close JSON
    cat >> "$output_file" << EOF

  ]
}
EOF
    
    echo "Document access report saved to: $output_file"
}

# Execute tracking
track_document_access "$1"

Multi-User File Access Monitor

#!/bin/bash

# Monitor file access across multiple user accounts
# Usage: ./multi_user_monitor.sh

monitor_multi_user_access() {
    local report_file="multi_user_access_$(date +%Y%m%d_%H%M%S).txt"
    
    echo "MacFleet Multi-User File Access Report" > "$report_file"
    echo "Generated: $(date)" >> "$report_file"
    echo "Device: $(scutil --get ComputerName)" >> "$report_file"
    echo "=========================================" >> "$report_file"
    echo "" >> "$report_file"
    
    # Get all user home directories
    local users=($(dscl . -list /Users | grep -v "^_" | grep -v "daemon" | grep -v "nobody" | grep -v "root"))
    
    for user in "${users[@]}"; do
        local user_home=$(dscl . -read /Users/$user NFSHomeDirectory | awk '{print $2}')
        
        if [ -d "$user_home" ]; then
            echo "User: $user ($user_home)" >> "$report_file"
            echo "--------------------------------" >> "$report_file"
            
            # Check Documents folder
            if [ -d "$user_home/Documents" ]; then
                echo "Recently accessed documents:" >> "$report_file"
                find "$user_home/Documents" -type f -name "*.pdf" -o -name "*.doc*" -o -name "*.xls*" -o -name "*.ppt*" 2>/dev/null | head -10 | while read file_path; do
                    local filename=$(basename "$file_path")
                    local last_used=$(mdls "$file_path" -name kMDItemLastUsedDate 2>/dev/null | awk '{print $3,$4}')
                    
                    if [ "$last_used" != "(null)" ] && [ -n "$last_used" ]; then
                        echo "  - $filename (Last used: $last_used)" >> "$report_file"
                    fi
                done
            fi
            
            # Check Downloads folder
            if [ -d "$user_home/Downloads" ]; then
                echo "Recent downloads:" >> "$report_file"
                find "$user_home/Downloads" -type f -mtime -7 2>/dev/null | head -5 | while read file_path; do
                    local filename=$(basename "$file_path")
                    local mod_time=$(stat -f "%Sm" -t "%Y-%m-%d %H:%M:%S" "$file_path" 2>/dev/null)
                    echo "  - $filename (Downloaded: $mod_time)" >> "$report_file"
                done
            fi
            
            echo "" >> "$report_file"
        fi
    done
    
    echo "Multi-user access report saved to: $report_file"
}

# Execute monitoring
monitor_multi_user_access

Remote Fleet Management

Centralized Usage Collector

#!/bin/bash

# Collect usage data for remote fleet management
# Usage: ./fleet_collector.sh

collect_fleet_data() {
    local device_id=$(system_profiler SPHardwareDataType | grep "Hardware UUID" | awk '{print $3}')
    local computer_name=$(scutil --get ComputerName)
    local timestamp=$(date -u +%Y-%m-%dT%H:%M:%SZ)
    
    # Create comprehensive report
    local report_file="fleet_usage_${computer_name}_$(date +%Y%m%d_%H%M%S).json"
    
    cat > "$report_file" << EOF
{
  "device_info": {
    "device_id": "$device_id",
    "computer_name": "$computer_name",
    "timestamp": "$timestamp",
    "os_version": "$(sw_vers -productVersion)",
    "uptime": "$(uptime | awk '{print $3,$4}' | sed 's/,//')"
  },
  "application_usage": [
EOF
    
    # Collect top applications
    local first_app=true
    find /Applications -maxdepth 2 -name "*.app" -type d | head -20 | while read app_path; do
        local app_name=$(basename "$app_path" .app)
        local last_used=$(mdls "$app_path" -name kMDItemLastUsedDate 2>/dev/null | awk '{print $3,$4}')
        local version=$(mdls "$app_path" -name kMDItemVersion 2>/dev/null | awk -F'"' '{print $2}')
        
        if [ "$first_app" = false ]; then
            echo "," >> "$report_file"
        fi
        first_app=false
        
        # Format values for JSON
        if [ "$last_used" = "(null)" ] || [ -z "$last_used" ]; then
            last_used="null"
        else
            last_used="\"$last_used\""
        fi
        
        if [ "$version" = "(null)" ] || [ -z "$version" ]; then
            version="null"
        else
            version="\"$version\""
        fi
        
        cat >> "$report_file" << EOF
    {
      "name": "$app_name",
      "version": $version,
      "last_used": $last_used,
      "path": "$app_path"
    }EOF
    done
    
    cat >> "$report_file" << EOF

  ],
  "system_stats": {
    "total_applications": $(find /Applications -maxdepth 2 -name "*.app" -type d | wc -l | tr -d ' '),
    "disk_usage": "$(df -h / | tail -1 | awk '{print $5}')",
    "memory_usage": "$(vm_stat | grep "Pages active" | awk '{print $3}' | sed 's/\.//')"
  }
}
EOF
    
    echo "Fleet data collected in: $report_file"
    
    # Optional: Send to central server
    # curl -X POST -H "Content-Type: application/json" -d @"$report_file" "https://your-fleet-server.com/api/usage"
}

# Execute collection
collect_fleet_data

Automated Usage Monitoring

#!/bin/bash

# Automated usage monitoring with alerts
# Usage: ./usage_monitor.sh

setup_monitoring() {
    local log_file="/var/log/macfleet_usage.log"
    local config_file="/etc/macfleet/usage_config.conf"
    
    # Create configuration if it doesn't exist
    if [ ! -f "$config_file" ]; then
        sudo mkdir -p /etc/macfleet
        sudo cat > "$config_file" << EOF
# MacFleet Usage Monitoring Configuration
MONITOR_INTERVAL=3600  # Check every hour
ALERT_THRESHOLD=30     # Alert if app unused for 30 days
REPORT_INTERVAL=86400  # Generate report daily
CLEANUP_THRESHOLD=90   # Flag apps unused for 90 days
EOF
    fi
    
    # Source configuration
    source "$config_file"
    
    # Create monitoring script
    cat > "/tmp/macfleet_monitor.sh" << EOF
#!/bin/bash

# MacFleet Usage Monitor
log_usage() {
    local timestamp=\$(date -u +%Y-%m-%dT%H:%M:%SZ)
    local computer_name=\$(scutil --get ComputerName)
    
    echo "[\$timestamp] Starting usage check on \$computer_name" >> "$log_file"
    
    # Check for unused applications
    find /Applications -maxdepth 2 -name "*.app" -type d | while read app_path; do
        local app_name=\$(basename "\$app_path" .app)
        local last_used=\$(mdls "\$app_path" -name kMDItemLastUsedDate 2>/dev/null | awk '{print \$3,\$4}')
        
        if [ "\$last_used" != "(null)" ] && [ -n "\$last_used" ]; then
            local days_since=\$(( (\$(date +%s) - \$(date -jf "%Y-%m-%d %H:%M:%S %z" "\$last_used +0000" +%s)) / 86400 ))
            
            if [ \$days_since -gt $ALERT_THRESHOLD ]; then
                echo "[\$timestamp] ALERT: \$app_name unused for \$days_since days" >> "$log_file"
            fi
            
            if [ \$days_since -gt $CLEANUP_THRESHOLD ]; then
                echo "[\$timestamp] CLEANUP: \$app_name flagged for removal (\$days_since days)" >> "$log_file"
            fi
        fi
    done
    
    echo "[\$timestamp] Usage check completed" >> "$log_file"
}

# Run monitoring
log_usage
EOF
    
    chmod +x "/tmp/macfleet_monitor.sh"
    
    # Set up launchd for automated monitoring
    cat > "/tmp/com.macfleet.usage.monitor.plist" << EOF
<?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>Label</key>
    <string>com.macfleet.usage.monitor</string>
    <key>ProgramArguments</key>
    <array>
        <string>/tmp/macfleet_monitor.sh</string>
    </array>
    <key>StartInterval</key>
    <integer>$MONITOR_INTERVAL</integer>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>
EOF
    
    echo "Monitoring setup complete. Use 'sudo launchctl load /tmp/com.macfleet.usage.monitor.plist' to start."
}

# Execute setup
setup_monitoring

Best Practices for Mac Fleet Management

1. Performance Optimization

  • Monitor resource-intensive applications
  • Track applications that haven't been used recently
  • Identify opportunities for app cleanup
  • Optimize system performance through usage insights

2. Security and Compliance

  • Track file access for security audits
  • Monitor document handling compliance
  • Identify unauthorized file access patterns
  • Maintain access logs for compliance requirements

3. License Management

  • Monitor software usage for license optimization
  • Track application deployment effectiveness
  • Identify unused licenses for cost savings
  • Ensure compliance with software licensing agreements

4. User Experience

  • Understand user behavior patterns
  • Optimize application deployment strategies
  • Improve user productivity through usage insights
  • Customize device configurations based on usage

5. Maintenance and Cleanup

  • Identify unused applications for removal
  • Clean up temporary files and caches
  • Optimize storage usage
  • Schedule regular maintenance based on usage patterns

Troubleshooting Common Issues

1. Permission Errors

# Fix permission issues
sudo chown -R $(whoami) /Users/$(whoami)/Documents
sudo chmod -R 755 /Users/$(whoami)/Documents

2. Metadata Not Available

# Check if Spotlight indexing is enabled
mdutil -s /
# Re-index if necessary
sudo mdutil -i on /
sudo mdutil -E /

3. Script Execution Issues

# Make script executable
chmod +x script_name.sh
# Check bash version
bash --version
# Use full path for commands
/usr/bin/mdls instead of mdls

4. Date Format Issues

# Handle different date formats
date -jf "%Y-%m-%d %H:%M:%S %z" "2024-01-01 12:00:00 +0000" +"%Y-%m-%d %H:%M:%S"

Conclusion

Monitoring application and file usage is essential for effective Mac fleet management. These scripts provide comprehensive insights into user behavior, system performance, and security compliance. Regular monitoring helps optimize resources, improve user experience, and maintain security standards across your Mac fleet.

Remember to test scripts in a controlled environment before deploying them across your fleet, and always follow your organization's security and privacy policies when monitoring user activity.

Configure Alert Sound and Volume on macOS

Learn how to customize system alert sounds and volume levels on Mac devices. Essential for creating consistent audio experiences across enterprise Mac fleets and accommodating different work environments.

Change Alert Sound

Change the default alert sound from "Tink" to other available system sounds:

#!/bin/bash

# Get current user context
CURRENT_USER=$(stat -f "%Su" /dev/console)
CURRENT_USER_UID=$(id -u "$CURRENT_USER")

# Configuration
ALERT_SOUND="Submarine"  # Options: Basso, Funk, Glass, Ping, Pop, Submarine, Tink

echo "Setting alert sound to: $ALERT_SOUND"

# Apply alert sound setting
launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" \
    defaults write .GlobalPreferences com.apple.sound.beep.sound "/System/Library/Sounds/${ALERT_SOUND}.aiff"

echo "✅ Alert sound changed to $ALERT_SOUND"
echo "🔄 Changes take effect immediately"

Change Alert Volume

Adjust the alert volume level (0-100%):

#!/bin/bash

# Get current user context
CURRENT_USER=$(stat -f "%Su" /dev/console)
CURRENT_USER_UID=$(id -u "$CURRENT_USER")

# Configuration
ALERT_VOLUME="75"  # Volume percentage (0-100)

echo "Setting alert volume to: ${ALERT_VOLUME}%"

# Apply alert volume setting
launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" \
    osascript -e "set volume alert volume $ALERT_VOLUME"

echo "✅ Alert volume set to ${ALERT_VOLUME}%"

List Available Alert Sounds

Script to discover all available system alert sounds:

#!/bin/bash

echo "🔊 Available System Alert Sounds:"
echo "=================================="

# List all sound files in system sounds directory
SOUNDS_DIR="/System/Library/Sounds"
if [[ -d "$SOUNDS_DIR" ]]; then
    for sound_file in "$SOUNDS_DIR"/*.aiff; do
        if [[ -f "$sound_file" ]]; then
            sound_name=$(basename "$sound_file" .aiff)
            echo "  📢 $sound_name"
        fi
    done
else
    echo "❌ System sounds directory not found"
fi

echo ""
echo "💡 Use any of these names in the ALERT_SOUND variable"

Complete Alert Configuration

Comprehensive script to configure both sound and volume:

#!/bin/bash

# Function to configure alert settings
configure_alert_settings() {
    local sound_name="$1"
    local volume_level="$2"
    
    # Get current user context
    local current_user=$(stat -f "%Su" /dev/console)
    local current_user_uid=$(id -u "$current_user")
    
    echo "=== MacFleet Alert Configuration ==="
    echo "👤 User: $current_user"
    echo "🔊 Sound: $sound_name"
    echo "🔊 Volume: ${volume_level}%"
    echo "==================================="
    
    # Validate sound file exists
    local sound_path="/System/Library/Sounds/${sound_name}.aiff"
    if [[ ! -f "$sound_path" ]]; then
        echo "❌ Error: Sound '$sound_name' not found"
        echo "📋 Available sounds:"
        ls /System/Library/Sounds/*.aiff | sed 's|.*/||' | sed 's|\.aiff||' | sed 's/^/  - /'
        return 1
    fi
    
    # Validate volume range
    if [[ $volume_level -lt 0 || $volume_level -gt 100 ]]; then
        echo "❌ Error: Volume must be between 0 and 100"
        return 1
    fi
    
    # Apply alert sound setting
    launchctl asuser $current_user_uid sudo -iu "$current_user" \
        defaults write .GlobalPreferences com.apple.sound.beep.sound "$sound_path"
    
    # Apply alert volume setting
    launchctl asuser $current_user_uid sudo -iu "$current_user" \
        osascript -e "set volume alert volume $volume_level"
    
    echo "✅ Alert settings configured successfully"
    echo "🎵 Sound: $sound_name"
    echo "🔊 Volume: ${volume_level}%"
}

# Enterprise configuration
ALERT_SOUND="Glass"
ALERT_VOLUME="50"

# Apply configuration
configure_alert_settings "$ALERT_SOUND" "$ALERT_VOLUME"

Get Current Alert Settings

Script to display current alert sound and volume configuration:

#!/bin/bash

# Get current user context
CURRENT_USER=$(stat -f "%Su" /dev/console)
CURRENT_USER_UID=$(id -u "$CURRENT_USER")

echo "📊 Current Alert Settings"
echo "========================="

# Get current alert sound
current_sound=$(launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" \
    defaults read .GlobalPreferences com.apple.sound.beep.sound 2>/dev/null)

if [[ -n "$current_sound" ]]; then
    sound_name=$(basename "$current_sound" .aiff)
    echo "🔊 Alert Sound: $sound_name"
else
    echo "🔊 Alert Sound: Tink (default)"
fi

# Get current alert volume using AppleScript
current_volume=$(launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" \
    osascript -e "get volume settings" 2>/dev/null | grep -o 'alert volume:[0-9]*' | cut -d: -f2)

if [[ -n "$current_volume" ]]; then
    echo "🔊 Alert Volume: ${current_volume}%"
else
    echo "🔊 Alert Volume: Unable to determine"
fi

echo "👤 User: $CURRENT_USER"
echo "🖥️  Device: $(hostname)"

Enterprise Alert Policy

Standardized alert configuration for enterprise environments:

#!/bin/bash

# Enterprise alert standardization
COMPANY_NAME="MacFleet"
ENVIRONMENT_TYPE="office"  # Options: office, quiet, presentation, factory

# Define environment-specific settings
case "$ENVIRONMENT_TYPE" in
    "office")
        ALERT_SOUND="Glass"
        ALERT_VOLUME="50"
        ;;
    "quiet")
        ALERT_SOUND="Tink"
        ALERT_VOLUME="25"
        ;;
    "presentation")
        ALERT_SOUND="Pop"
        ALERT_VOLUME="10"
        ;;
    "factory")
        ALERT_SOUND="Basso"
        ALERT_VOLUME="100"
        ;;
    *)
        ALERT_SOUND="Glass"
        ALERT_VOLUME="50"
        ;;
esac

# Function to apply enterprise alert policy
apply_enterprise_alert_policy() {
    local current_user=$(stat -f "%Su" /dev/console)
    local current_user_uid=$(id -u "$current_user")
    
    echo "🏢 Applying Enterprise Alert Policy"
    echo "==================================="
    echo "Environment: $ENVIRONMENT_TYPE"
    echo "Device: $(hostname)"
    echo "User: $current_user"
    echo "Sound: $ALERT_SOUND"
    echo "Volume: ${ALERT_VOLUME}%"
    echo "Timestamp: $(date)"
    
    # Apply sound setting
    launchctl asuser $current_user_uid sudo -iu "$current_user" \
        defaults write .GlobalPreferences com.apple.sound.beep.sound "/System/Library/Sounds/${ALERT_SOUND}.aiff"
    
    # Apply volume setting
    launchctl asuser $current_user_uid sudo -iu "$current_user" \
        osascript -e "set volume alert volume $ALERT_VOLUME"
    
    echo "✅ Enterprise alert policy applied"
    echo "📊 Configuration complete on $(hostname)"
}

# Execute enterprise policy
apply_enterprise_alert_policy

Reset to Default Settings

Restore alert settings to macOS defaults:

#!/bin/bash

# Get current user context
CURRENT_USER=$(stat -f "%Su" /dev/console)
CURRENT_USER_UID=$(id -u "$CURRENT_USER")

echo "🔄 Resetting alert settings to defaults..."

# Reset alert sound to default (Tink)
launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" \
    defaults delete .GlobalPreferences com.apple.sound.beep.sound 2>/dev/null || true

# Reset alert volume to default (75%)
launchctl asuser $CURRENT_USER_UID sudo -iu "$CURRENT_USER" \
    osascript -e "set volume alert volume 75"

echo "✅ Alert settings reset to defaults"
echo "🔊 Sound: Tink (default)"
echo "🔊 Volume: 75% (default)"

Usage with MacFleet

  1. Choose appropriate sound and volume for your environment
  2. Test settings on a single device first
  3. Deploy through MacFleet's remote script execution
  4. Verify settings across device fleet

Available System Sounds

Sound NameDescriptionUse Case
BassoDeep, attention-grabbingHigh-priority alerts
FunkModern, pleasantGeneral notifications
GlassClear, sharpProfessional environments
PingQuick, subtleMinimal distraction
PopShort, crispQuick acknowledgments
SubmarineUnique, distinctiveCreative environments
TinkDefault system soundStandard configuration

Environment Guidelines

EnvironmentRecommended SoundVolume Level
OfficeGlass, Tink25-50%
Quiet zonesPing, Pop10-25%
PresentationsPop, Tink10%
Factory/LoudBasso, Funk75-100%
CreativeSubmarine, Funk50-75%

Troubleshooting

Sound not changing: Verify sound file exists in /System/Library/Sounds/ Volume not applying: Ensure AppleScript execution permissions Permission denied: Verify user context with launchctl asuser