#!/usr/bin/env perl
use strict;
use warnings;
use diagnostics;

use File::Find;
use lib "./lib";
use HotSaNICparser;

my $module=$ARGV[0] || "";
$module=~ s/modules\///;
$module="/".$module;
if ($module eq "/") {$module="";}

my %CONFIG = HotSaNICparser::get_config(".");
my $thumbsize = $CONFIG{THUMBSIZE} || "20%";
my $method = $CONFIG{CONVERTMETHOD} || "HTML";

if ($module ne "") {print "converting ",$CONFIG{WEBDIR},$module,"\n";}

# exit if method is HTML or unknown
if (index("ImgMgck I::M",$method) == -1) { exit 0; }

# check if the ImageMagick perl-module is installed
if ($method eq 'I::M') {
  eval { require Image::Magick; };
  if ($@) {
    print "$0: Perlmodule Image::Magick not installed\n";
    $method = "ImgMgck";
  } else { 
    require Image::Magick;
    print "Using Image::Magick perl-module\n";
  }
}

# build array with all weekly diagram files in the web-dir
#
require File::Find;
my @files;
$File::Find::name="";  # suppress stupid warning...
File::Find::find( {wanted => sub { /^.*-week\..*\z/s && push @files, $File::Find::name; } }, $CONFIG{WEBDIR}.$module);

my $cmd;

foreach my $file ( @files ) {
  my $thumb=$file;
  $thumb=~ s/^(.+)\/(.+)-week\.(.+)$/$1\/thumb-$2\.$3/;
#  print "$file -> $thumb\n";
  print "resizing $file\n";

  if ($method eq "I::M") {
    my $image = new Image::Magick;
    $image->Read($file);
    $image->Scale(geometry => "$thumbsize");
    $image->Write($thumb);
    }
  else {
    if ( -x $CONFIG{CONVERTPATH} ) {
      $cmd = "$CONFIG{CONVERTPATH} -geometry $thumbsize $file $thumb";
      # print "$cmd\n";
      system($cmd) == 0
      or warn "$0: could not convert $file to $thumb: $!";
      }
    }
  }

exit;

