#!/usr/bin/perl
use File::Find qw(find);
use Archive::Tar;

my(@FILES);
my $root = "/home/cpanel/cpanelsync/addons";
opendir(DD,${root});
while($dir = readdir(DD)) {
	next if ($dir =~ /\.bak/);
	next if ($dir =~ /^\./);
	next if (! -d "${root}/${dir}");
	next if (-l "${root}/${dir}");


	chdir("${root}/${dir}");
	opendir(DDL,"${root}/${dir}");
	while($subdir = readdir(DDL)) {
		next if ($subdir =~ /^\./);
		next if (! -d "${root}/${dir}/${subdir}");
		next if (-l "${root}/${dir}/${subdir}");
		@FILES=();
		if ($ARGV[0] eq "bz2") {
		           find(\&wanted, ${subdir});			
			$tar = Archive::Tar->new;
			$tar->add_files(@FILES);
			$tar->write("${root}/${subdir}.tar");
			undef $tar;
			system("bzip2","-v","${root}/${subdir}.tar");
			system("mv","-fv","${root}/${subdir}.tar.bz2","${root}/${dir}/${subdir}.tar.bz2");
		}
		if ($ARGV[0] eq "lock") {
			open(LOCK,">","${root}/${dir}/${subdir}/.cpanelsync.lock");
			print LOCK "locked";
			close(LOCK);
			next();
		}
		if ($ARGV[0] eq "unlock") {
			open(LOCK,">","${root}/${dir}/${subdir}/.cpanelsync.lock");
			close(LOCK);
			next();
		}
		chdir("${root}/${dir}/${subdir}");	
		system("/home/cpanel/buildcpanelsync");

	}
	closedir(DDL);
}
closedir(DD);

sub wanted {
	my $file = "$File::Find::dir/$_";
	return if ($file =~ /\.bz2$/ && $file !~ /\.bz2\.bz2$/);
	push(@FILES,$file);
}
