#!/bin/bash
#
# Sync ~/Pictures to a NAS share, then run neatcli organize on both ends.
#
# Uses mount -t cifs with sudo (prompts for password if no credentials file).
# Create ~/.smb/mini.nas to avoid the password prompt each time:
#   echo -e "username=schmeeve\npassword=yourpass" > ~/.smb/mini.nas
#   chmod 600 ~/.smb/mini.nas
#
# Adjust SHARE and SUBPATH to match your environment.

SHARE="//mini.nas/miniShare1"
SUBPATH="Pictures"
MOUNTPOINT="/mnt/miniShare1"
CREDENTIALS="${HOME}/.smb/mini.nas"
SOURCE="${HOME}/Pictures"
START="$(date +%s)"

echo "[sync-pictures] Starting at $(date)"

# 1. Create mountpoint and mount if not already mounted
if mount | grep -q "${MOUNTPOINT}"; then
  echo "[sync-pictures] Already mounted at ${MOUNTPOINT}"
else
  echo "[sync-pictures] 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-pictures] ERROR: Failed to mount ${SHARE}"
    exit 1
  fi
  echo "[sync-pictures] Mounted at ${MOUNTPOINT}"
fi

# 2. One-way rsync contents of ~/Pictures → share subpath
MP="${MOUNTPOINT}/${SUBPATH}"
echo "[sync-pictures] Syncing ${SOURCE}/ → ${MP}/"
rsync -vrau \
  "${SOURCE}/" \
  "${MP}/" \
  --progress --stats \
  --exclude=".DS_Store"

# 3. Run neatcli organize on both source and dest
if command -v neatcli &>/dev/null; then
  echo "[sync-pictures] Organizing source: ${SOURCE}"
  neatcli organize --execute "${SOURCE}"
  echo "[sync-pictures] Organizing dest: ${MP}"
  neatcli organize --execute "${MP}"
else
  echo "[sync-pictures] WARNING: neatcli not found in PATH, skipping organize step"
fi

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