#!/usr/bin/env bash
#
# photos-originals-mount.sh — restore the Photos.app `originals/` subtree as a
# network-backed mount, replacing the dead NFS-on-black export.
#
# WHAT THIS IS
#   Before black died, ~/Pictures/Photos Library.photoslibrary/originals was a
#   symlink into an NFS mount. Photos.app read originals over NFS transparently;
#   the SQLite core (database/) + derivatives (resources/) stayed local on APFS.
#   This script reproduces that split with `rclone mount` over DO Spaces and a
#   bounded local LRU cache, so plum holds only hot originals and evicts the rest.
#
#   The mounted prefix holds a FAITHFUL COPY of the library's originals tree
#   (originals/<hex>/<UUID>.ext) — NOT macsync's blob keys. Both Photos.app and
#   macsync's IPhotoSync read the same mounted files; macsync additionally
#   uploads them under its own blob scheme for the ML pipeline. Two consumers,
#   one mount.
#
# PRECONDITIONS (operator, one-time)
#   1. macFUSE installed + kext approved in System Settings → Privacy & Security
#      (reboot may be required):           brew install --cask macfuse
#   2. rclone installed:                    brew install rclone
#   3. The originals tree is present in Spaces under $PREFIX (see the seed step
#      in §E3 of .project/storage-portability-plan.md — download from iCloud,
#      then `rclone copy` the tree up preserving paths).
#
# Secrets come from ~/.vault (0600), never from the environment or in-tree.

set -euo pipefail

# --- config (override via env) ---------------------------------------------
LIBRARY="${LIBRARY:-$HOME/Pictures/Photos Library.photoslibrary}"
MOUNTPOINT="${MOUNTPOINT:-$HOME/_/photos-originals}"   # where rclone mounts
CACHE_DIR="${CACHE_DIR:-$HOME/.cache/macsync-originals}"
CACHE_MAX="${CACHE_MAX:-20G}"                          # LRU ceiling on plum

# Shared Spaces/rclone config + creds from ~/.vault.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib/spaces-env.sh
source "$SCRIPT_DIR/lib/spaces-env.sh"
spaces_env_init

[ -d "$(dirname "$MOUNTPOINT")" ] || mkdir -p "$(dirname "$MOUNTPOINT")"
mkdir -p "$MOUNTPOINT" "$CACHE_DIR"

# Already mounted? (mount table lists the mountpoint)
if mount | grep -q " $MOUNTPOINT "; then
  echo "already mounted at $MOUNTPOINT"
  exit 0
fi

echo "mounting spaces://$BUCKET/$PREFIX → $MOUNTPOINT (cache ≤ $CACHE_MAX)"

# --vfs-cache-mode full → real POSIX read/write semantics Photos.app expects;
# --vfs-cache-max-size  → LRU eviction ceiling (keeps plum off 100%);
# --dir-cache-time      → keep the directory tree warm so Finder/Photos don't stall.
exec rclone mount ":s3:$BUCKET/$PREFIX" "$MOUNTPOINT" \
  --vfs-cache-mode full \
  --vfs-cache-max-size "$CACHE_MAX" \
  --vfs-cache-max-age 720h \
  --dir-cache-time 72h \
  --attr-timeout 5s \
  --cache-dir "$CACHE_DIR" \
  --volname "Lilith Photos Originals" \
  --no-modtime \
  --log-level INFO
