#!/usr/bin/env bash
# Evaluate an org src block using Emacs batch mode
# Usage: org-eval <org-file> [block-index]
#   block-index is 1-based (first block = 1).
#   If omitted, evaluates ALL blocks.

set -e

if [ $# -lt 1 ]; then
    echo "Usage: org-eval <org-file> [block-index]"
    echo "  Evaluates src blocks in the org file"
    echo "  block-index is 1-based (first block = 1)"
    echo "  If omitted, evaluates ALL blocks"
    exit 1
fi

ORG_FILE="$1"
BLOCK_INDEX="${2:-}"

if [ ! -f "$ORG_FILE" ]; then
    echo "Error: File not found: $ORG_FILE"
    exit 1
fi

echo "Evaluating: $ORG_FILE"

if [ -n "$BLOCK_INDEX" ]; then
    # 1-based indexing: subtract 1 for Emacs' dotimes (0-based)
    if [ "$BLOCK_INDEX" -lt 1 ]; then
        echo "Error: block-index must be 1 or greater" >&2
        exit 1
    fi
    SKIP=$((BLOCK_INDEX - 1))
    # Evaluate specific block
    emacs --batch \
        --load org \
        --eval "(setq org-confirm-babel-evaluate nil)" \
        --eval "(with-current-buffer (find-file-noselect \"$ORG_FILE\") \
                 (goto-char (point-min)) \
                 (dotimes (_ $SKIP) \
                   (org-babel-next-src-block)) \
                 (if (org-in-src-block-p t) \
                     (org-babel-execute-src-block) \
                   (error \"Block $BLOCK_INDEX not found\")))"
else
    # Evaluate all blocks
    emacs --batch \
        --load org \
        --eval "(setq org-confirm-babel-evaluate nil)" \
        --eval "(org-babel-execute-buffer)"
fi

echo "Done."
