#!/bin/bash

#==============================================================
#   It is recommended to test the script on a local machine for its purpose and effects.
#   ManageEngine Endpoint Central will not be responsible for any
#   damage/loss to the data/setup based on the behavior of the script.
#   Description - Script to clean system-level junk files on macOS
#                 System Logs, Library Caches, Diagnostic Reports,
#                 ASL Archives, Print Spool, Unified Log Archives
#   Parameters  -
#   Remarks     -
#   Configuration Type - COMPUTER
#==============================================================


AGE_DAYS=30

# SYSTEM LOG FILES
LOG_PATH="/private/var/log"
if [ -d "$LOG_PATH" ]; then
    find "$LOG_PATH" -maxdepth 1 -type f \
        -mtime +"$AGE_DAYS" -delete 2>/dev/null
    echo "System Log Files Cleanup Completed."
else
    echo "System log folder not found."
fi

# SYSTEM LIBRARY CACHES
CACHE_PATH="/Library/Caches"
# Symlink check first
[ -L "$CACHE_PATH" ] && {
    echo "Symlink detected for $CACHE_PATH. Skipping cleanup."
    exit 1
}
if [ -d "$CACHE_PATH" ]; then
    # Prevent cleanup if the cache path is a symlink
    find "$CACHE_PATH" -mindepth 1 -maxdepth 1 \
        -exec rm -rf {} + 2>/dev/null
    echo "System Library Caches Cleanup Completed."
else
    echo "System Library Caches folder not found."
fi

# CRASH AND DIAGNOSTIC REPORTS
DIAG_PATH="/Library/Logs/DiagnosticReports"

if [ -d "$DIAG_PATH" ]; then
    find "$DIAG_PATH" -type f \
        -mtime +"$AGE_DAYS" -delete 2>/dev/null
    echo "Crash and Diagnostic Reports Cleanup Completed."
else
    echo "DiagnosticReports folder not found."
fi

# ASL LOG ARCHIVES
ASL_PATH="/private/var/log/asl"

if [ -d "$ASL_PATH" ]; then
    find "$ASL_PATH" -type f \
        -mtime +"$AGE_DAYS" -delete 2>/dev/null
    echo "ASL Log Archives Cleanup Completed."
else
    echo "ASL log folder not found."
fi

# CUPS PRINT SPOOL
CUPS_PATH="/private/var/spool/cups"
if [ -d "$CUPS_PATH" ]; then
    launchctl bootout system/org.cups.cupsd 2>/dev/null
    sleep 2
    find "$CUPS_PATH" -maxdepth 1 -type f\
	\( -name "c[0-9]*" -o -name "d[0-9]*" \) -delete 2>/dev/null
    launchctl kickstart -p system/org.cups.cupsd 2>/dev/null
    echo "CUPS Print Spool Cleanup Completed."
else
    echo "CUPS spool folder not found."
fi

# UNIFIED LOG ARCHIVES
DIAG_DB_PATH="/private/var/db/diagnostics"
if [ -d "$DIAG_DB_PATH" ]; then
    find "$DIAG_DB_PATH" -type f \
        -mtime +"$AGE_DAYS" -delete 2>/dev/null
    echo "Unified Log Archives Cleanup Completed."
else
    echo "Unified log diagnostics folder not found."
fi

echo "System Level Cleanup Completed."
