#!/bin/bash
# cleanmacapps Mac Score — read-only. Open source. Read it before you run it.
#
# What it does: counts and measures a few things on your Mac and prints the totals.
# What it does NOT do: delete, move or change anything. Send anything anywhere.
#   It prints numbers only (never file names, app names, or personal data).
#   Nothing leaves your Mac unless YOU open the claim link it prints.
#
# Run:    bash score.sh          (prints your numbers + a claim link)
#         bash score.sh --open   (also opens the claim link in your browser)
# Needs:  macOS 11 or later. No sudo. No installs.
set -u
SITE="https://cleanmacapps.com"
V=1

say() { printf '%s\n' "$*"; }
num() { case "$1" in ''|*[!0-9]*) echo "";; *) echo "$1";; esac; }

# 1. macOS version, Mac model, chip
OS=$(sw_vers -productVersion 2>/dev/null)
MID=$(sysctl -n hw.model 2>/dev/null)
MNAME=$(system_profiler SPHardwareDataType 2>/dev/null | awk -F': ' '/Model Name/{print $2; exit}')
CHIP=$(sysctl -n machdep.cpu.brand_string 2>/dev/null)

# 2. Uptime in days
BOOT=$(sysctl -n kern.boottime 2>/dev/null | sed -E 's/^\{ sec = ([0-9]+),.*/\1/')
UP=""; [ -n "$(num "$BOOT")" ] && UP=$(( ( $(date +%s) - BOOT ) / 86400 ))

# 3. Disk: total and free GB on the data volume
DVOL=/System/Volumes/Data; [ -d "$DVOL" ] || DVOL=/
read -r DT DF <<<"$(df -k "$DVOL" 2>/dev/null | awk 'NR==2{printf "%d %d", $2/1048576, $4/1048576}')"

# 4. Size of ~/Library/Caches in MB
CACHE=$(du -sk "$HOME/Library/Caches" 2>/dev/null | awk '{printf "%d", $1/1024}')

