#!/usr/bin/perl -w
#
# Copyright: © 2009 Cyril Brulebois <kibi@debian.org>
#   This program is free software; you can redistribute it and/or
#   modify it under the terms of the Do What The Fuck You Want To
#   Public License, Version 2, as published by Sam Hocevar. See
#   http://sam.zoy.org/projects/COPYING.WTFPL for more details.

use strict;


#
# Helper functions
#

# Get the date, if it exists:
sub get_date {
  my $filename = shift;
  open my $fh, '<', $filename
    or die "Unable to open $filename";
  my $date;
  while (<$fh>) {
    if (/(?:^|[^\\])\[\[meta date="([^"]+)"/) {
      $date=$1;
    }
  }
  close $fh
    or die "Unable to close $filename";
  return $date;
}

# Replace the date, since it exists:
sub replace_date {
  my $filename = shift;
  my $newdate  = shift;
  my $newfilename = "$filename+dates";

  open my $fh, '<', $filename
    or die "Unable to open $filename";
  open my $newfh, '>', $newfilename
    or die "Unable to open $newfilename";
  my $date;
  while (my $l = <$fh>) {
    if ($l =~ /(?:^|[^\\])\[\[meta date="([^"]+)"/) {
      $date=$1;
      $l =~ s/meta date="$date"/meta date="$newdate"/;
    }
    print $newfh $l;
  }
  close $fh
    or die "Unable to close $filename";
  close $newfh
    or die "Unable to close $newfilename";
  rename $newfilename, $filename
    or die "Unable to replace $filename with $newfilename";
}

# Add the date, it didn't exist yet:
sub add_date {
  my $filename = shift;
  my $date     = shift;

  open my $fh, '>>', $filename
    or die "Unable to open $filename";
  print $fh "\n";
  print $fh "[[meta date=\"$date\"]]\n";
  close $fh
    or die "Unable to close $filename";
}


#
# Real body now:
#

# Get all articles:
my @articles = <*/*/*/*.mdwn>;

# Count for each date:
my %counts;
foreach my $article (sort @articles) {
  my @path = reverse(split m{/}, $article);
  my ($file, $d, $m, $a) = @path;
  my $date = get_date($article) || "$a-$m-$d";
  $counts{$date}++;
}

# Process everyone:
foreach my $article (sort @articles) {
  my @path = reverse(split m{/}, $article);
  my ($file, $d, $m, $a) = @path;
  my $date = get_date($article);
  my $has_date = defined($date);
  $date ||= "$a-$m-$d";

  # Check for singletons:
  if ($counts{$date} > 1) {
    # More than one exact same date:
    if ($has_date) {
      replace_date($article, "$date FIXME");
    }
    else {
      add_date($article, "$date FIXME");
    }
  }
  else {
    # There's a single date, we're fine:
    if ($has_date) {
      # Nothing to do
    }
    else {
      add_date($article, "$date");
    }
  }
}
