#!/usr/bin/perl

use strict;
use XML::Simple qw(:strict);

my $flxb_out  = "$ENV{HOME}/.fluxbox/menu";
my $flxb_file = "$ENV{HOME}/.fluxbox/__menu.fluxbox";
my $xfce_file = "$ENV{HOME}/.fluxbox/__menu.xfce4";
my @icon_dirs = ("/usr/share/icons",
                 "/usr/share/pixmaps",
                 "/usr/share/app-install/icons",
                 "/usr/share/icons/Human",
                 "/usr/share/icons/Human/22x22",
                 "/usr/share/icons/Human/22x22/apps",
                 "/usr/share/icons/Rodent",
                 "/usr/share/icons/Tango",
                 "/usr/share/icons/default",
                 "/usr/share/icons/gnome",
                 "/usr/share/icons/handhelds",
                 "/usr/share/icons/hicolor",
                 "/usr/share/icons/hicolor/22x22/apps",
                 "/usr/share/icons/hicolor/24x24/apps",
                 "/usr/share/icons/locolor",
                 "/usr/share/icons/gnome/22x22",
                 "/usr/share/icons/gnome/22x22/actions",
                 "/usr/share/icons/gnome/22x22/animations",
                 "/usr/share/icons/gnome/22x22/apps",
                 "/usr/share/icons/gnome/22x22/categories",
                 "/usr/share/icons/gnome/22x22/devices",
                 "/usr/share/icons/gnome/22x22/emblems",
                 "/usr/share/icons/gnome/22x22/emotes",
                 "/usr/share/icons/gnome/22x22/mimetypes",
                 "/usr/share/icons/gnome/22x22/places",
                 "/usr/share/icons/gnome/22x22/status");

open(FLXB_IN,  "<", $flxb_file) || die "$!";
open(FLXB_OUT, ">", $flxb_out)  || die "$!";

my $xmls = XML::Simple->new(ForceArray => 1,
                           SuppressEmpty => 1,
                           KeyAttr => ['name']);

my $file = $xmls->XMLin($xfce_file);

while(<FLXB_IN>) {
  if(/={10}/) {
    print FLXB_OUT "    [submenu] (xfce4) {}\n";
    foreach my $key (keys (%{$file->{menu}})) {
      print FLXB_OUT "        [submenu] ($key) {}\n";

      foreach my $key2 (keys (%{$file->{menu}->{$key}->{'app'}}))   {
        my $icon = $file->{menu}->{$key}->{'app'}->{$key2}->{'icon'};
        if($icon !~ /\//) {
          ($icon, undef) = split(/\./, $icon) if ($icon =~ /\.\w{3}/);
          foreach my $path (@icon_dirs) {
            if (-e "$path/$icon.png") {
              $icon = "$path/$icon.png";
              next;
            }
            elsif (-e "$path/$icon.xpm") {
              $icon = "$path/$icon.xpm";
              next;
            }
          }
        }

        $icon = "<" . $icon . ">";

        my $cmd = $file->{menu}->{$key}->{'app'}->{$key2}->{'cmd'};
        # http://standards.freedesktop.org/desktop-entry-spec/latest/ar01s06.html
        $cmd =~ s/\ \%[fFuUdDnNickvm]//g;

        print FLXB_OUT "            [exec] ($key2) { $cmd } $icon\n";
      }
      print FLXB_OUT "        [end]\n";
    }
    print FLXB_OUT "    [end]\n";
  } else {
    print FLXB_OUT "$_";
  }
}

close FLXB_OUT;
close FLXB_IN;
