#!/usr/bin/perl -w

use strict;

my %links;

open (my $inf, "grep -ari href $ARGV[0]|");
while (<$inf>) {
	chomp;
	while ( /[Hh][Rr][Ee][Ff]=\"(.*?)\"/g ) {
		my $url = $1;
		$url =~ s=https://nrw.svw.info/==;
		if ($url =~ /^\/ergebnisse\/show\/$ARGV[0]\//) {
			$url =~ s=/ergebnisse/show/==;
			if ($url =~ /^(.*)\/$/g) {
				my $dir = $1;
				if (! -d "$dir") {
					`rm -f $dir`;
					`mkdir -p $dir`;
				}
				if ((-r "${url}index.html") && (! -z "${url}index.html")) {
					# print "${url}index.html schon da.\n";
				} else {
					print "URL $url\n";
					print "curl -q -o ${url}index.html https://nrw.svw.info/ergebnisse/show/$url\n";
					`curl -q -o ${url}index.html https://nrw.svw.info/ergebnisse/show/$url`;
				}
			} else {
				my $dir = `dirname $url`;
				chomp $dir;
				my $file = `basename $url`;
				chomp $file;
				if ((-r "${dir}/${file}") && (! -z "${dir}/${file}")) {
					# print "${dir}/${file} schon da.\n";
				} else {
					print "URL $url\n";
					if (! -d "$dir") {
						`rm -f $dir`;
						`mkdir -p $dir`;
					}
					print "curl -q -o ${dir}/${file} https://nrw.svw.info/ergebnisse/show/$url\n";
					`curl -q -o ${dir}/${file} https://nrw.svw.info/ergebnisse/show/$url`;
				}
			}
		}
	}
}
