#!/usr/bin/perl

##########################################################
# this subroutine works as a filter
# usage: cat list.txt | convert > blacklist
#     or cat list.txt | convert --white > whitelist
##########################################################
# Author: Andrei Kouznetsov <akouznet@math.wsu.edu>
# See: http://kouznetsov.awardspace.com/epiphany/adblock.xml

use strict;
use Getopt::Long;

# if $white is set to true, then the whitelist is printed
# otherwise print the blacklist
my $white = 0;
GetOptions('white' => \$white);

# the first line is a header, skip it
<>;

while (my $line = <>){
	chomp $line; # remove trailing EOL
	next if $line =~ /^!/; # if it is a comment, go to the next line
	if ($white){
		next if not $line =~ s/^@@//; # next if it is not a white list
	} else {
		next if $line =~ /^@@/; # next if the line represents a white list
	}
	print "$_\n" if $_=convert($line);
}

sub convert {
	my $pattern = shift;
	
	# if the filter cannot be converted due to some reasons, return undef
	return undef if $pattern =~ /#|\||\$|\^/;
	
	# first, quote all special symbols
# 	$pattern =~ s/(\.|\-)/\\\1/g;
	$pattern =~ s/(\.|\?)/\\\1/g;
	
	# add the start and the end matchers if necessary
# 	$pattern =~ s/^(?!\*)/\^/;
# 	$pattern =~ s/(?<!\*)$/\$/;
	
	# remove * from the start and the end of the pattern
	$pattern =~ s/^\*|\*$//g;
	
	# replace * with .*
	$pattern =~ s/\*/\.\*/g;
	
	#replace ? with .
# 	$pattern =~ s/\?/\./g;
	
	# replace + with \+
	$pattern =~ s/(^|[^\\])\+/\1\\+/g;
	return $pattern;
}
