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

my %options = ();

getopts("qa:f:t:",\%options);

# a = type of addon
# f = addon name
# t = action (bz2|lock|unlock)

my(@FILES);
my $cpaddons_root = '/home/cpanel/cpanelsync/addons/cpaddons';
chdir $cpaddons_root;
system('bzip2','-k','cPAddonsAvailable.pm');


opendir my $cpaddons_md5_dh,$cpaddons_root . '/cPAddonsMD5';
my @md5files = readdir $cpaddons_md5_dh;
closedir $cpaddons_md5_dh;

chdir $cpaddons_root . '/cPAddonsMD5';
foreach my $md5file (@md5files) {
    next if (! -f $md5file);
    system('bzip2','-k',$md5file);
}
system('/home/cpanel/buildcpanelsync');

my $root = "/home/cpanel/cpanelsync/addons/cpaddons/cPanel";


if ($options{'t'} eq '') { 
	die '-t action (bz2|lock|unlock) is required';
}
if ($options{'a'} ne "" && ! -d "${root}/$options{'a'}") {
	die '-a may only be (Blogs Bulletin_Boards Chat CMS Ecommerce Gallery Guest_Books Support)';
}

opendir(DD,$root);
while($dir = readdir(DD)) {
	next if ($dir =~ /\.bak/);
	next if ($dir =~ /^\./);
	next if (! -d "$root/$dir");
	next if (-l "$root/$dir");

	next if ($options{'a'} ne '' && $dir ne $options{'a'} );

	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");

		next if ($options{'f'} ne '' && $subdir !~ /^$options{'f'}/ );

		@FILES=();
		if ($options{'t'} 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");
         system('bzip2','-k',$subdir.'.pm');
		} elsif ($options{'t'} eq "lock") {
			open(LOCK,">","$root/$dir/$subdir/.cpanelsync.lock");
			print LOCK "locked";
			close(LOCK);
			next();
		} elsif ($options{'t'} 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);
}
