#! /usr/bin/perl

#
# scan-translatables.pl
# (c) T.Kusano <AE5T-KSN@asahi-net.or.jp>, 2000.
#
# usage: scan-translatables.pl [-c] directory
#
#    Scan all *.directory/*.desktop files under the specified directory
#    and display English and 'ja' entries.
#    If '-c' option is specified, display files that have no 'ja'
#    entries.
#

use strict;
use vars qw($opt_c $LANG);
use DirHandle;
use Getopt::Std;

$LANG = 'ja';

getopts('c');

$opt_c = 0 unless defined($opt_c);

if (!@ARGV) {
    &usage();
}

&main(@ARGV);

exit 0;

sub main {
    my $directory = shift;
    unless (-d $directory) {
	print STDERR "Error: $directory is not a directory.\n";
	exit 1;
    }
    &scan_dir($directory, '');
}

sub scan_dir {
    my $basedir = shift;
    my $dir = shift;

    my $top = "$basedir$dir";
    my $dh = new DirHandle $top or die "Error: opendir($dir): $!\n";
    my @subdirs = ();
    while (defined(my $ent = $dh->read)) {
	next if ($ent eq '.'  || $ent eq '..');
	if (-d "$top/$ent") {
	    push @subdirs, $ent;
	} elsif ($ent =~ /\.(?:desktop|directory)/) {
	    &check_file($basedir, "$dir/$ent");
	}
    }
    $dh->close;
    undef $dh;
    foreach my $d (@subdirs) {
	&scan_dir($basedir, "$dir/$d");
    }
}

sub check_file {
    my $dir = shift;
    my $file = shift;
    my $n = 0;
    my $c = 0;
    open FH, "< $dir/$file" or die "Error: $file: $!\n";
    $file =~ s,^/,,;
    while (<FH>) {
	if (/^Name=/ ||
	    /^Comment=/) {
	    print "$file:$_" unless $opt_c;
	} elsif (/^Name\[$LANG\]=/o) {
	    print "$file:$_" unless $opt_c;
	    $n++;
	} elsif (/^Comment\[$LANG\]=/o) {
	    print "$file:$_" unless $opt_c;
	    $c++;
	}
    }
    close FH;
    if ($opt_c && ($n != 1 || $c != 1)) {
	print $file, "\n";
    }
}

# end of script
