#!/bin/bash
# ============================================================
# THE EXPERTS — DARK DATA SCANNER for macOS
# Finds invisible junk, system debris, and forgotten files
# Usage: curl -sL https://darkdataclean.com/mac.sh | bash
# ============================================================

VERSION="1.0.0"
HOSTNAME=$(hostname)
USER_NAME=$(whoami)
DATE=$(date +"%Y-%m-%d %H:%M:%S")
# Find a writable location (Desktop symlinks may be broken due to Dropbox/iCloud)
REPORT_DATE=$(date +%Y%m%d-%H%M%S)
if [ -d "$HOME/Desktop" ] && [ -w "$HOME/Desktop" ]; then
    REPORT_FILE="$HOME/Desktop/DarkData-Report-${REPORT_DATE}.txt"
elif [ -d "$HOME/Documents" ] && [ -w "$HOME/Documents" ]; then
    REPORT_FILE="$HOME/Documents/DarkData-Report-${REPORT_DATE}.txt"
else
    REPORT_FILE="$HOME/DarkData-Report-${REPORT_DATE}.txt"
fi
# Test we can actually write
if ! touch "$REPORT_FILE" 2>/dev/null; then
    REPORT_FILE="/tmp/DarkData-Report-${REPORT_DATE}.txt"
fi

# Colors
RED='\033[0;31m'
YELLOW='\033[1;33m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'

# Check it's actually macOS
if [[ "$(uname)" != "Darwin" ]]; then
    echo "This scanner is for macOS only. For Linux, use linuxlockdown.com/darkdata.sh"
    exit 1
fi

MACOS_VERSION=$(sw_vers -productVersion)
MAC_MODEL=$(sysctl -n hw.model 2>/dev/null)

# Human-readable bytes
hsize() {
    local bytes=$1
    if [ "$bytes" -lt 1024 ]; then
        echo "${bytes}B"
    elif [ "$bytes" -lt 1048576 ]; then
        printf "%.0fKB\n" "$(echo "$bytes/1024" | bc -l)"
    elif [ "$bytes" -lt 1073741824 ]; then
        printf "%.0fMB\n" "$(echo "$bytes/1048576" | bc -l)"
    else
        printf "%.1fGB\n" "$(echo "$bytes/1073741824" | bc -l)"
    fi
}

# Directory size in bytes (fast, uses find)
dsize() {
    local dir=$1
    if [ -d "$dir" ]; then
        find "$dir" -type f -print0 2>/dev/null | xargs -0 stat -f '%z' 2>/dev/null | awk '{s+=$1} END{print s+0}'
    else
        echo 0
    fi
}

# Banner
clear
cat << 'BANNER'
╔══════════════════════════════════════════════════════════════╗
║                                                              ║
║         THE EXPERTS — DARK DATA SCANNER v1.0 (macOS)         ║
║                                                              ║
║   "Most people clean what they can see. Dark data is         ║
║    everything they can't. Invisible files, system junk,      ║
║    forgotten debris. All of it slowing you down."            ║
║                                                              ║
╚══════════════════════════════════════════════════════════════╝
BANNER

echo ""
echo "  Mac:        $MAC_MODEL"
echo "  User:       $USER_NAME"
echo "  macOS:      $MACOS_VERSION"
echo "  Scanning... this takes 30-90 seconds..."
echo ""

TOTAL=0
declare -a FINDINGS

echo -e "${CYAN}[1/18]${NC} Scanning ~/Library/Caches..."
LIB_CACHE=$(dsize "$HOME/Library/Caches")

echo -e "${CYAN}[2/18]${NC} Scanning ~/Library/Logs..."
LIB_LOGS=$(dsize "$HOME/Library/Logs")

echo -e "${CYAN}[3/18]${NC} Scanning Safari cache and history..."
SAFARI=$(dsize "$HOME/Library/Safari")
SAFARI_CACHE=$(dsize "$HOME/Library/Caches/com.apple.Safari")

echo -e "${CYAN}[4/18]${NC} Scanning Chrome cache..."
CHROME_CACHE=$(dsize "$HOME/Library/Caches/Google/Chrome")
CHROME_APP_CACHE=$(dsize "$HOME/Library/Application Support/Google/Chrome/Default/Cache")

