### -*-cperl-*-
###
### Main output for Trivial Gallery.
###
### (c) 2021 Mark Wooding
###

###----- Licensing notice ---------------------------------------------------
###
### This file is part of Trivial Gallery.
###
### Trivial Gallery is free software: you can redistribute it and/or modify
### it under the terms of the GNU Affero General Public License as
### published by the Free Software Foundation; either version 3 of the
### License, or (at your option) any later version.
###
### Trivial Gallery is distributed in the hope that it will be useful, but
### WITHOUT ANY WARRANTY; without even the implied warranty of
### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
### Affero General Public License for more details.
###
### You should have received a copy of the GNU Affero General Public
### License along with Trivial Gallery.  If not, see
### <https://www.gnu.org/licenses/>.

package TrivGal;

use autodie qw{:all};

use Errno;
use Exporter qw{import};
use File::stat;
use Image::ExifTool qw{};
use Image::Imlib2;
use Image::Size qw{};
use User::pwent;
use POSIX;

our @EXPORT;
sub export (@) { push @EXPORT, @_; }

###--------------------------------------------------------------------------
### Internal utilities.

sub read_or_set ($\$@) {
  my ($me, $ref, @args) = @_;
  if (@args == 0) { return $$ref; }
  elsif (@args == 1) { $$ref = $args[0]; return $me; }
  elsif (@args > 1) { die "too many arguments"; }
}

###--------------------------------------------------------------------------
### Random utilities.

