#!/bin/bash

# Debugging: Print commands as they are executed
set -x

# Define source and destination directories
SOURCE_DIR=~/obsidian
DEST_DIR=/home/ac1dburn/obsidian-site/content
IMAGE_DIR=$DEST_DIR/images

# Ensure destination directories exist
mkdir -p "$DEST_DIR"
mkdir -p "$IMAGE_DIR"

# Temporary log for copied files
LOG_FILE=/tmp/copied_files.log

# Clear the log file
> "$LOG_FILE"

# Find Markdown files with "publish: true" and process them
find -L "$SOURCE_DIR" -type f -name "*.md" -exec grep -q "publish: true" {} \; -exec grep -l "publish: true" {} + | while read -r markdown_file; do
    # Extract relative path from the source directory
    relative_path="${markdown_file#$SOURCE_DIR/}"

    # Destination path
    dest_path="$DEST_DIR/$relative_path"

    # Copy the Markdown file
    cp "$markdown_file" "$dest_path"
    echo "Copied $markdown_file to $dest_path" >> "$LOG_FILE"

    # Extract and copy referenced images
    grep -o '\!\[\[.*\]\]' "$markdown_file" | sed 's/\!\[\[\(.*\)\]\]/\1/' | while IFS= read -r image_ref; do
        image_path="$SOURCE_DIR/$image_ref"
        
        # Debugging: Print image_path
        echo "Checking image_path: $image_path" >> "$LOG_FILE"
        
        if [ -f "$image_path" ]; then
            cp "$image_path" "$IMAGE_DIR/"
            echo "Copied image $image_ref to $IMAGE_DIR/" >> "$LOG_FILE"
        else
            echo "Image reference $image_ref in $markdown_file does not exist." >> "$LOG_FILE"
        fi
    done
done

# Print the log file
cat "$LOG_FILE"

# Debugging: Indicate completion
echo "Script execution completed."