#!/usr/bin/perl -w
#
# extract.pl
# A script to extract files from each theme.
# This should be called *before* doing anything with the documentation.
#
# Licensed under the GPL-2
# © 2009 Mauro Lizaur <mauro@cacavoladora.org>
#

use warnings;
use strict;
use debian::themedata; 
use FileHandle;

my $PWD = `pwd`;
chomp($PWD);
my $DOCDIR = "debian/metacity-themes/usr/share/doc/metacity-themes";
my $THEMEDIR = "debian/metacity-themes/usr/share/themes";
my $TMPDIR = "debian/tmp";

&make_extract_themes();
print "\nDone";

sub extract_themes {
   my @x=@_;
   my $file=$x[0];
   my $path=$x[1];

   if ($file=~ m/gz$/){
       `tar zxf $file -C $path`;
   }else{
       `bunzip2 -k -c $file | tar -x -C $path`;
   }
}

sub fix_themes {
    my $tweak=$_[0];
    my $name=$_[1];
    my $file=$_[2];

    my $tarball=$file;
    if( $tweak eq 1 ){
        mkdir $TMPDIR;
        &extract_themes( ($file, $TMPDIR) );
        $tarball="TWEAK-".$name.".tar.gz";
        chdir($TMPDIR);
        my $themepath=`ls -F1|grep -e "/\$"`;
        chomp($themepath);
        my @docfiles=map { $themepath.$_; } split("\n",`ls $themepath`);
        my $docfiles=join(" ",@docfiles);
        `cp $docfiles $themepath$name`;
        `mv $themepath$name .`;
        `tar czvf $tarball $name`;
        `cp $tarball ../..`;
        chdir($PWD);
        `rm -fr debian/tmp`;
    }
    return $tarball;
}

sub make_extract_themes(){
    print "\nExtracting themes...\n";
    # Creates documentation for the themes which were installed.
    foreach my $theme (@themedata::installed){
        unless (-e "$THEMEDIR/$theme->{name}"){
            if (mkdir "$THEMEDIR/$theme->{name}"){
                print "$theme->{name}: created theme directory, $THEMEDIR/$theme->{name}.\n";
            }else{
                die "Error creating theme doc directory, $THEMEDIR/$theme->{name}\: $!\n";
            }
        }
        
        # /ugly/ hack to fix some themes that aren't extracted /correctly/
        my $filename = fix_themes( ($theme->{tweak}, $theme->{name}, $theme->{filename}) );
        &extract_themes( ($filename, $THEMEDIR) );
        
    }
}
