#!/bin/bash
#
# sync-comfyui-snaps — Pull new images from nimo.loc ComfyUI output, sync to NAS,
# then rename AI snaps and organize.
#
# Crontab (every 2 hours):
#   0 */2 * * * /home/schmeeve/.local/bin/sync-comfyui-snaps >> /home/schmeeve/.local/log/sync-comfyui-snaps.log 2>&1
#
# Requires: rsync, SSH key auth to nimo.loc (or runs directly on nimo.loc),
#           rename-ai-snaps and organize-images in ~/.local/bin/
#
# NAS credentials file at ~/.smb/mini.nas (chmod 600):
#   username=schmeeve
#   password=yourpass

# Source is local (this script runs on nimo.loc).
# Set NIMO_HOST to a remote hostname only if running this from another machine.
NIMO_HOST=""
NIMO_USER="schmeeve"
NIMO_SRC="/home/schmeeve/ComfyUI/output"

SHARE="//mini.nas/miniShare1"
NAS_SUBPATH="Pictures"
MOUNTPOINT="${HOME}/mnt/miniShare1"
CREDENTIALS="${HOME}/.smb/mini.nas"

RENAME_SCRIPT="${HOME}/git/schmeeve-toolz/rename-ai-snaps"
ORGANIZE_SCRIPT="${HOME}/git/schmeeve-toolz/organize-images"

START="$(date +%s)"
echo "[sync-comfyui-snaps] Starting at $(date)"

# 1. Mount NAS if not already mounted
if mount | grep -q "${MOUNTPOINT}"; then
  echo "[sync-comfyui-snaps] Already mounted at ${MOUNTPOINT}"
else
  echo "[sync-comfyui-snaps] Mounting ${SHARE} → ${MOUNTPOINT}"
  mkdir -p "${MOUNTPOINT}"
  OPTS="username=schmeeve,uid=$(id -u),gid=$(id -g),forceuid,forcegid,nounix,serverino"
  if [ -f "${CREDENTIALS}" ]; then
    OPTS="${OPTS},credentials=${CREDENTIALS}"
  fi
  sudo mount -t cifs "${SHARE}" "${MOUNTPOINT}" -o "${OPTS}"
  if ! mount | grep -q "${MOUNTPOINT}"; then
    echo "[sync-comfyui-snaps] ERROR: Failed to mount ${SHARE}"
    exit 1
  fi
  echo "[sync-comfyui-snaps] Mounted at ${MOUNTPOINT}"
fi

DEST="${MOUNTPOINT}/${NAS_SUBPATH}"
mkdir -p "${DEST}"

# 2. Rsync from nimo.loc ComfyUI output → NAS Pictures
# If running directly on nimo.loc, set NIMO_HOST="" and it will use a local path instead.
if [ -z "${NIMO_HOST}" ] || [ "${NIMO_HOST}" = "localhost" ]; then
  SRC="${NIMO_SRC}/"
else
  SRC="${NIMO_USER}@${NIMO_HOST}:${NIMO_SRC}/"
fi

echo "[sync-comfyui-snaps] Syncing ${SRC} → ${DEST}/"
rsync -vu --checksum \
  --include="*.png" --include="*.jpg" --include="*.jpeg" --include="*.webp" \
  --exclude="*" \
  --progress --stats \
  "${SRC}" "${DEST}/"

# 3. Rename AI snaps (non-interactive for automation)
if [ -x "${RENAME_SCRIPT}" ]; then
  echo "[sync-comfyui-snaps] Running rename-ai-snaps on ${DEST}"
  "${RENAME_SCRIPT}" "${DEST}" --no-interactive
else
  echo "[sync-comfyui-snaps] WARNING: rename-ai-snaps not found at ${RENAME_SCRIPT}"
fi

# 4. Organize images
if [ -x "${ORGANIZE_SCRIPT}" ]; then
  echo "[sync-comfyui-snaps] Running organize-images on ${DEST}"
  "${ORGANIZE_SCRIPT}" "${DEST}" -e
else
  echo "[sync-comfyui-snaps] WARNING: organize-images not found at ${ORGANIZE_SCRIPT}"
fi

DURATION=$(($(date +%s) - START))
echo "[sync-comfyui-snaps] Done in ${DURATION}s at $(date)"
