#!/usr/bin/env perl

use strict;
use warnings;

use IPC::Open2 qw(open2);

=head1 NAME

markatzea - evaluate your markdown code blocks

=head1 SYNOPSIS

markatzea <file>

=head1 DESCRIPTION

B<markatzea> is a tool which takes markdown, evaluates code blocks with
interpreters and prints the output of those processes to a different codeblock.

=cut

while (my $line = <>) {
    unless ($line =~ /^```(\w+)\|?(\w+)?\s+(.+)/) {
        print $line;
        next;
    }

    my $lang = $1;
    my $out_lang = $2 || ""; # Out lang is optional
    my $command = $3;
    my $shell = $ENV{SHELL} || '/bin/sh';

    my $pid = open2(my $out, my $in, $shell, '-c', $command)
      or die "Failed to open subprocess: $!";

    print "```$lang\n";
    while ($line = <>) {
        print $line;
        last if $line =~ /^```/;
        print $in $line;
    }

    close($in);

    if (not eof $out) {

      print "```$out_lang\n";

      while (my $line = <$out>) {
        if ($line =~ /\n$/) {
          print $line;
        } else {
          print "$line\n";
        }
      }

      print "```\n";
    }

    waitpid($pid, 0);
    my $exit_status = $? >> 8;
    die "Child process exited with non-zero status $exit_status\n"
      if ($exit_status != 0);
}
