#!/usr/bin/perl

use strict;
use warnings;

# -- Built-in stuff often has crap sections...
#
my %overrides = (
  'browser'                                      => 'network',
  'camera-ui'                                    => 'multimedia',
  'filemanager'                                  => 'system',
  'hildon-application-manager'                   => 'system',
  'hildon-control-panel'                         => 'system',
  'image-viewer'                                 => 'graphics',
  'mediaplayer'                                  => 'multimedia',
  'modest'                                       => 'network',
  'nokia-maps'                                   => 'navigation',
  'osso-addressbook'                             => 'office',
  'osso-backup'                                  => 'system',
  'osso-xterm'                                   => 'system',
  'osso_calculator'                              => 'utilities',
  'osso_lmarbles'                                => 'games',
  'osso_notes'                                   => 'utilities',
  'osso_pdfviewer'                               => 'office',
  'osso_rss_feed_reader'                         => 'network',
  'osso_sketch'                                  => 'graphics',
  'ovi'                                          => 'system',
  'rtcom-call-ui'                                => 'utilities',
  'rtcom-messaging-ui'                           => 'utilities',
  'worldclock'                                   => 'utilities',
);

#-- Valid sections...
#
my %validSections = map { $_ => 1} qw(
  desktop development education games graphics
  multimedia navigation network office science system utilities
);

# -- Loop over all desktop files...
#
my %sections = ();
foreach my $desktop (</usr/share/applications/hildon/*.desktop>) {
  # Check it's a launcher icon
  open(IN, "<$desktop") or die "Unable to open $desktop: $!\n";
  my $skip = 0;
  while (<IN>) {
    $skip ||= /^Type=(.*)$/i && $1 !~ /^Application$/i;
    $skip ||= /^NoDisplay=True/i;
  }
  close(IN);
  next if $skip;

  # Check if there's an override...
  my ($name)  = $desktop =~ /([^\/]+)\.desktop$/;
  my $section = $overrides{$name};
  if (!$section) {
    # ...find by package, then
    chomp(my $package = `dpkg -S "$desktop"`);
    if (!$package) {
      print STDERR "Unknown desktop file: $desktop\n";
      next;
    }
    $package =~ s/: .*//;
    $section = (grep { /^Section: / } `apt-cache show "$package"`)[0];
    $section =~ s/.*?: (.+?\/)?//;
    chomp($section);
  }

  $section = 'other' unless $validSections{$section || ''};

  # -- Now we've got the section, store it...
  #
  print "$name = $section\n";
  push @{ $sections{$section} }, $name;
}

use Data::Dumper; print Dumper(\%sections);
