#!/usr/bin/env perl
# pretxt.pl --- preprocess txt files (before feeding into markdown)

# Copyright (c) 2024-2025 Amin Bandali <[email protected]>
#
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice and this notice are preserved.  This file is offered as-is,
# without any warranty.


use strict;
use warnings 'all';
use utf8;
use open ':std', ':encoding(UTF-8)';

my $fn = $ARGV[0] or die "$0: error: no input filename given\n";
my $field = $ARGV[1];

open my $fh, '<:encoding(UTF-8)', $fn
   or die "$0: error: could not open file $fn: $!";

my $in_pre = 1;
my $seen_nonempty = 0;

my @fields;
my $body = '';
my $mtime = localtime((stat($fh))[9]);

while (<$fh>) {
   if ($in_pre) {
       chomp;                  # remove trailing \n
       if (length $_) {
           $seen_nonempty = 1 if !$seen_nonempty;
           if ($field) {
               if ($_ !~ /^\s/) {
                   push @fields, $_
               } else {
                   $fields[$#fields] .= "\n$_"
               }
           }
       } else {
           $in_pre = 0 if $seen_nonempty;
       }
   } else {
       last if $field;
       $body .= $_;
   }
}

close $fh or die "$0: error: could not close file $fn: $!";

my $out = '';

if ($field) {
   my $date = $fields[1]
       ? $fields[1] =~ s/(Last updated|آخرین به‌روزرسانی) //r
       : `date -Rd '$mtime' | tr -d \\\\n`;
   my %fields_map = (
       title => $fields[0],
       date => $date,
       mtime => $mtime,
       );
   $out = "$fields_map{$field}\n" if $fields_map{$field};
} else {
   $out = $body;
}

print $out;
STDOUT->flush;