#!/bin/bash

echo -e '20 text/gemini\r'

# check for shebang to determine whether to miss 1st line off
if head -n 1 $1 | grep -q '^#!'
then
    getter="tail -n +2 $1"
else
    getter="cat $1"
fi

mode=normal

while read line
do
    if [ $mode == exec ]
    then
        if [ "$line" == ":::" ]
        then
            # end exec block + execute
            mode=normal
            $executor $script
        else
            # write this line to the temp file
            echo "$line" >> $script
        fi
    elif [[ "^$line" =~ "^:::" ]]
    then
        # begin exec block
        mode=exec
        executor="$(sed -E 's/^:::(.+)$/\1/' <<< $line)"
        script="$(mktemp)"
    else
        # normal text
        echo "$line"
    fi
done <<< $($getter)