#!/usr/pkg/bin/perl
#
# phlogit - a perl clone of the 'mkgopherentry' shell script
#
# Set the phlog directory below and call with a title and a
# filename. You can optionally add a -w, which will format your text
# to 68 columns.  The script will update your gophermap in reverse
# chronological order, with a short post intro and a link to the
# full post. The intro is extracted from the top of the file up to
# the first blank line. Each post is tagged with the current
# date. Note the script expects the file to be in the phlog
# directory before you run it.
#
# GPLv3 or later slugmax@sdf.org
#
# $Id: phlogit,v 1.9 2017/07/29 16:32:13 slugmax Exp $
#
use strict;
use warnings;
use Getopt::Long;
use Text::Wrap;

my $home = $ENV{'HOME'};
my $phlog_dir  = qq{$home/gopher/phlog};

my($title,$file,$wrap);
GetOptions(
    "title=s" => \$title,
    "file=s"  => \$file,
    "wrap!"    => \$wrap
);

sub usage {
    print qq{$0 --title|-t 'title' --file|-f 'file' --wrap|-w\n};
    exit;
}

sub slurp_file {
  my $infile = shift;
  open( my $fh, "<", $infile ) or die "Unable to open $infile in _slurp_file: $!\n";
  my $text = do { local( $/ ) ; <$fh> } ;
  return \$text;
}

sub burp_file {
  my $outfile   = shift;
  my $text_ref  = shift;
  my $append    = shift;
  my $wrap_text = shift;
  my $fh;

  if ( $wrap_text ) {
      $Text::Wrap::columns=68;
      $$text_ref = wrap('','',$$text_ref);
  }

  if ($outfile eq "STDOUT") {
    print $$text_ref;
  } else {
      if ( $append ) {
          open( $fh, ">>", "$outfile" ) or die "Unable to open $outfile in _burp_file: $!\n" ;
      } else {
          open( $fh, ">", "$outfile" ) or die "Unable to open $outfile in _burp_file: $!\n" ;
      }
    print $fh $$text_ref ;
  }
}

usage() if (!$title || !$file);

my $old_gmap   = slurp_file("$phlog_dir/gophermap");
my $post_text  = slurp_file("$phlog_dir/$file");
# Intro is any text from the start of the text file until the first blank
# line (or the end of the file if there are no blank lines)
my $intro      = $1 if ( $post_text && $$post_text =~ m{(.+?)(?:^$|\Z)}ms );
my $DATE       = qx(date "+%A, %B %d, %Y");
my $post_blurb = qq{+++ $title +++\n    $DATE\n$intro\n0Continued...\t$file\n\n};

burp_file("$phlog_dir/gophermap",\$post_blurb,0,$wrap);
burp_file("$phlog_dir/gophermap",$old_gmap,1,0);
chmod 0754, "$phlog_dir/gophermap";
chmod 0754, "$phlog_dir/$file";