#! /usr/bin/env perl

use strict;
use warnings;

use v5.10;

use Cwd;
use File::Path qw(make_path);
use File::Basename;
use File::Spec::Functions;

# If not in a location with a test directory, exit
if (! -f 'test/.coverage') {
    exit 1;
}

my $outdir = shift @ARGV;
make_path($outdir);

# Get the name of the package
my $package = basename cwd;

# Create the htmlcov directory
`cd test && coverage html`;

# And get all of the files that we'll want
my @files = glob 'test/htmlcov/*';

my $rename = qr/.*(${package}|_egg)_(.*_py).*(\.html)/;

for (@files) {

    open(my $in_fh, '<', $_);

    s/$rename/$2$3/;

    my $base = fileparse $_;

    open(my $out_fh, '>', catfile($outdir, $base));

    for (<$in_fh>) {
        if (/$package/) {
            # Fix href
            s/(href=")$rename/$1$3$4/;
            # Fix text
            s|/.*${package}(.*\.egg)?/(.*)|$2|;
        }
        print $out_fh $_;
    }

}
