#!/bin/env perl

use strict;

use File::Path;
use Digest::MD5;

my $tarbz2name = $ARGV[0];
my $tmpdir = $ARGV[1];

my $srcdir = "$tmpdir/sodipodi-flags";
my $iconsdir = "$ENV{'HOME'}/.icons";
my $tgtdir = "$iconsdir/flags";

my $genCcScript = "./gen_cc.pl";

system( "tar", "-C", $tmpdir, "-xjf", $tarbz2name ) == 0 or die "Could not unpack the archive\n";

chdir $srcdir or die "Could not change directory to the flags home\n";

open( GENCCFILE, $genCcScript ) or die "Could not find the gen_cc.pl script";
binmode GENCCFILE;
my $ctx = Digest::MD5->new;
$ctx->addfile( *GENCCFILE );
close GENCCFILE;
my $digest = $ctx->hexdigest;

( $digest eq "b570bfc4f7a4b439053bdac5a1de0504" ) or die "Invalid version of the script file!";

my $perlPath = $^X;

system( $perlPath, $genCcScript ) == 0 or die "Could not generate 2-letter flags\n";

stat( $iconsdir );
	
( ( -d _ ) and ( -w _ ) ) or die "There is no icons directory $iconsdir";

if ( stat( $tgtdir ) ) {
  rmtree $tgtdir, 0, 1  or die "Could not remove the target directory $tgtdir";
}

system( "mv -f cc $tgtdir" ) == 0 or die "Could not rename cc to $tgtdir: $?";

chdir $tmpdir;
rmtree $srcdir, 0, 1 or die "Could not remove the temp source directory $srcdir";

exit 0;
