#!/usr/bin/perl -w
use strict;
use Data::Dumper;

my %projects;


foreach my $year (qw/2010 2011 2012 2013 2014/) {
    open LIST, "projects$year";
    while (<LIST>) {
	chomp;
	my $file = $_;
	my ($project, $url, $name);
	open PAGE, $file;
	while (<PAGE>) {
	    if (/Project name and homepage[:* ]*\[([^\[\]]*)\]\(([^()]*)\)/) {
		$project = $1;
		$url = $2;
	    }
	    if (/(Název projektu|Project name)[:* ]*(.*)/) {
		if (!$project) {
		    $project = $2;
		}
	    }
	    if (/(Domovská stránka projektu|Project home ?page)[:* ]*<([^<>]*)>/) {
		$url = $2;
	    }
	    if (/\[\[!meta title="([^"]*)"\]\]/) {
		$name = $1;
	    }
	}

	if (!$project or !$name or !$url) {
	    print STDERR "Expected field missing in $file\n";
        }

	print STDERR "Working on student $name ($year)\n";
	if (!$projects{$project}) {
	    $projects{$project} = {};
	    $projects{$project}{'students'} = [];
	}
	my $p = $projects{$project};
	if (!$$p{'url'} or $url) {
	    $$p{'url'} = $url;
	}
	push @{$$p{'students'}}, { 'file' => $file, 'name' => $name, 'year' => $year };
    }
}

print '[[!meta title="Projekty"]]'."\n";
print '[[!meta stylesheet="/columns" rel="stylesheet"]]'."\n";
print "\n";
print 'This page lists the projects and which students worked on them in the'."\n";
print 'past years.'."\n";

foreach (sort(keys(%projects))) {
    print "\n* [$_](", $projects{$_}{'url'}, ")\n";
    #print Dumper($projects{$_}{'students'});
    foreach (@{$projects{$_}{'students'}}) {
	my $page = $_->{'file'};
	$page =~ s|.mdwn$||;
	$page =~ s|/index$||;
	my $name = $_->{'name'} || "???";
	my $year = $_->{'year'} || "20??";
	
	print "  * [[", $name || "", "|student/", $page, "]] ($year)\n";
    }
}
