#!/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.

RECURSIVE=""
SUBDIR=""

for arg in "$@"; do
  case "$arg" in
    --help|-h)
      cat <<'EOF'
Usage: sync-pictures [options] [<subdir>]

Sync ~/Pictures (or a subdirectory) to a NAS share and run neatcli organize on both ends.

Options:
  -r, --recursive   Sync recursively (default: top-level files only)
  -h, --help        Show this help message and exit

If <subdir> is given, sync only that subdirectory relative to ~/Pictures.
Use '.' to refer to ~/Pictures itself.
EOF
      exit 0
      ;;
    --recursive|-r)
      RECURSIVE=1
      ;;
    *)
      [ -z "${SUBDIR}" ] && SUBDIR="${arg}" || {
        echo "[sync-pictures] ERROR: Unexpected argument: ${arg}"
        exit 1
      }
      ;;
  esac
done

SHARE="//mini.nas/miniShare1"
SUBPATH="Pictures"
MOUNTPOINT="${HOME}/mnt/miniShare1"
CREDENTIALS="${HOME}/.smb/mini.nas"
SOURCE="${HOME}/Pictures"
if [ -n "${SUBDIR}" ] && [ "${SUBDIR}" != "." ]; then
  SOURCE="${SOURCE}/${SUBDIR}"
  SUBPATH="${SUBPATH}/${SUBDIR}"
fi
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}/"
if [ -n "${RECURSIVE}" ]; then
  rsync -vur \
    "${SOURCE}/" \
    "${MP}/" \
    --progress --stats \
    --exclude=".DS_Store"
else
  rsync -vu --exclude='*/' \
    "${SOURCE}/" \
    "${MP}/" \
    --progress --stats \
    --exclude=".DS_Store"
fi

# 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)"
