#!/bin/bash

# Current date for the 'updated' field
current_date=$(date +%F)

# Recursive search for all markdown files in the content folder
find ../content -type f -name "*.md" | while read file; do
  # Check if the file has frontmatter enclosed in +++
  if [ "$(head -n 1 "$file")" = "+++" ]; then
    # Check if the 'date' field exists in the frontmatter
    if grep -q '^date\s*=' "$file"; then
      # Check if the 'updated' field is already present
      if grep -q '^updated\s*=' "$file"; then
        echo "✘ Skipped: 'updated' field already present in $file"
      else
        # Use awk to insert the 'updated' field after the 'date' field
        awk -v date="$current_date" '
        BEGIN { inserted=0 }
        /^date\s*=/ && inserted == 0 {
          print $0
          print "updated = " date
          inserted = 1
          next
        }
        { print }
        ' "$file" > "$file.tmp" && mv "$file.tmp" "$file"

        echo "✔ Inserted 'updated' after date in $file"
      fi
    else
      echo "✘ No date field found in the frontmatter of $file"
    fi
  else
    echo "✘ No frontmatter found in $file"
  fi
done
