#!/usr/bin/perl

# Generates the csv file that I import into Hootsuite each month to do
# the #ApacheBirthday tweets.
#
# Caveats:
#
# The "n years" bit probably doesn't work if you're running it
# for a month in the following year. eg, if you run it for January while
# it's still December.
#
# This script takes a long time to run because it verifies that projects
# actually exist, by loading their website. This is so that we're not
# reporting on Attic'ed projects, and subprojects, and so on.
#

use strict;
use warnings;
use JSON::Parse qw(parse_json);
use LWP::UserAgent;
use HTTP::Request;
use Data::Dumper;

my $V = 0; # Set to 1 to make it noisy

usage() unless $ARGV[0] =~ m/\d/;
my $month = sprintf("%02d", $ARGV[0]);
usage() unless $month;

my $thisyear = (localtime(time))[5] + 1900;

my $where = 'https://projects.apache.org/json/foundation/committees.json';

# Fetch the json
my $ua = LWP::UserAgent->new(timeout=>5, agent=>"Twitter4Ponies/0.1 ");
my $res = $ua->request(HTTP::Request->new(GET => $where)); 
# print $res->content;
my $projects = parse_json( $res->content );

my $day = 1; my $hour = 9;
foreach my $p ( @$projects ) {

    my $proj = $p->{id};
    my $d = $p->{established};
    next unless $d;
    next unless $d =~ m/-$month$/;

    # Skip projects that aren't actually there. (Attic? Subprojects?)
    warn "Checking the validity of $proj" if $V;
    my $v = $ua->request(HTTP::Request->new(GET => "http://$proj.apache.org/"));
    next unless $v->is_success();

    my $y = ( $d =~ m/(\d\d\d\d)/ )[0];
    my $age = $thisyear - $y;

    print '"' .  sprintf("%02d", $day) . '/' . "$month/$thisyear "  . sprintf("%02s", $hour) . ':00:00"' . ',';
    print '"';
    print "Happy birthday to " .
            $p->{name} .
            "! " . $age;
    print ( ($age > 1) ? ' years ' : ' year ' );
    print "as an ASF top level project! #ApacheBirthday";
    print '","';
    print "http://$proj.apache.org/";
    print '"' . "\n";
    $day++;
    if ( $day > 28 ) {
        $day = 1; $hour += 6;
    }
}

sub usage {
    print "Usage: ./birthday.pl MONTH - eg, ./birthday.pl 07\n";
    exit();
}