echo -e "${CYAN}[5/18]${NC} Scanning Mail downloads..."
MAIL_DOWNLOADS=$(dsize "$HOME/Library/Containers/com.apple.mail/Data/Library/Mail Downloads")
MAIL_CACHE=$(dsize "$HOME/Library/Mail/V10/MailData/Envelope Index-shm" 2>/dev/null || echo 0)

echo -e "${CYAN}[6/18]${NC} Scanning Xcode derived data..."
XCODE_DERIVED=$(dsize "$HOME/Library/Developer/Xcode/DerivedData")
XCODE_ARCHIVES=$(dsize "$HOME/Library/Developer/Xcode/Archives")
XCODE_SIMS=$(dsize "$HOME/Library/Developer/CoreSimulator/Devices")
XCODE_TOTAL=$((XCODE_DERIVED + XCODE_ARCHIVES + XCODE_SIMS))

echo -e "${CYAN}[7/18]${NC} Scanning old iOS device backups..."
IOS_BACKUPS=$(dsize "$HOME/Library/Application Support/MobileSync/Backup")

echo -e "${CYAN}[8/18]${NC} Scanning Time Machine local snapshots..."
TM_SNAPS=$(tmutil listlocalsnapshots / 2>/dev/null | wc -l | tr -d ' ')
TM_SIZE=0
if [ "$TM_SNAPS" -gt 0 ]; then
    # Estimate ~500MB per snapshot (rough)
    TM_SIZE=$((TM_SNAPS * 524288000))
fi

echo -e "${CYAN}[9/18]${NC} Scanning Downloads folder..."
DOWNLOADS=$(dsize "$HOME/Downloads")

echo -e "${CYAN}[10/18]${NC} Scanning Trash..."
TRASH=$(dsize "$HOME/.Trash")

echo -e "${CYAN}[11/18]${NC} Scanning duplicate .DS_Store files..."
DS_STORE_COUNT=$(find "$HOME" -name ".DS_Store" 2>/dev/null | wc -l | tr -d ' ')
DS_STORE_SIZE=$(find "$HOME" -name ".DS_Store" -print0 2>/dev/null | xargs -0 stat -f '%z' 2>/dev/null | awk '{s+=$1} END{print s+0}')

echo -e "${CYAN}[12/18]${NC} Scanning screenshot clutter..."
DESKTOP_SHOTS=$(find "$HOME/Desktop" -name "Screenshot*.png" 2>/dev/null | wc -l | tr -d ' ')
DESKTOP_SHOTS_SIZE=$(find "$HOME/Desktop" -name "Screenshot*.png" -print0 2>/dev/null | xargs -0 stat -f '%z' 2>/dev/null | awk '{s+=$1} END{print s+0}')

echo -e "${CYAN}[13/18]${NC} Scanning Dropbox cache..."
DROPBOX_CACHE=$(dsize "$HOME/Dropbox/.dropbox.cache")

echo -e "${CYAN}[14/18]${NC} Scanning ~/Library/Application Support caches..."
APP_SUPPORT_CACHE=0
APP_SUPPORT_DIRS=("$HOME/Library/Application Support"/*/Cache "$HOME/Library/Application Support"/*/caches); for d in "${APP_SUPPORT_DIRS[@]}"; do
    [ -d "$d" ] && APP_SUPPORT_CACHE=$((APP_SUPPORT_CACHE + $(dsize "$d")))
done

echo -e "${CYAN}[15/18]${NC} Scanning Spotify cache..."
SPOTIFY=$(dsize "$HOME/Library/Caches/com.spotify.client")
SPOTIFY_APP=$(dsize "$HOME/Library/Application Support/Spotify/PersistentCache")

echo -e "${CYAN}[16/18]${NC} Scanning Zoom/Teams/Slack caches..."
ZOOM=$(dsize "$HOME/Library/Application Support/zoom.us")
TEAMS=$(dsize "$HOME/Library/Application Support/Microsoft/Teams/Cache")
SLACK=$(dsize "$HOME/Library/Application Support/Slack/Cache")
COMMS=$((ZOOM + TEAMS + SLACK))

