#!/home/ben/software/install/bin/perl
use warnings;
use strict;
use utf8;
use FindBin '$Bin';
use lib '/home/ben/projects/html-valid/blib/lib';
use lib '/home/ben/projects/html-valid/blib/arch';
use HTML::Valid 'sanitize_errors';
use Path::Tiny;
#use LWP::UserAgent;

# True if we can use the World Wide Web.
my $webok;
eval {
    require Data::Validate::URI;
    Data::Validate::URI->import (qw/is_web_uri/);
    require LWP::Simple;
    LWP::Simple->import ();
    $webok = 1;
};

if ($@) {
#    print "$@\n";
    $webok = 0;
}

my $htv = HTML::Valid->new (quiet => 1);
while (@ARGV) {
    my $file = shift @ARGV;
    if ($file =~ /^--(\S*)/) {
	my $option = $1;
	my $value = shift @ARGV;
	if (! $value) {
	    print "$file needs a value";
	}
	$htv->set_option ($option, $value);
	next;
    }
    my $content;
    if (-f $file) {
	# Yes, Path::Tiny, there is still no flock for NFS on BSD. Thank
	# you for the information.
	local $SIG{__WARN__} = sub {};
	$content = path ($file)->slurp_utf8 ();
	$htv->set_filename ($file);
    }
    elsif ($webok && is_web_uri ($file)) {
	print "Getting $file from web.\n";
	$content = get ($file);
	if (! $content) {
	    #		my $ua = LWP::UserAgent->new (agent => "Jeepers, Creepers, where'd ya get those peepers");
	    #		my $reply = $ua->get ($file);
	    #		if (! $reply->is_success ()) {
	    #		    print $reply->status_line (), "\n";
	    warn "Could not download '$file', skipping.\n";
	    next;
	}
	#$content = $reply->decoded_content ();
	#	    }
    }
    else {
	warn "$0: Cannot find '$file'.\n";
	next;
    }
    my ($output, $errors) = $htv->run ($content);
    if ($errors) {
	print STDERR sanitize_errors ($errors);
    }
    print $output;
    $htv->reset ();
}


# Local variables:
# mode: perl
# End:
