#!/usr/bin/perl
#
#  Addendat console-based blogging script.  I'm not using taint checking
# because I assume that, should you actually *WANT* to trash your own
# files, there are easier ways to do it from your own console.

# Configuration:
# $addendat tells where to find the main addendat CGI.
$addendat='./addendat.cgi';

# $user tells who added this entry.  By default, it'll be your unix
# username.
$user=getpwuid($<);

# $publicize tells Addendat whether to publicize your blog entry.
#$publicize='y';   # Uncomment this to always publicize
#$publicize=0;     # Uncomment this to never publicize
# If left undefined, the CLI blog will ask whether or not to publicize
# additions.

# $accesscode is your blog's access code.  If you're only blogging from
# console, then set your blogs so that only you can write them, and
# exposure of the access code won't be harmful.
$accesscode='nyet';
# End config.

$file=`mktemp /tmp/Addendat-$$-XXXXXX`;
chomp($file);
if ($ENV{EDITOR}) {
  system "$ENV{EDITOR} $file";
} else {
  print "No editor specified in $ENV{EDITOR}.  Using vi.\n";
  sleep(1);
  system "vi $file";
}

open (FILE,"<$file") || die "Cannot read temp file $file.\n";
$oldslash=$/;
undef($/);
$entry=<FILE>;
close(FILE);
$/=$oldslash;

if ($file ne '') {
  print "Blog entry: \n";
  print "$entry";
  print "\nAdd this? ";
  $resp=<STDIN>;
  if ($resp=~/^Y/i) {
    if (!defined($publicize)) {
      print "Publicize your entry on the Hub? (type y[enter] for yes) ";
      $publicize=<STDIN>;
      if ($publicize=~/^y/i) {
        $publicize='y';
        print "Publicizing.\n";
#        if ($publicize) {
#          print ADDENDAT "publicize=$publicize\n";
#        }
      } else {
        print "Not publicizing.\n";
      }
    }
    open (ADDENDAT,"|$addendat") || die "Cannot run $addendat";
    print ADDENDAT "entry=".&urlescape($entry)."\n";
    print ADDENDAT "user=".&urlescape($user)."\n";
    if ($publicize eq 'y') {
      print ADDENDAT "publicize=$publicize\n";
    }
#    if ($publicize) {
#      print ADDENDAT "publicize=$publicize\n";
#    }
    print ADDENDAT "accesscode=".&urlescape($accesscode)."\n";
    print ADDENDAT "debug=1\n";
    close (ADDENDAT);
  }
}

sub urlescape()
{
  local $c;
  local $ret='';
  local $str=$_[0];
  while (length($str)) {
    $c=substr($str,0,1);
    $str=substr($str,1);
    if ($c=~/[a-zA-Z0-9]/) {
      $ret.=$c;
    } elsif ($c eq ' ') {
      $ret.='+';
    } else {
      if (ord($c)<0x10) {
        $ret.='%0'.sprintf("%X",ord($c));
      } else {
        $ret.='%'.sprintf("%X",ord($c));
      }
    }
  }
  return $ret;
}
