#!/bin/bash

# ─────────────────────────────────────────────────────────────
# clear_caches.sh
# CalAudit — Cache Care // ADB Cache Clearing Script
# https://calaudit.org
#
# Clears all app caches on a connected Android device via ADB.
# Does NOT clear app data.
#
# WHAT THIS SCRIPT DOES:
#   1. Checks that ADB is installed and a device is connected
#   2. Detects your Android API level
#   3. API 24+ (Android 7+): runs cmd package trim-caches —
#      the same command Android calls internally when storage
#      runs low. Clears all app caches in one shot.
#   4. Below API 24: exits safely — no safe ADB cache method
#      exists without root on older Android versions
#
# WHY NOT pm clear --cache-only:
#   Despite being documented, this flag hangs silently on many
#   Android builds including Android 14. trim-caches is the
#   reliable Google-supported path for all API 24+ devices.
#
# WHAT THIS SCRIPT DOES NOT DO:
#   - Does not clear app data, saved logins, or preferences
#   - Does not require root
#   - Does not install anything
#   - Does not connect to the internet
#
# REQUIREMENTS:
#   - ADB installed and in your PATH
#   - Android device connected via USB with USB Debugging enabled
#   - Device screen unlocked and RSA fingerprint accepted
# ─────────────────────────────────────────────────────────────

set -euo pipefail

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
RESET='\033[0m'

echo ""
echo -e "${CYAN}╔══════════════════════════════════════════╗${RESET}"
echo -e "${CYAN}║     CalAudit — Cache Care // ADB Tool    ║${RESET}"
echo -e "${CYAN}╚══════════════════════════════════════════╝${RESET}"
echo ""

# ── Step 1: Check ADB is installed ──
echo -e "${CYAN}[1/4]${RESET} Checking ADB installation..."
if ! command -v adb &> /dev/null; then
    echo -e "${RED}✗ ADB not found.${RESET}"
    echo "  Install with: sudo apt install adb"
    echo "  Or download Android Platform Tools from developer.android.com"
    exit 1
fi
echo -e "${GREEN}✓ ADB found:${RESET} $(adb version | head -1)"
echo ""

# ── Step 2: Check device is connected ──
echo -e "${CYAN}[2/4]${RESET} Checking for connected device..."
DEVICE_COUNT=$(adb devices | grep -c "device$" || true)

if [ "$DEVICE_COUNT" -eq 0 ]; then
    echo -e "${RED}✗ No device found.${RESET}"
    echo ""
    echo "  Checklist:"
    echo "  → USB cable is connected"
    echo "  → Developer Options is enabled on your phone"
    echo "  → USB Debugging is toggled ON"
    echo "  → Your phone screen is unlocked"
    echo "  → You tapped 'Allow' on the RSA fingerprint prompt"
    echo ""
    echo "  Then run this script again."
    exit 1
fi

DEVICE_SERIAL=$(adb devices | grep "device$" | head -1 | cut -f1)
echo -e "${GREEN}✓ Device connected:${RESET} $DEVICE_SERIAL"
echo ""

# ── Step 3: Detect Android API level ──
echo -e "${CYAN}[3/4]${RESET} Detecting Android version..."
API_LEVEL=$(adb shell getprop ro.build.version.sdk | tr -d '[:space:]')
ANDROID_VERSION=$(adb shell getprop ro.build.version.release | tr -d '[:space:]')

echo -e "${GREEN}✓ Android $ANDROID_VERSION${RESET} (API $API_LEVEL)"
echo ""

if [ "$API_LEVEL" -lt 24 ]; then
    echo -e "${RED}✗ Android version too old for safe cache-only clearing via ADB.${RESET}"
    echo ""
    echo "  API 23 and below: the only available ADB cache command is 'pm clear'"
    echo "  which wipes ALL app data — not just cache. This script will not run"
    echo "  that command as it would delete your saved logins and app data."
    echo ""
    echo "  Safe alternative: Settings → Apps → [App] → Storage → Clear Cache"
    exit 1
fi

# ── Step 4: Clear all caches ──
echo -e "${CYAN}[4/4]${RESET} Clearing all app caches..."
echo ""
echo -e "  Method: ${YELLOW}cmd package trim-caches${RESET}"
echo "  This is the same operation Android runs internally when"
echo "  your storage runs low. Clears all app caches at once."
echo ""

adb shell cmd package trim-caches 999999999999

echo ""
echo -e "${GREEN}────────────────────────────────────────────${RESET}"
echo -e "${GREEN}✓ Done.${RESET}"
echo ""
echo "  Your app data, saved logins, and preferences are untouched."
echo "  Caches will rebuild automatically as you use your apps."
echo ""
echo -e "  ${CYAN}calaudit.org — Cache Care${RESET}"
echo ""
