#!/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

# Check if source directory exists
if [ ! -d "$SOURCE_DIR" ]; then
    echo "Source directory $SOURCE_DIR does not exist!"
    exit 1
fi

# Check if destination directory exists, if not create it
if [ ! -d "$DEST_DIR" ]; then
    mkdir -p "$DEST_DIR"
fi

# Find markdown files where publish: true exists in the YAML front matter
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/}"
    
    # Extract directory path
    dir_path=$(dirname "$relative_path")
    
    # Create the corresponding directory structure in the destination directory
    mkdir -p "$DEST_DIR/$dir_path"
    
    # Copy markdown file to the destination directory
    cp "$markdown_file" "$DEST_DIR/$relative_path"
    
    # Debugging: Log the operations being performed
    echo "Copied $markdown_file to $DEST_DIR/$relative_path"
done

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