# Album Plugin:	org/link
# For info:	'album -plugin_info org/link'
use strict;
use File::Basename;

sub start_plugin {
  my ($opt) = @_;

  album::hook($opt,'medium',\&symlink_medium);
  album::hook($opt,'thumbnail',\&symlink_thumbnail);


  return {
    author => 'Matt Forrest',
    href => 'mailto://mforrest@scs.ryerson.ca',
    version => '1.4',
    description => "If the image is a link, use a link for the medium and thumbnail.\nThe image must be in an album readable by the webserver\n  (or have a 'tn/' directory)",
  };
}

# DO_LINK - find the real source and link it
# ARG: full path to the new link to be created
# ARG: full path to the original source image
# ARG: full path to the original medium/thumbnail/whatever
sub do_link {
  my ($opt,$full_path, $real_img,$real_file) = @_;

  my($real_source);
  if( dirname($real_img) =~ /../ ) {
    $real_source="../" . dirname($real_img) . "/" . album::option($opt,'dir') . "/" . basename($real_file);
  } else {
    $real_source=basename($real_file);
  }
  symlink($real_source,$full_path);
  return $full_path;
}

sub symlink_medium {
  my ($opt, $hookname,  $dir, $obj, $file, $full_path) = @_;
  my $img = "$dir/$file";
  my $type = $opt->{medium_type};
  $type = $opt->{type} if $obj->{is_movie} && !$type;
  my ($medium_file,$medium_path)
    = album::new_image_path($opt,$dir,$file,$type,'med.','med.');

	return undef unless -l $img;

  # Don't regenerate mediums unless the image has changed
  return undef
    if (-f $obj->{medium}{path} && !$opt->{force}
        && !option_changed($opt,'medium')
        && -M $obj->{medium}{path} < -M $full_path);

  my($real_img)=readlink($img);
  my($real_med_file,$real_med_path)
    = album::new_image_path($opt,$dir,$real_img,$type,'med.','med.');
  return do_link($opt,$medium_path,$real_img,$real_med_file);
}


sub symlink_thumbnail {
  my ($opt, $hookname,  $dir, $obj, $file, $full_path) = @_;
  my $img = "$dir/$file";
  my $type = $opt->{type};
  my ($thumb_file,$thumb_path)
    = album::new_image_path($opt,$dir,$file,$type,'tn.','');

	return undef unless -l $img;

  return undef
    if (-f $obj->{thumb}{path} && !$opt->{force}
        && !option_changed($opt,'geometry')
        && !option_changed($opt,'crop')
        && -M $obj->{thumb}{path} < -M $full_path);

	my $real_img = readlink($img);
  my ($real_file, $real_path)
    = album::new_image_path($opt,$dir,$real_img,$type,'tn.','');
  return do_link($opt,$thumb_path,$real_img,$real_file);
}


1;

