#!/bin/bash
# Rsync to Samba share using permanent fstab mount
# Usage: ./rsync-to-samba.sh

set -euo pipefail

# Local source directory
SOURCE="./infoscreen_server_2025"

# Destination parent mount from fstab
DEST_PARENT="/mnt/nas_share"
DEST_SUBDIR="infoscreen_server_2025"
DEST_PATH="$DEST_PARENT/$DEST_SUBDIR"

# Exclude file (allows override via env)
EXCLUDE_FILE="${EXCLUDE_FILE:-exclude.txt}"

# Basic validations
if [ ! -d "$SOURCE" ]; then
  echo "Source directory not found: $SOURCE" >&2
  exit 1
fi

if [ ! -f "$EXCLUDE_FILE" ]; then
  echo "Exclude file not found: $EXCLUDE_FILE (expected in repo root)." >&2
  exit 1
fi

# Ensure the fstab-backed mount is active; don't unmount after sync
if ! mountpoint -q "$DEST_PARENT"; then
  echo "Mount point $DEST_PARENT is not mounted. Attempting to mount via fstab..."
  if ! sudo mount "$DEST_PARENT"; then
    echo "Failed to mount $DEST_PARENT. Check your /etc/fstab entry and /root/.nas-credentials." >&2
    exit 1
  fi
fi

# Ensure destination directory exists
mkdir -p "$DEST_PATH"

echo "Syncing files to $DEST_PATH ..."
rsync -avz --progress \
  --exclude-from="$EXCLUDE_FILE" \
  "$SOURCE/" "$DEST_PATH/"

echo "Sync completed successfully."
