# Generate tv_grep from tv_grep.in.  This processing is necessary for
# the pod documentation, which should be partly autogenerated from
# information provided by the Grep.pm library.
#
# We could avoid this step if we had the documentation in a separate
# file - but then we'd need a separate step for producing
# documentation.  The input file tv_grep.in is also a legal Perl
# program, so debugging should not be any harder than it was.

use IO::File;
use XMLTV;

require './filter/Grep.pm';

my $out = shift @ARGV; die "no output file given" if not defined $out;
my $in = 'filter/tv_grep.in';
my $in_fh = new IO::File "< $in" or die "cannot read $in: $!";
my $out_fh = new IO::File "> $out" or die "cannot write to $out: $!";
while (<$in_fh>) {
    if (/^\s*\@PROGRAMME_CONTENT_TESTS\s*$/) {
	# Query XMLTV.pm to find out what keys of programme exist.
	# This is rather a duplicate of the usage message in tv_grep
	# itself: should unify one day.
	#
	my %key_type = %{XMLTV::list_programme_keys()};
 	foreach (sort keys %key_type) {
	    my ($arg, $matcher) = @{XMLTV::Grep::get_matcher($_)};
	    if (not defined $arg) {
		print $out_fh "B<--$_>\n\n";
	    }
	    elsif ($arg eq 'regexp') {
		print $out_fh "B<--$_> REGEXP\n\n";
	    }
	    elsif ($arg eq 'empty') {
		print $out_fh "B<--$_> ''\n\n";
	    }
	    else {
		die "bad arg type from get_matcher(): $arg";
	    }
 	}
    }
    else {
	print $out_fh $_;
    }
}
close $out_fh or die "cannot close $out: $!";
close $in_fh or die "cannot close $in: $!";

