#!/bin/bash

# 需求:
# 1.把 ComfyUI_x/output 中的文件打包到 bak/YYYY-MM-DD.tar.gz
# 2.成功后删除原文件

# 环境: Ubuntu 22.04
# 执行:
# chmod +x ./clean-output.sh
# dos2unix ./clean-output.sh
# sh ./clean-output.sh

# 定时任务
# crontab -e
# 0 0 */3 * * /mnt/nvme0n1/ComfyUI/clean-output.sh >> /var/log/clean-output.log 2>&1
# crontab -l

set -euo pipefail

# 根目录列表
COMFY_ROOTS=(
	/mnt/nvme0n1/ComfyUI/ComfyUI_0
	# /mnt/nvme0n1/ComfyUI/ComfyUI_1
	# /mnt/nvme0n1/ComfyUI/ComfyUI_2
	# /mnt/nvme0n1/ComfyUI/ComfyUI_3
	# /mnt/nvme0n1/ComfyUI/ComfyUI_4
	# /mnt/nvme0n1/ComfyUI/ComfyUI_5
	# /mnt/nvme0n1/ComfyUI/ComfyUI_6
	# /mnt/nvme0n1/ComfyUI/ComfyUI_7
)

DATE=$(date +%F)                # 2025-07-21
LOG="/var/log/clean-output.log"

# 写日志函数
log() {
	echo "[$(date '+%F %T')] $*" | tee -a "$LOG"
}

log "===== Starting backup ====="

for r in "${COMFY_ROOTS[@]}"; do
	SRC_DIR="${r}/output"
	BAK_DIR="${SRC_DIR}/bak"

	# 如果 output 为空则跳过
	[[ -d "$SRC_DIR" ]] || { log "$SRC_DIR 不存在，跳过"; continue; }
	[[ -n "$(ls -A "$SRC_DIR")" ]] || { log "$SRC_DIR 为空，跳过"; continue; }

	mkdir -p "$BAK_DIR"
	TAR_FILE="${BAK_DIR}/${DATE}.tar.gz"

	log "开始打包 $SRC_DIR -> $TAR_FILE"

	tar -czf "$TAR_FILE" -C "$SRC_DIR" --exclude='bak' . && {
	# tar -cJf "${TAR_FILE%.tar.gz}.tar.xz" -C "$SRC_DIR" --exclude='bak' . && {
		log "打包完成，开始清理源文件"
		# 删除除 bak 以外的文件/目录
		find "$SRC_DIR" -mindepth 1 ! -path "${BAK_DIR}*" -delete
		log "$SRC_DIR 已清理"
	} || {
		log "打包失败，保留源文件"
	}
done

log "===== Backup finished ====="

# 重新解压出来
# tar -xzf 2025-07-21.tar.gz -C /mnt/nvme0n1/ComfyUI/ComfyUI_0/output/