# 5. Orphaned Application Support folders: folders with no matching installed app (heuristic)
APPS=""
APPCOUNT=0
for a in /Applications/*.app /Applications/*/*.app "$HOME"/Applications/*.app /System/Applications/*.app /System/Applications/Utilities/*.app; do
  [ -d "$a" ] || continue
  n=$(basename "$a" .app | tr '[:upper:]' '[:lower:]' | tr -d ' ')
  b=$(/usr/libexec/PlistBuddy -c 'Print CFBundleIdentifier' "$a/Contents/Info.plist" 2>/dev/null | tr '[:upper:]' '[:lower:]')
  APPS="$APPS$n"$'\n'"$b"$'\n'
  case "$a" in /System/*) ;; *) APPCOUNT=$((APPCOUNT+1));; esac
done
ORPH=0; ORPHMB=0
for d in "$HOME/Library/Application Support"/*/; do
  [ -d "$d" ] || continue
  f=$(basename "$d"); k=$(printf '%s' "$f" | tr '[:upper:]' '[:lower:]' | tr -d ' ')
  case "$k" in com.apple.*|apple|addressbook|callhistory*|cloudkit|crashreporter|dock|fileprovider|icloud|knowledge|mobilesync|syncservices|ubiquity|networkserviceproxy|animoji|accounts|identityservices|homeenergyd|*.savedstate|"") continue;; esac
  printf '%s\n' "$APPS" | grep -qiF -- "$k" && continue
  hit=0
  while IFS= read -r line; do
    [ ${#line} -ge 4 ] || continue
    case "$k" in *"$line"*) hit=1; break;; esac
  done <<<"$APPS"
  [ $hit -eq 1 ] && continue
  ORPH=$((ORPH+1))
  s=$(du -sk "$d" 2>/dev/null | awk '{print $1}'); ORPHMB=$((ORPHMB + ${s:-0}/1024))
done

# 6. Background jobs: LaunchAgents (yours + system-wide) and LaunchDaemons, third-party only (Apple's live in /System)
LA=$(ls "$HOME"/Library/LaunchAgents/*.plist /Library/LaunchAgents/*.plist 2>/dev/null | wc -l | tr -d ' ')
LD=$(ls /Library/LaunchDaemons/*.plist 2>/dev/null | wc -l | tr -d ' ')

# 7. Apps not opened in 90+ days (Spotlight's "last used" date; never-opened counts too)
STALE=0; CUT=$(( $(date +%s) - 90*86400 ))
for a in /Applications/*.app "$HOME"/Applications/*.app; do
  [ -d "$a" ] || continue
  d=$(mdls -raw -name kMDItemLastUsedDate "$a" 2>/dev/null)
  if [ -z "$d" ] || [ "$d" = "(null)" ]; then STALE=$((STALE+1)); continue; fi
  t=$(date -j -f "%Y-%m-%d %H:%M:%S %z" "$d" +%s 2>/dev/null || echo 0)
  [ "$t" -lt "$CUT" ] && STALE=$((STALE+1))
done

# 8. Battery cycle count + condition (laptops only)
PWR=$(system_profiler SPPowerDataType 2>/dev/null)
CYC=$(printf '%s' "$PWR" | awk -F': ' '/Cycle Count/{print $2; exit}')
COND=$(printf '%s' "$PWR" | awk -F': ' '/Condition/{print $2; exit}')

# 9. Apps allowed to use camera / microphone / location.
#    macOS protects this list. Without Full Disk Access for Terminal it can't be read, and we report "unknown".
TCC="$HOME/Library/Application Support/com.apple.TCC/TCC.db"
CAM=""; MIC=""
if [ -r "$TCC" ] && command -v sqlite3 >/dev/null; then
  CAM=$(sqlite3 "$TCC" "SELECT count(*) FROM access WHERE service='kTCCServiceCamera' AND auth_value=2" 2>/dev/null)
  MIC=$(sqlite3 "$TCC" "SELECT count(*) FROM access WHERE service='kTCCServiceMicrophone' AND auth_value=2" 2>/dev/null)
fi
LOC="" # location grants live in a root-only file; a no-sudo script can't read them

enc() { local s="$1" o="" c i; for ((i=0;i<${#s};i++)); do c=${s:i:1}; case "$c" in [a-zA-Z0-9.~_-]) o+="$c";; *) o+=$(printf '%%%02X' "'$c");; esac; done; printf '%s' "$o"; }
Q="v=$V&os=$(enc "$OS")&mid=$(enc "$MID")&mn=$(enc "$MNAME")&chip=$(enc "$CHIP")&up=$UP&dt=$DT&df=$DF&cache=$CACHE&orph=$ORPH&orphmb=$ORPHMB&apps=$APPCOUNT&la=$LA&ld=$LD&stale=$STALE&cyc=$CYC&cond=$(enc "$COND")&cam=$CAM&mic=$MIC&loc=$LOC"
URL="$SITE/claim?$Q"

say ""
say "  YOUR MAC — numbers only"
say "  ------------------------------------------"
say "  macOS               $OS"
say "  Model               $MNAME ($MID)"
say "  Chip                $CHIP"
say "  Uptime              ${UP:-?} days"
say "  Disk                ${DF:-?} GB free of ${DT:-?} GB"
say "  Caches folder       ${CACHE:-?} MB"
say "  Orphaned app data   $ORPH folders, $ORPHMB MB  (no matching app found)"
say "  Background jobs     $LA agents, $LD daemons"
say "  Apps (yours)        $APPCOUNT, $STALE not opened in 90+ days"
say "  Battery             ${CYC:-no battery} cycles${COND:+, $COND}"
say "  Camera / mic grants ${CAM:-unknown} / ${MIC:-unknown}"
say ""
say "  Your score card (nothing is saved until you press Publish on the page):"
say "  $URL"
say ""
[ "${1:-}" = "--open" ] && open "$URL"
exit 0
