#!/usr/bin/perl
#------------------------------------------------------------------------------
#$Author: andrius $
#$Date: 2018-01-12 07:35:11 -0500 (Fri, 12 Jan 2018) $ 
#$Revision: 1082 $
#$URL: svn://saulius-grazulis.lt/restful/tags/v0.16.0/tools/scripts/validate-inner-html $
#------------------------------------------------------------------------------
#*
#  Pretty-prints the HTML, which is included in the input (if any).
#  Included HTML does not need to take up the whole input, as this
#  script only retrieves a part which is between '<!DOCTYPE html' and
#  '</html>' XML tags.
#**

use strict;
use warnings;

my @html;
my $is_html = 0;
while( <> ) {
    $is_html = 1 if /^<!DOCTYPE html/;
    push @html, $_ if $is_html;
    print $_ if !$is_html;
    if( /^<\/html>/ && @html ) {
        html_pp( @html );
        @html = ();
        $is_html = 0;
    }
}

sub html_pp
{
    my @lines = @_;

    my $pid = open( my $out, "-|" );
    if( $pid ) { # parent process; read from $xmllint what child and its
                 # subprocesses have printed to STDOUT
        binmode( $out, ":utf8" );
        local $/ = ""; # read in paragraph mode
        my @values = <$out>;
        print join "\n", @values;
        wait;
        die if $?;
        close $out;
    } else { # child process; print to STDOUT anything what you want
             # the parent to see comming from $xmllint.

        open( my $xmllint,
              '| xmllint --format -' )
            or die( "error calling the 'xmllint' pipe -- $!" );

        print $xmllint @lines;
        close $xmllint or die "error closing the 'xmllint' pipe -- $!";

        exit 0
    }
}
