#!/bin/bash

if [ -z "$1" ]; then
  echo "Usage: $0 <file>"
  exit 1
fi

input_file="$1"

if [ ! -f "$input_file" ]; then
  echo "Error: File $input_file not found" >&2
  exit 1
fi

# Read file content
content=$(cat "$input_file")

while true; do
    # Extract the first filename found in the ~>> ... <<~ pattern
    # Use sed to capture the filename between the delimiters
    inc_file=$(echo "$content" | sed -n 's/.*~>>[[:space:]]*\([^[:space:]]*\)[[:space:]]*<<~.*/\1/p' | head -n 1)
    
    if [ -z "$inc_file" ]; then
        break
    fi
    
    if [ -f "$inc_file" ]; then
        # Read include file and strip trailing newline
        inc_content=$(cat "$inc_file" | tr -d '\n')
        # Use sed to replace the first occurrence of the tag for this specific file
        # We escape the delimiters for sed just in case
        content=$(echo "$content" | sed "s/~>>[[:space:]]*$inc_file[[:space:]]*<<~/$inc_content/")
    else
        echo "Error: Included file $inc_file not found" >&2
        exit 1
    fi
done

if [ -n "$2" ]; then
  echo -n "$content" > "$2"
else
  echo -n "$content"
fi