echo -e "${CYAN}[17/18]${NC} Scanning node_modules (if any dev projects)..."
NODE_MODULES=0
if [ -d "$HOME/Documents" ] || [ -d "$HOME/Projects" ] || [ -d "$HOME/dev" ]; then
    NODE_MODULES=$(find "$HOME" -maxdepth 5 -name "node_modules" -type d -prune 2>/dev/null | xargs -I{} du -sh {} 2>/dev/null | awk '{s+=$1} END{print int(s*1048576)}')
fi

echo -e "${CYAN}[18/18]${NC} Calculating overall disk stats..."
DISK_USED=$(df -k / | awk 'NR==2{print $3*1024}')
DISK_TOTAL=$(df -k / | awk 'NR==2{print $2*1024}')
DISK_FREE=$(df -k / | awk 'NR==2{print $4*1024}')
DISK_PCT=$(df / | awk 'NR==2{gsub("%",""); print $5}')

# Calculate total dark data
TOTAL=$((LIB_CACHE + LIB_LOGS + SAFARI + SAFARI_CACHE + CHROME_CACHE + CHROME_APP_CACHE))
TOTAL=$((TOTAL + MAIL_DOWNLOADS + XCODE_TOTAL + IOS_BACKUPS + TM_SIZE + DOWNLOADS + TRASH))
TOTAL=$((TOTAL + DS_STORE_SIZE + DESKTOP_SHOTS_SIZE + DROPBOX_CACHE + APP_SUPPORT_CACHE))
TOTAL=$((TOTAL + SPOTIFY + SPOTIFY_APP + COMMS + NODE_MODULES))

echo ""
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${BOLD}                 MAC DARK DATA REPORT${NC}"
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
echo -e "  Mac:              ${BOLD}$MAC_MODEL${NC}"
echo -e "  macOS:            ${BOLD}$MACOS_VERSION${NC}"
echo -e "  Disk used:        $(hsize $DISK_USED) of $(hsize $DISK_TOTAL) (${DISK_PCT}%)"
echo -e "  Free space:       ${BOLD}$(hsize $DISK_FREE)${NC}"
echo ""
echo -e "${BOLD}  DARK DATA FOUND:${NC}"
echo ""

printf "  %-40s %12s %8s\n" "CATEGORY" "SIZE" "STATUS"
printf "  %-40s %12s %8s\n" "────────────────────────────────────────" "────────────" "────────"

report_line() {
    local name=$1
    local bytes=$2
    local threshold_mb=${3:-100}
    local threshold_bytes=$((threshold_mb * 1024 * 1024))
    local status color
    if [ "$bytes" -gt "$threshold_bytes" ]; then
        status="HIGH"; color=$RED
    elif [ "$bytes" -gt $((threshold_bytes / 10)) ]; then
        status="MEDIUM"; color=$YELLOW
    else
        status="LOW"; color=$GREEN
    fi
    printf "  %-40s %12s ${color}%8s${NC}\n" "$name" "$(hsize $bytes)" "$status"
}

report_line "App Caches (~/Library/Caches)" $LIB_CACHE 500
report_line "App Logs (~/Library/Logs)" $LIB_LOGS 50
report_line "Safari history + cache" $((SAFARI + SAFARI_CACHE)) 200
report_line "Chrome cache" $((CHROME_CACHE + CHROME_APP_CACHE)) 500
report_line "Mail attachments + cache" $MAIL_DOWNLOADS 500
report_line "Xcode derived/sim/archives" $XCODE_TOTAL 2000
report_line "iOS device backups" $IOS_BACKUPS 2000
report_line "Time Machine local snapshots" $TM_SIZE 1000
report_line "Downloads folder clutter" $DOWNLOADS 1000
report_line "Trash (not emptied)" $TRASH 100
report_line "Screenshot clutter on Desktop" $DESKTOP_SHOTS_SIZE 50
report_line "Dropbox cache" $DROPBOX_CACHE 500
report_line "App Support caches" $APP_SUPPORT_CACHE 300
report_line "Spotify cache" $((SPOTIFY + SPOTIFY_APP)) 500
report_line "Zoom/Teams/Slack caches" $COMMS 200
report_line "node_modules (dev projects)" $NODE_MODULES 500