export qw{join_paths};
sub join_paths (@) {
  my @p = @_;
  my $p = "";
  ELT: for my $e (@p) {
    $e =~ s#^/{2,}#/#;
    $e =~ s#([^/])/+$#$1#;
    if ($e eq "") { next ELT; }
    elsif ($p eq "" || $e =~ m#^/#) { $p = $e; }
    else { $p = "$p/$e"; }
  }
  return $p;
}

export qw{split_path};
sub split_path ($) {
  my ($path) = @_;

  my ($dir, $base, $ext) =
    $path =~ m#^ (?: (.*) /)?
		 (?: ([^/]*) \.)?
		 ([^./]*) $#x;
  if (defined $base) { $ext = ".$ext"; }
  else { $base = $ext; $ext = ""; }
  return ($dir, $base, $ext);
}

export qw{urlencode};
sub urlencode ($) {
  my ($u) = @_;
  $u =~ s#([^0-9a-zA-Z_./~-])#sprintf "%%%02x", ord $1#eg;
  return $u;
}

export qw{urldecode};
sub urldecode ($) {
  my ($u) = @_;
  $u =~ s#\%([0-9a-fA-F]{2})#chr hex $1#eg;
  return $u;
}

###--------------------------------------------------------------------------
### Image types.

our %TYPE;

package TrivGal::ImageType {
  sub new ($$) {
    my ($cls, $ext) = @_;
    return $TYPE{$ext} = bless { ext => $ext }, $cls;
  }
  sub ext ($) {
    my ($me, @args) = @_;
    return $me->{ext};
  }
  sub mimetype ($@) {
    my ($me, @args) = @_;
    return TrivGal::read_or_set $me, $me->{mimetype}, @args;
  }
  sub imlibfmt ($@) {
    my ($me, @args) = @_;
    return TrivGal::read_or_set $me, $me->{imlibfmt}, @args;
  }
}

TrivGal::ImageType->new(".jpg")->mimetype("image/jpeg")->imlibfmt("jpeg");
TrivGal::ImageType->new(".png")->mimetype("image/png")->imlibfmt("png");

###--------------------------------------------------------------------------
### Configuration.

export qw{$SCOPE $SUFFIX};
our $SCOPE //= $::SCOPE;
our $SUFFIX //= $::SUFFIX;

export qw{$IMGROOT $CACHE $TMP};
our $IMGROOT //= "$ENV{HOME}/publish/$SCOPE-html$SUFFIX/tgal-images";
our $CACHE //=
  ($ENV{XDG_CACHE_HOME} // "$ENV{HOME}/.cache") .
  "/tgal/$SCOPE$SUFFIX";
our $TMP //= "$CACHE/tmp";

export qw{$ROOTURL $IMGURL $CACHEURL $STATICURL $SCRIPTURL};
my $user = getpwuid($>)->name;
our $ROOTURL //= "/~$user";
our $IMGURL //= "$ROOTURL/tgal-images";
our $CACHEURL //= "$ROOTURL/tgal-cache";
our $STATICURL //= "$ROOTURL/tgal-static";
our $SCRIPTURL;

export qw{$SRCURL};
our $SRCURL = "https://git.distorted.org.uk/~mdw/tgal/";

export qw{%SIZE};
our %SIZE = (smallthumb => 96,
	     medthumb => 144,
	     bigthumb => 228,
	     small => 480,
	     embed => 720,
	     view => 1200);

export qw{init};
my $initp = 0;
sub init () {
  my $m = HTML::Mason::Request->instance;
  my $r = $m->cgi_request;

  $m->interp->set_escape(u => sub { my ($r) = @_; $$r = urlencode $$r; });

  return unless !$initp;

  $SCRIPTURL //= $r->subprocess_env("SCRIPT_NAME");
  $initp = 1;
}

###--------------------------------------------------------------------------
### Temporary files.

export qw{clean_temp_files};
sub clean_temp_files () {
  my $d;

  eval { opendir $d, $TMP; };
  if ($@) {
    if ($@->isa("autodie::exception") && $@->errno == ENOENT) { return; }
    else { die $@; }
  }
  my $now = time;
  FILE: while (my $name = readdir $d) {
    next FILE unless $name =~ /^t(\d+)\-/;
    my $pid = $1;
    next FILE if kill 0, $pid;
    my $f = "$TMP/$name";
    my $st = stat $name;
    next FILE if $now - $st->mtime() < 300;
    unlink $f;
  }
  closedir $d;
}

###--------------------------------------------------------------------------
### Scaled images.

my %ORIENT =
  (1 => [0, 0],
   2 => [0, 1],
   3 => [2, 0],
   4 => [2, 1],
   5 => [3, 1],
   6 => [1, 0],
   7 => [1, 1],
   8 => [3, 0]);

package TrivGal::Image {
  use File::Path qw{make_path};
  use File::stat;

  sub new ($$) {
    my ($cls, $path) = @_;
    my $imgpath = "$IMGROOT/$path";
    my $st = stat $imgpath or die "no image `$path'";
    return bless {
      path => $path, imgpath => $imgpath,
      mtime => $st->mtime,
      img => undef,
      rot => undef, flip => undef,
      wd => undef, ht => undef,
      _wd => undef, _ht => undef,
      sz => undef
    }, $cls;
  }

  sub _getsz ($) {
    my ($me) = @_;
    return if defined $me->{_wd};

    my ($wd, $ht, $err) = Image::Size::imgsize $me->{imgpath};
    defined $wd or die "failed to read size of `$me->{path}': $err";
    my $sz = $wd; if ($sz < $ht) { $sz = $ht; }
    @$me{"_wd", "_ht", "sz"} = ($wd, $ht, $sz);
  }

  sub _getexif ($) {
    my ($me) = @_;
    return if defined $me->{wd};

    $me->_getsz;
    my $exif = new Image::ExifTool; $exif->ExtractInfo($me->{imgpath});
    my $orient = $exif->GetValue("Orientation", "ValueConv");
    my ($wd, $ht) = @$me{"_wd", "_ht"};
    my ($rot, $flip);
    if (defined $orient) { ($rot, $flip) = $ORIENT{$orient}->@*; }
    else { ($rot, $flip) = (0, 0); }
    if ($rot%2) { ($wd, $ht) = ($ht, $wd); }
    @$me{"rot", "flip", "wd", "ht"} = ($rot, $flip, $wd, $ht);
  }

  sub sz ($) { my ($me) = @_; $me->_getsz; return $me->{sz}; }
  sub wd ($) { my ($me) = @_; $me->_getexif; return $me->{wd}; }
  sub ht ($) { my ($me) = @_; $me->_getexif; return $me->{ht}; }

  sub scale ($$;$) {
    my ($me, $scale, $forcep) = @_;
    my $m = HTML::Mason::Request->instance;

    my $path = $me->{path};
    my $sz = $SIZE{$scale} or die "unknown scale `$scale'";
    my $url;

    if ($me->sz <= $sz)
      { $url = $m->interp->apply_escapes("$IMGURL/$path", "u"); }
    else {
      my $tail = "scale.$sz/$path";
      my $thumb = "$CACHE/$tail";
      my $thumburl = $m->interp->apply_escapes("$CACHEURL/$tail", "u");

      my $st = stat $thumb;
      if ($st && $st->mtime > $me->{mtime})
	{ $url = $thumburl; }
      elsif (!$forcep) {
	$url =
	  $m->interp->apply_escapes("$SCRIPTURL/$path", "u") .
	  "?scale=$scale";
      } else {
	my $img = $me->{img};
	unless (defined $img) {
	  $me->_getexif;
	  $img = $me->{img} = Image::Imlib2->load($me->{imgpath});
	  if ($me->{rot}) { $img->image_orientate($me->{rot}); }
	  if ($me->{flip}) { $img->flip_horizontal(); }
	}

	my ($dir, undef, $ext) = TrivGal::split_path $thumb;
	my $ty = $TYPE{lc $ext} or die "unknown type `$ext'";
	my $sc = $sz/$me->sz;
	my $scaled = $img->create_scaled_image($sc*$wd, $sc*$ht);

	$scaled->image_set_format($ty->imlibfmt);
	$scaled->set_quality(90);
	my $new = "$TMP/t$$-$ext";
	make_path $TMP, { mode => 0771 };
	$scaled->save($new);
	make_path $dir, { mode => 0771 };
	rename $new, $thumb;
	$url = $thumburl;
      }
    }

    return $url;
  }
}

###--------------------------------------------------------------------------
### Directory listings.

package TrivGal::Item {
  sub new ($$) {
    my ($cls, $name) = @_;
    return bless { name => $name }, $cls;
  }
  sub name ($@) {
    my ($me, @args) = @_;
    return TrivGal::read_or_set $me, $me->{name}, @args;
  }
  sub comment ($@) {
    my ($me, @args) = @_;
    return TrivGal::read_or_set $me, $me->{comment}, @args;
  }
}

export qw{listdir};
sub listdir ($) {
  my ($path) = @_;
  my (@d, @f);
  my $ix = undef;

  $path =~ s#/$##;
  if (-f "$path/.tgal.index") {
    open my $f, "<", "$path/.tgal.index";
    my $item = undef;
    my $comment = undef;
    LINE: while (<$f>) {
      chomp;
      next LINE if /^\s*(\#|$)/;
      if (s/^\s+//) {
	die "no item" unless $item;
	$comment = defined $comment ? $comment . "\n" . $_ : $_;
      } else {
	if ($item && $comment) { $item->comment($comment); }
	my ($flags, $name, $c) =
	  /^ (?: ([-!]+) \s+)?		# flags
	     (\S+) \s*			# filename
	     (\S | \S.*\S )?		# start of the comment
	     \s*
	     $/x;
	my $indexp = $flags =~ /!/;
	my $hidep = $flags =~ /-/;
	$name = urldecode $name;
	my $list;
	$item = TrivGal::Item->new($name);
	if ($name =~ m#/$#) {
	  $list = \@d;
	  die "can't index a folder" if $indexp;
	} else {
	  $list = \@f;
	  my (undef, undef, $ext) = split_path $name;
	  die "unknown image type" unless $TYPE{lc $ext};
	  if ($indexp) {
	    die "two index images" if defined $ix;
	    $ix = $item;
	  }
	}
	$comment = $c;
	push @$list, $item unless $hidep;
      }
    }
    if ($item && $comment) { $item->comment($comment); }
    close $f;
  } else {
    my $st = stat $path;
    unless ($st->mode&0004) { return ([], [], undef); }

    opendir $d, $path;
    my @e = readdir $d;
    closedir $d;

    ENT: for my $e (sort @e) {
      my (undef, undef, $ext) = split_path $e;
      my $dotp = $e =~ /^\./;
      my $st = stat "$path/$e";
      my $list = undef;
      if ($dotp) { }
      elsif (-d $st) { $list = \@d; $e .= "/"; }
      elsif ($TYPE{lc $ext} && -f $st) { $list = \@f; }
      $list and push @$list, TrivGal::Item->new($e);
    }
    $ix = $f[0] if @f;
  }

  return (\@d, \@f, $ix);
}

export qw{contents};
sub contents ($) {
  my ($file) = @_;
  my $contents = "";
  my $f;
  local $@;
  eval { open $f, "<", "$file"; };
  if ($@) {
    if ($@->isa("autodie::exception") && $@->errno == ENOENT)
      { return undef; }
    die $@;
  }
  while (sysread $f, $buf, 16384) { $contents .= $buf; }
  close $f;
  return $contents;
}

export qw{find_covering_file};
sub find_covering_file ($$$) {
  my ($top, $path, $name) = @_;
  for (;;) {
    my $stuff = contents "$top/$path/$name"; return $stuff if defined $stuff;
    if ($path eq "") { return undef; }
    if ($path =~ m#^(.*)/[^/]+/?#) { $path = $1; }
    else { $path = ""; }
  }
}

###----- That's all, folks --------------------------------------------------

clean_temp_files;

1;
