#!/usr/bin/perl -w
#
# Go through all the .desktop files in a directory tree and make
# symlinks to the .desktop files in an output directory organized
# by subdirectories named by Category.
#
# The idea is to use this new directory to build fvwm menus via the
# fvwm-menu-desktop script while getting the benefits of category
# organization.
#
# I also utterly ignore all hits about apps that should not be
# in a menu, if fvwm-menu-desktop wants to check that, it can, but
# I don't.
#
# usage: make-menu-dirs /usr/share/applications SystemMenus
#
use strict;
use File::Find;

my $appdir = $ARGV[0];

my $outdir = $ARGV[1];

if (! -d $appdir) {
   die "$appdir is not a directory\n";
}

if (! -d $outdir) {
   die "$outdir is not a directory\n";
}

chomp($appdir=`cd $appdir && pwd`);
chomp($outdir=`cd $outdir && pwd`);

sub process_one_desktop_file {
   my $dtf = shift;
   my $f;
   if (open($f, '<', $dtf)) {
      my %subdirs;
      local $_;
      while (<$f>) {
         if (/^Categories=(.+)$/) {
            my $cats = $1;
            my $c;
            foreach $c (split(/\;/, $cats)) {
               $c=~s/^\s+//g;
               if (($c ne '') && ($c ne '.') && ($c ne '..')) {
                  $subdirs{$c}=1;
               }
            }
         }
      }
      my $s;
      my $basename = substr($dtf,rindex($dtf, '/')+1);
      my $linkmade = 0;
      foreach $s (keys(%subdirs)) {
         mkdir("$outdir/$s");
         symlink($dtf, "$outdir/$s/$basename");
         $linkmade=1;
      }
      if (! $linkmade) {
         symlink($dtf, "$outdir/$basename");
      }
   }
}

sub wanted {
   if ((/\.desktop$/) && (-f $_)) {
      process_one_desktop_file($File::Find::name);
   }
}

find(\&wanted, $appdir);