echo ""
echo -e "${BOLD}  OTHER FINDINGS:${NC}"
printf "  %-40s %12s\n" ".DS_Store files cluttering folders" "$DS_STORE_COUNT"
printf "  %-40s %12s\n" "Desktop screenshots" "$DESKTOP_SHOTS"
printf "  %-40s %12s\n" "Local Time Machine snapshots" "$TM_SNAPS"

echo ""
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${BOLD}  TOTAL DARK DATA:        ${RED}$(hsize $TOTAL)${NC}"

PCT=$(awk -v t=$TOTAL -v u=$DISK_USED 'BEGIN{if(u>0) printf "%.1f", t*100/u; else print 0}')
echo -e "${BOLD}  % of used disk space:   ${RED}${PCT}%${NC}"
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""

# Save report
{
    echo "MAC DARK DATA REPORT"
    echo "===================="
    echo "Date:     $DATE"
    echo "Mac:      $MAC_MODEL"
    echo "User:     $USER_NAME"
    echo "macOS:    $MACOS_VERSION"
    echo ""
    echo "Disk:     $(hsize $DISK_USED) of $(hsize $DISK_TOTAL) used (${DISK_PCT}%)"
    echo "Free:     $(hsize $DISK_FREE)"
    echo ""
    echo "Library caches:       $(hsize $LIB_CACHE)"
    echo "Library logs:         $(hsize $LIB_LOGS)"
    echo "Safari:               $(hsize $((SAFARI + SAFARI_CACHE)))"
    echo "Chrome:               $(hsize $((CHROME_CACHE + CHROME_APP_CACHE)))"
    echo "Mail:                 $(hsize $MAIL_DOWNLOADS)"
    echo "Xcode:                $(hsize $XCODE_TOTAL)"
    echo "iOS backups:          $(hsize $IOS_BACKUPS)"
    echo "Time Machine snaps:   $(hsize $TM_SIZE) ($TM_SNAPS snapshots)"
    echo "Downloads:            $(hsize $DOWNLOADS)"
    echo "Trash:                $(hsize $TRASH)"
    echo "Desktop screenshots:  $(hsize $DESKTOP_SHOTS_SIZE) ($DESKTOP_SHOTS files)"
    echo "Dropbox cache:        $(hsize $DROPBOX_CACHE)"
    echo "App Support caches:   $(hsize $APP_SUPPORT_CACHE)"
    echo "Spotify:              $(hsize $((SPOTIFY + SPOTIFY_APP)))"
    echo "Comms (Zoom/Teams):   $(hsize $COMMS)"
    echo "node_modules:         $(hsize $NODE_MODULES)"
    echo ".DS_Store files:      $DS_STORE_COUNT"
    echo ""
    echo "TOTAL DARK DATA:      $(hsize $TOTAL) (${PCT}% of used disk)"
} > "$REPORT_FILE"

# What this means
echo -e "${BOLD}  WHAT THIS MEANS:${NC}"
echo ""
if [ "$TOTAL" -gt 21474836480 ]; then
    echo -e "  ${RED}⚠  Your Mac has ${BOLD}$(hsize $TOTAL)${NC}${RED} of invisible junk.${NC}"
    echo -e "  ${RED}   That's enough to make your Mac feel slow AND be using space you could reclaim.${NC}"
elif [ "$TOTAL" -gt 5368709120 ]; then
    echo -e "  ${YELLOW}⚠  Your Mac has $(hsize $TOTAL) of dark data.${NC}"
    echo -e "  ${YELLOW}   Worth cleaning — you'll get back real usable storage.${NC}"
else
    echo -e "  ${GREEN}✓  Your Mac is relatively clean ($(hsize $TOTAL) dark data).${NC}"
fi

echo ""
echo -e "${BOLD}  GET YOUR MAC CLEANED BY THE EXPERTS:${NC}"
echo ""
echo "  • One-off professional clean:      £49"
echo "  • Annual subscription (4 cleans):  £79/year"
echo "  • Apple Household (Mac+iPad+iPhone): £129/year"
echo ""
echo "  Remote session, 30-45 minutes, we walk you through everything"
echo "  you see cleared in real time. Before/after report included."
echo ""
echo -e "  ${CYAN}Book now: https://darkdataclean.com${NC}"
echo -e "  ${CYAN}Email:    hello@darkdataclean.com${NC}"
echo ""
echo "  Full report saved to: $REPORT_FILE"
echo ""
