#!/opt/perl/bin/perl -w
# -*- Mode: perl; indent-tabs-mode: nil; c-basic-offset: 4  -*-

#############################################################################
## Copyright (C) 2005-2006 Novell, Inc.
##
## Authors: Rodney Dawes <dobey@novell.com>
##

use strict;
use XML::Simple;
use Getopt::Long;
use Cwd;

my $PROGRAM = "icon-name-mapping";

my $condir;
my $LN_S = ($^O eq 'MSWin32' ? 'copy' : 'ln -s');

############################################################################
my @default_getopt_config = ("permute", "pass_through", "bundling",
			     "no_auto_abbrev", "no_ignore_case");

Getopt::Long::Configure (@default_getopt_config);
GetOptions ("help|h" => \&usage,
	    "context|c=s" => \$condir);


############################################################################

sub tls_load_mapping {
    my $filename = shift;

    my $mapping = XML::Simple::XMLin ($filename,
				      keyattr => [ qw(dir) ],
				      forcearray => [ qw(context icon link) ]);
    return $mapping;
}

sub tls_map_icons {
    my $mapping = shift;
    my $dirname = shift;

    print "Setting up icon mapping for: $dirname\n";
    chomp (my $cwd = Cwd::cwd());
    chdir $dirname;
    foreach my $icon (@{$mapping->{context}->{$dirname}->{icon}}) {
        if (-f "$icon->{name}.png") {
            foreach my $legacy (@{$icon->{link}}) {
                system ("$LN_S \"$icon->{name}.png\" \"$legacy.png\"")
                    if (! -e "$legacy.png");
            }
        } elsif (-f "$icon->{name}.svg") {
            foreach my $legacy (@{$icon->{link}}) {
                system ("$LN_S \"$icon->{name}.svg\" \"$legacy.svg\"")
                    if (! -e "$legacy.svg");
            }
        }

        if (-f "$icon->{name}.icon") {
            foreach my $legacy (@{$icon->{link}}) {
                system ("$LN_S \"$icon->{name}.icon\" \"$legacy.icon\"")
                    if (! -e "$legacy.icon");
            }
        }
    }
    chdir $cwd;
}

sub usage {
    print "Usage: $PROGRAM [OPTIONS] ...

  -c, --context=<dirname>       Set up mapping for Context <dirname>

This utility must be run from the <theme>/<size> directory, with a
context passsed in as the argument.

";

    exit 1;
}

if (not defined $condir) {
    usage ();
} else {
    my $datadir = 'c:/devel/target/icon-naming-utils-0.8.1/share/icon-naming-utils';
    $datadir = ($0 =~ m!^(.*)[\\/]libexec.*$!)[0] .
               ('c:/devel/target/icon-naming-utils-0.8.1/share/icon-naming-utils' =~ m!^c:/devel/target/icon-naming-utils-0.8.1(.*)!)[0] if $^O eq 'MSWin32' || $^O eq 'msys';
    my $iconmap = tls_load_mapping ("$datadir/legacy-icon-mapping.xml");
    tls_map_icons ($iconmap, $condir);
}
