#!/usr/bin/env bash
set -euo pipefail

HF_CACHE="${HF_HOME:-$HOME/.cache/huggingface}"
HF_DATASETS_CACHE="${HF_DATASETS_CACHE:-$HF_CACHE/datasets}"

echo "=== cleaning tmpfs and HF temp artifacts"

find /tmp -maxdepth 1 -user "$(whoami)" \( \
    -name "hf_*" -o \
    -name "*.arrow" -o \
    -name "*datasets*" \
\) -exec rm -rf {} + 2>/dev/null && echo "[+] /tmp cleaned" || true

if [ -d /dev/shm ]; then
    find /dev/shm -maxdepth 1 -user "$(whoami)" -type f -delete 2>/dev/null
    echo "[+] /dev/shm cleaned"
fi

RUN_USER="/run/user/$(id -u)"
if [ -d "$RUN_USER" ]; then
    find "$RUN_USER" -maxdepth 1 \( -name "torch_*" -o -name "hf_*" \) -exec rm -rf {} + 2>/dev/null || true
    echo "[+] $RUN_USER scanned"
fi

if [ -d "$HF_DATASETS_CACHE" ]; then
    find "$HF_DATASETS_CACHE" \( \
        -name "*.lock" -o \
        -name "tmp_*" -o \
        -name "*.incomplete" \
    \) -delete 2>/dev/null || true
    echo "[+] HF datasets cache cleaned: $HF_DATASETS_CACHE"
fi

D_TMP="/mnt/D/tmp"
if [ -d "$D_TMP" ]; then
    find "$D_TMP" -maxdepth 1 -mindepth 1 -mmin +60 -exec rm -rf {} + 2>/dev/null || true
    echo "[+] $D_TMP cleaned (entries older than 1h)"
fi

echo "[+] done"