#! /usr/bin/env perl

use strict;

use DateTime;
use Cwd qw( realpath );
use File::Spec::Functions;
use File::Basename;

# Figure out where we'll store a copy of the repository that contains
# the Atom files already committed.
my $baseDir = realpath(catdir(dirname($0), '..'));
print "baseDir = $baseDir\n";
my $dataDir = catdir($baseDir, 'tmp_data');
if (! -d $dataDir) {
    mkdir($dataDir) || die("failed to create $dataDir\n$!");
}

# Find out where the svn application is on this system and set the
# URL for the data repository.
# NB Presently we're just using the lab, but it could be anywhere.
my $svnApp = `which svn`;
chomp($svnApp);
my $svnURL = 'https://svn.apache.org/repos/asf/labs/boardcast/data';

# Now check out the data repository.
if (! runCommand("$svnApp co $svnURL $dataDir")) {
    die("Couldn't check out data from SVN\n");
}

# Ask the user to enter their data. This isn't yet fault tolerant, but
# this is just a quick prototype after all :-)
my %categories = (
    'committer' => 'Committers',
    'general' => 'General',
    'pmc' => 'PMC Changes',
    'releases' => 'Releases' );

my $rv = 0;
my ($name, $project, $catKey, $title, $content);

($rv, $name) = askQuestion('What is your name');
die("You MUST enter your name.") unless $rv == 1;

($rv, $project) = askQuestion('Which project does the news relate to');
exit unless $rv == 1;

($rv, $catKey) = askCategory('Please enter the category for the news');
die("You didn't enter a category!") unless $rv == 1;

($rv, $title) = askQuestion('Enter the title of the news item');
exit unless $rv == 1;

($rv, $content) = getContent('Please enter the content for the item');
die("You need to enter some content!") unless $rv == 1;


print "name    : $name\n";
print "project : $project\n";
print "category: [$catKey] ".$categories{$catKey}."\n";

my $dtObj = DateTime->now;
my $dtTm = $dtObj->ymd . 'T' . $dtObj->hms . 'Z';

print "dtTm = $dtTm\n";

my $catLbl = $categories{$catKey};
my $tag = $project.",".$dtTm.":".$title;
$tag =~ s/ /_/g;

my $fn = catfile($dataDir, $tag.'.xml');
$fn =~ s/Z.*\.xml$/\.xml/g;
$fn =~ s/\,|\:/_/g;

my $contentData =<<EOT;
<?xml version="1.0"?>
<entry xmlns="http://www.w3.org/2005/Atom">
  <id>tag:$tag</id>
  <author>
    <name>$name</name>
  </author>
  <category term="/$catKey" label="$catLbl" />
  <title>$title</title>
  <updated>$dtTm</updated>
  <content>$content</content>
</entry>
EOT

if (open(my $fh, ">$fn")) {
    print $fh $contentData;
    close($fh);
    print "File saved as $fn\n";
    die("Failed to add file to SVN\n") unless
          runCommand("$svnApp add $fn");
    die("Unable to commit file!\n") unless
          runCommand("$svnApp commit -m 'Auto generated by $0' --non-interactive $fn");
} else {
    print "failed to open output stream for file '$fn'\n";
    print $contentData;
}

sub askQuestion
{
    my $prompt = shift;
    print "$prompt?\n-> ";
    my $inp = <STDIN>;
    chomp($inp);
    return (0, '') if $inp eq '';
    return(1, $inp);
}

sub askCategory
{
    my $prompt = shift;
    print "$prompt?\n";
    my $n = 0;
    my @options;
    foreach my $k (sort(keys(%categories))) {
        $options[$n] = $k;
        $n++;
        print "    ".($n).". ".$categories{$k}."\n";
    }
    print "-> ";
    my $i = <STDIN>;
    chomp($i);
    return (0, '') unless $i =~ /[0-9]*/;
    return (0, '') if ($i < 1 || $i > $#options);
    my $key = $options[$i - 1];
    return (1, $key);
}

sub getContent
{
    my $prompt = shift;
    print "$prompt?\n";
    print "[Enter content. Finish with '.' on a line by itself]\n";
    my $txt = '';
    while (my $line = <STDIN>) {
        last if $line =~ /^\.\n/;
        $txt .= $line;
    }
    return (0, '') if $txt eq '';
    return (1, $txt);
}

sub runCommand
{
    my $cmd = shift;
    my $fh = select(STDOUT);
    $| = 1;
    print "Running shell command...";
    `$cmd`;
    print 'Done. '.($? ? 'Failed' : 'OK')."\n";
    $| = 0;
    select($fh);
    print "Command was : $cmd\n" if $?;
    return(0) if $?;
    return(1);
}

