#!/usr/bin/perl

use strict;
use vars qw($real_install_procedure $real_gimp_main %db);
use Gimp 'interface=lib';
use Gimp::Lib;
use Gimp::Fu;

$real_install_procedure = \&Gimp::Lib::gimp_install_procedure;
*Gimp::Lib::gimp_install_procedure = \&fu_install_procedure;

$real_gimp_main = \&Gimp::Lib::gimp_main;
*Gimp::Lib::gimp_main = \&fu_gimp_main;

sub fu_gimp_main(;@) {
   die "PERL-FU-MAIN\n";
}

sub fu_install_procedure($$$$$$$$$$$) {
   my($name,$blurb,$desc,$author,$copyright,$date,$menu,$types,$type,
      $paramtypes,$returntypes)=@_;
   print "registering $name under $menu\n";#d#
   $db{$name}=$paramtypes;
   &$real_install_procedure($name,$blurb,$desc,$author,$copyright,$date,$menu,$types,$type,
      $paramtypes,$returntypes);
}

sub perl_fu_refresh {
  &$real_install_procedure("perl_fu_refreshx", "xRefresh the Perl-Fu scripts",
                           "Refresh all Perl-Fu sxcripts",
                           "Marc Lehmann <pcg\@goof.com>", "Marc Lehmann", "1998-04-21",
                           "<Toolbox>/Xtns/Perl-Fu/Refresxh", "*",&Gimp::PROC_EXTENSION,
                           [[&Gimp::PARAM_INT32, "run_mode", "Interactive, [non-interactive]"]],[]);
   my $gimp_data_dir = eval { Gimp::gimp_gimprc_query ("gimp_data_dir") };
   my $perl_fu_dir = eval { Gimp::gimp_gimprc_query ("perl-fu-dir") };
   my @dirs=($ENV{'HOME'}."/.gimp/perl-scripts");
   push(@dirs,"$gimp_data_dir/perl-scripts") if defined($gimp_data_dir);
   push(@dirs,$perl_fu_dir) if defined($perl_fu_dir);
   for my $dir (@dirs) {
      next unless opendir DIR,"$dir/.";
      while(defined($_=readdir(DIR))) {
         next if /^\.$|^\.\.$/;
         if(eval { package FU; do "$dir/$_"; $@; } eq "PERL-FU-MAIN\n") {
            eval { FU::query() };
         } else {
            print "skipping illegal plug-in $dir/$_\n";
         }
         delete @FU::{keys %FU::}; # woaw.. remove all symbols from FU::
      }
      close DIR;
   }
}

sub query {
  &$real_install_procedure("perl_fu_refresh", "Refresh the Perl-Fu scripts",
                           "Refresh all Perl-Fu scripts",
                           "Marc Lehmann <pcg\@goof.com>", "Marc Lehmann", "1998-04-21",
                           "<Toolbox>/Xtns/Perl-Fu/Refresh", "*",&Gimp::PROC_EXTENSION,
                           [[&Gimp::PARAM_INT32, "run_mode", "Interactive, [non-interactive]"]],[]);
}

sub quit {
}

exit(&$real_gimp_main());
