#!/usr/bin/perl

use lib "$ENV{HOME}/dev/lib";
use WordPress;
use Getopt::Std;
use POSIX 'strftime';
use strict;


my $user = $ENV{USER} || scalar getpwuid($<);

# load default opts from ~/.tb/config
my %opt = (x => 0, T => strftime("$user\'s update for %A, %B %e %Y", localtime()));
getopts('xmp:T:', \%opt) or usage();
my $pass = $opt{p} || get_password();

my $title = $opt{T};
my $text = join "", <>;

if ($opt{'m'}) {
  # Is this really needed? Why not just "markdown foo | bp" ?
  require Text::Markdown;
  fill_paragraphs($text);
  $text = Text::Markdown::markdown($text);      # XXX error handling?
} 

if ($opt{x}) {
  print $text;
  exit 0;
}

# This does not result a status code. WOO HOO, POST INTO THE VOID!
WordPress->new(
        'http://internalblog.grantstreet.com/teamupdates/xmlrpc.php',
        $user,
        $pass,
    )->post($title,
            $text,
            [ $user ],          # List of categories
           );

1;

sub get_password {
  my $pw_file = $ENV{GSG_BLOG_PASSWORD_FILE} || "$ENV{HOME}/.tb/password";
  if (open my($fh), "<", $pw_file) {
    chomp(my $line = <$fh>);
    return $line;
  } else {
    warn "No password supplied.\n";
    exit 2;
  }
}

# I didn't want to do this, but WordPress likes to translate
# newline characters to <br /> elements.
#
# Sadly, this doesn't properly handle many lists.
# Maybe there is a way to tell WP not to do that.
sub fill_paragraphs {
  my ($text) = $_[0];
  my @p = split /\n\n+/, $text;
  for my $p (@p) {
    my ($prefix) = $p =~ /\A (.*)   .* \n
                             (?:\1  .* \n?)* \z /x;
    $p =~ tr/\n/ / if $prefix eq "";
  }
  $_[0] = join "\n\n", @p;
}
