#!/bin/bash

# Sync Obsidian content to Astro blog
# This script copies content from Obsidian vault to the blog's content directories
# while preserving the structure and automatically handling images

set -e

# Configuration
OBSIDIAN_PATH="/mnt/synology/obsidian/Public/Blog"
BLOG_PATH="$(pwd)"
CONTENT_PATH="$BLOG_PATH/src/content"
IMAGES_SOURCE="$OBSIDIAN_PATH/images"
IMAGES_DEST="$BLOG_PATH/public/blog/images"

echo "🔄 Syncing Obsidian content to blog..."

# Ensure destination directories exist
mkdir -p "$CONTENT_PATH/blog"
mkdir -p "$IMAGES_DEST/posts"
mkdir -p "$IMAGES_DEST/placeholders"

# Sync all markdown files from Obsidian to blog content
echo "📝 Copying markdown files..."
find "$OBSIDIAN_PATH" -name "*.md" | while read file; do
    # Get relative path
    rel_path=$(realpath --relative-to="$OBSIDIAN_PATH" "$file")
    dest_file="$CONTENT_PATH/blog/$rel_path"
    
    # Create destination directory if it doesn't exist
    mkdir -p "$(dirname "$dest_file")"
    
    # Copy file with image path correction
    sed 's|!\[\(.*\)\](\(.*\))|![\1](/blog/images/posts/\2)|g' "$file" > "$dest_file"
    
    echo "  ✅ Copied: $rel_path"
done

# Sync images
echo "🖼️  Copying images..."
if [ -d "$IMAGES_SOURCE" ]; then
    rsync -av --delete "$IMAGES_SOURCE/" "$IMAGES_DEST/posts/"
    echo "  ✅ Images synced"
else
    echo "  ⚠️  Warning: Image source directory not found"
fi

# Fix permissions
chmod -R 755 "$CONTENT_PATH/blog"
chmod -R 755 "$IMAGES_DEST"

echo "🚀 Sync completed successfully!"
echo "✨ You can now run 'npm run dev' to view your blog" 