#!/bin/bash
#
# Sync ~/webGoggles to a NAS share.
#
# Uses mount -t cifs with sudo (prompts for password if no credentials file).
# Create ~/.smb/ts.nas to avoid the password prompt each time:
#   echo -e "username=schmeeve\npassword=yourpass" > ~/.smb/ts.nas
#   chmod 600 ~/.smb/ts.nas
#
# No deletes or overwrites: rsync --backup renames any existing dest file
# with a -CONFLICT suffix before writing the source version.
#
# Adjust SHARE, SUBPATH, and SOURCE to match your environment.

SHARE="//ts.nas/aura"
SUBPATH="webGoggles"
MOUNTPOINT="${HOME}/mnt/ts.nas/aura"
CREDENTIALS="${HOME}/.smb/ts.nas"
SOURCE="${HOME}/webGoggles"
START="$(date +%s)"

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

# Verify source exists
if [ ! -d "${SOURCE}" ]; then
  echo "[sync-webgoggles] ERROR: Source ${SOURCE} does not exist"
  exit 1
fi

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

# 2. One-way rsync of SOURCE into the share subpath
MP="${MOUNTPOINT}/${SUBPATH}"
mkdir -p "${MP}"
echo "[sync-webgoggles] Syncing ${SOURCE}/ → ${MP}/"
rsync -vrau \
  "${SOURCE}/" \
  "${MP}/" \
  --backup \
  --suffix="-CONFLICT" \
  --exclude=".DS_Store" \
  --progress --stats

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