#!/usr/bin/perl
#
# Copyright 2009 by Manuel Carrasco Moñino
# Based on previous works by 
# Jan Provaznik <jenik@instrat.cz> (Olix desktop)
# Antonio Sanchez for GALPon MiniNo distro <minino@galpon.org>
#
# This file is part of the LookXP project, and may only be used, modified,
# and distributed under the terms of the LookXP project license,
# LICENSE.TXT.  By continuing to use, modify, or distribute this file you
# indicate that you have read the license and understand and accept it
# fully.
#

use File::Find;
use IO::Dir;
use strict;
use warnings;

my $mnu_trans = ".menutranslations";
my $apps=$ENV{'HOME'} . "/Apps";

my $dir=$ARGV[0] || $apps;
exit if (!-d $dir);

my $prg = $0;

my %trans;
my $lang = $ENV{LANG};
if ($lang && $lang =~ /^(..)/ ) {
  $lang = lc $1;
  my $tfile = "$dir/$mnu_trans";
  $tfile = "$apps/$mnu_trans" if (-f $tfile);
  if (-f $tfile) {
    open(F,$tfile);
    while(<F>){
      $trans{$1}=$2 if (/^([^\[]+)\[$lang\]=(.+)$/);
    }
    close(F);
  }
}

tie my %dir, 'IO::Dir', $dir;
foreach (sort{$a cmp $b} keys %dir) {
   next if (/^\.+$/ || /$mnu_trans/);
   my $n = $_;
   my $i = "$dir/$n";
   my ($type, $name, $icon, $exec),
   my $args = "";
   if ( -d "$i") {
     $name = $n;
     if ( -f "$i/AppRun") {
        $type = "prog"; $exec="$i/AppRun";
        $icon = (-f "$i/.MenuIcon") ? "$i/.MenuIcon" : "$i/.DirIcon";
     } else {
        $type = "menuprog"; $exec=$prg; $args=$i;
        $icon = (-f "$i/.DirIcon") ? "$i/.DirIcon" : "folder";
     }
   } elsif  ( $n =~ /\.desktop$/ ) {
      $type="prog";
      open(F,$i);
      while(<F>) {
         $name = $1 if (!$name && /Name=(.*)$/);
         $name = $1 if ($lang && /Name\[$lang[^\]]*\]=(.*)$/);
         $icon = $1 if (/Icon=(.*)$/);
         $exec = $1 if (/Exec=\s*(.*)$/);
      }
      # %u , %f , %c caption,  --icon %i, --miniicon %m
      $exec =~ s/\"(\%[Uufim])\"/$1/g;
      $exec =~ s/[\s]*\%[Uufim][\s]*/ /g;
      $exec =~ s/\s+$//g;
      close(F);
   } elsif  ( -x "$i" ) {
      $type = "prog"; $name=$n; $icon=$n; $exec=$i;
   }
   if ($type && $name && $exec) {
      $name = $trans{$name} if (%trans && $trans{$name});
      my $cmd = "$type \"$name\" \"$icon\" \"$exec\"";
      $cmd .= " \"$args\"" if ($args && $args ne '');
      print "$cmd\n";
   }
}

