#!/bin/bash
set -euo pipefail

TARGET_DIR="${1:-.}"
RETENTION_DAYS="${2:-0}"   # 0 表示不限时间，直接清理

PATTERNS=(
  "*.tar.gz" "*.tar.gz.*" "*.tgz"
  "*.tar.bz2" "*.tbz2"
  "*.tar.xz" "*.txz"
  "*.zip" "*.7z" "*.rar"
  "*.tar"
  "wget-log*" "wget.log*" "*.wget.log"
)

cd "$TARGET_DIR" || { echo "无法进入目录: $TARGET_DIR"; exit 1; }
LOG_FILE="./cleanup_$(date +%Y%m%d).log"
log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOG_FILE"; }

log "开始清理目录: $(pwd)  保留天数: $RETENTION_DAYS"
TOTAL_COUNT=0; TOTAL_SIZE=0

for pattern in "${PATTERNS[@]}"; do
  if [ "$RETENTION_DAYS" -gt 0 ]; then
    mapfile -d '' files < <(find . -maxdepth 1 -type f -name "$pattern" -mtime +"$RETENTION_DAYS" -print0)
  else
    mapfile -d '' files < <(find . -maxdepth 1 -type f -name "$pattern" -print0)
  fi
  for f in "${files[@]}"; do
    [ -e "$f" ] || continue
    size=$(stat -c%s "$f" 2>/dev/null || stat -f%z "$f" 2>/dev/null || echo 0)
    TOTAL_SIZE=$((TOTAL_SIZE + size)); TOTAL_COUNT=$((TOTAL_COUNT + 1))
    log "删除: $f (${size} 字节)"
    rm -f -- "$f"
  done
done

HUMAN_SIZE=$(numfmt --to=iec --suffix=B "$TOTAL_SIZE" 2>/dev/null || echo "${TOTAL_SIZE}B")
log "清理完成，共删除 ${TOTAL_COUNT} 个文件，释放 ${HUMAN_SIZE} 空间"
find . -maxdepth 1 -type f -name "cleanup_*.log" -mtime +30 -delete