#!/usr/bin/env bash
# append_sigdl.sh — Append {{< sigdl >}} to posts (idempotent).
# Usage:
#   ./append_sigdl.sh [-c content] [-i "posts PhD_journey"] [-n]
# Options:
#   -c  content directory (default: content)
#   -i  space-separated subdirs under content (default: "posts PhD_journey")
#   -n  dry run

set -euo pipefail

CONTENT_DIR="content"
INCLUDE_DIRS=("posts" "PhD_journey" "about")
DRYRUN=0

while [[ $# -gt 0 ]]; do
  case "$1" in
    -c) CONTENT_DIR="${2:-content}"; shift 2 ;;
    -i) IFS=' ' read -r -a INCLUDE_DIRS <<< "${2:-}"; shift 2 ;;
    -n) DRYRUN=1; shift ;;
    -h|--help)
      echo "append_sigdl.sh [-c content] [-i \"posts PhD_journey\"] [-n]"; exit 0 ;;
    *) echo "Unknown arg: $1"; exit 1 ;;
  esac
done

TOTAL=0
UPDATED=0

for sub in "${INCLUDE_DIRS[@]}"; do
  ROOT="$CONTENT_DIR/$sub"
  [[ -d "$ROOT" ]] || { echo "skip missing: $ROOT"; continue; }
  while IFS= read -r -d '' md; do
    TOTAL=$((TOTAL+1))
    if grep -q '{{< *sigdl' "$md"; then
      echo "exists: $md"
      continue
    fi
    echo "append: $md"
    UPDATED=$((UPDATED+1))
    if [[ $DRYRUN -eq 0 ]]; then
      printf "\n\n---\n\n{{< sigdl >}}\n" >> "$md"
    fi
  done < <(find "$ROOT" -type f -name '*.md' -print0)
done

echo "Done. Files seen: $TOTAL, appended: $UPDATED."
[[ $DRYRUN -eq 1 ]] && echo "(dry run: no changes)"

