#!/usr/bin/perl -p
#
# $Id$
#
(our $ME = $0) =~ s|.*/||;

$/ = undef;

use strict;
use warnings;

use File::stat;
use Image::Size;

chdir '/home/esm/blog' or die "Cannot cd: $!\n";

###############################################################################
# BEGIN helpers

sub find_image($$) {
    my $base = shift;			# in: part of an image name
    my $ext  = shift;			# in: image extension (jpg, png)

    opendir DDD, 'images'
      or do {
	  warn "$ME: Cannot opendir 'images': $!\n";
	  return;
      };

    my @tmp = sort grep { $_ !~ /-t\./ } grep { /^[^.].*$base.*\.$ext$/ } readdir DDD;
    closedir DDD;
    if (@tmp == 0) {
	warn "$ME: No image named '$base'\n";
	return;
    }
    elsif (@tmp > 1) {
	# Ambiguous.  But see if there's something _exactly_ like $base.
	my @tmp2 = grep { /\.$base\./ } @tmp;
	if (@tmp2 == 1) {
	    return "images/$tmp2[0]";
	}

	warn "$ME: Image base '$base' is ambiguous: matches @tmp\n";
	return;
    }

    return "images/$tmp[0]";
}

sub make_thumb($) {
    my $img = shift;			# in: path to image

    (my $thumb = $img) =~ s!\.([^.]+)$!-t.$1!;

    my $st_img = stat($img)
      or die "$ME: Internal error: cannot stat($img): $!\n";

    if (my $st_thumb = stat($thumb)) {
	if ($st_thumb->mtime == $st_img->mtime) {
	    # FIXME
	    return $thumb;
	}
    }

    # No thumbnail, or old one.  Make a new one.
    unlink $thumb;
    system "jhead -c -st $thumb $img >&2";
    exit $? if $?;

    if (! -e $thumb) {
	# Still no EXIF thumbnail.  Make one using ImageMagick
	system 'convert', '-geometry', '200x200', $img, $thumb;
	exit $? if $?;
    }

    # Hope we have one now
    utime $st_img->mtime, $st_img->mtime, $thumb;
    chmod 0444 => $thumb;

    # FIXME
    return $thumb;
}

sub exif_comment($) {
    my $img = shift;			# in: path to image

    return '';
}

# END   helpers
###############################################################################





# {www.foo.com bar} -> <a href="http://www.foo.com">bar</a>
s|\{(http://)?(\S+\.\S+)\s+([^\}]+)\}|<a href="http://$2">$3</a>|gs;

# http://www.foo.com/ -> <a href="http://www.foo.com">http://www.foo.com/</a>
s!(^|\s)(http://\S+[^.,])!$1<a href="$2">$2</a>!;

# Boldface
s{(?<!\\)\*(.*?)\*}{<b>$1</b>}gs;

# <pre>
s!^([ \t]+.*)$!<pre>$1</pre>!gm;
s!</pre>\n<pre>!\n!gs;

# Paragraph breaks
s!\n\n!\n<p>\n!gs;

# Images
s{(?<!\\)\[(\S+?)\.(jpg|png)(-(r|l))?\]}{
    my ($base, $ext, $align) = ($1, $2, $4||'l');

    if (my $img = find_image($base, $ext)) {
	my $tname = make_thumb($img);

	my ($tw, $th) = imgsize($tname);

	my $comment = exif_comment($img) || $img;
	my $css     = ($align eq 'l' ? 'left' : 'right');

	sprintf("<a href=\"/%s\"><img src=\"/%s\" alt=\"%s\" class=\"%s\" width=\"%d\", height=\"%d\" /></a>",
		$img,
		$tname,
		$comment, $css, # FIXME: escapeHTML()
		$tw, $th);
    }
    else {
	warn "$ME: no find_image() for $base\n";
	"$1";
    }
}ges;


# Remove backslash-escapes
s@(?<!\\)\\(\[|\]|\*)@$1@gs;

