#!/usr/bin/perl -w

# 4 types of messages:
#   - warn (yellow)
#   - go (green)
#   - info (blue)
#   - stop (red)
#
# CREATE TABLE `changelog` (
#   `id` int(10) NOT NULL auto_increment,
#   `author` varchar(255) NOT NULL,
#   `message` text NOT NULL,
#   `type` varchar(24) NOT NULL,
#   `posted` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
#   PRIMARY KEY (`id`)  
# ) TYPE=MyISAM;
# 

use DBI;
use Text::WikiFormat;

my $version = '1.1';

my $db_name = 'DATABASE';
my $db_user = 'USERNAME';
my $db_pass = 'PASSWORD';

my $posttype = $ARGV[0];
my $user = $ARGV[1];

if (!$posttype) {
  # We default to info
  $posttype = "info";
  $user = "NOC staff";
}

if (!$user) {
  # We default to info
  $user = "NOC staff";
}

if ($posttype eq "info" || $posttype eq "warn" || $posttype eq "go" || $posttype eq "stop") {
  if ($posttype eq "go") {
    $type = "go";
  } elsif ($posttype eq "warn") {
    $type = "exclamation";
  } elsif ($posttype eq "stop") {
    $type = "stop";
  } else {
    $type = "info";
  }

  # Fetch the message we'll be posting
  my @message = <STDIN>;
  my $message = join '' , @message;

  # Do HTML::Entities magic
  eval { require HTML::Entities; };
  if ($@) {
      #  we could encode more HTML characters if HTML::Entities was installed;
  }
  else {
      import HTML::Entities;
      $message = encode_entities($message)
  }

  # To handle all kinds of line endings. See Programming Perl, 3rd Ed, page 623
  #$message =~ s/\015?\012/\n/g;

  # translate two or more line breaks to a paragraph break
  #$message =~ s#\n\n+#</p><p>#g;

  # translate a single line break to <BR>
  #$message =~ s#\n#<br/>#g;

  # Try to do a wiki conversion
  $message = Text::WikiFormat::format($message,{
	blocks => {
		unordered => qr/^\*\s/,
	},
        indented => {
                        unordered => 0,
        },
  },{extended => 1}  );

  # Make it a nifty little paragraph
  $message = "$message";

  # Get the posting time
  my $timestamp = time();

  # Connect to the database
  my $db = DBI->connect("DBI:mysql:$db_name", "$db_user", "$db_pass") or die "Couldn't connect to database: " . DBI->errstr;

  # Insert the posting
  $db->do("INSERT INTO changelog (author, message, type) VALUES (". $db->quote($user) .", ". $db->quote($message) .", ". $db->quote($type) .")") or die "Couldn't execute query: " . $db->errstr;

  # Clean up database connection
  $db->disconnect();
} else {
  # Show an error and quit
  print "rc6.org changelog v$version, an interactive issue poster\n";
  print "\n";
  print "Usage: $0 [notice type] [username]\n";
  print "\n";
  print "[notice type]\n";
  print "  info: general information\n";
  print "  warn: active issues\n";
  print "  go  : resolved issues\n";
  print "  stop: critical issues\n";
  print "\n";
  print "[username]\n";
  print "  the username under which you want to post the message.\n";
  print "\n";
  print "Mail bug reports and suggestions to <noc\@rc6.org>\n";
}
