#!/usr/bin/perl
# cpanel12 - buildtree2                      Copyright(c) 2005-2007 cPanel, Inc.
#                                                           All rights Reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited

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 $root = "/home/cpanel/cpanelsync/addons";

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 (cpanel|modules|scripts|whm)';
}

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

	    # why in the hell is archive::tar used here and the a system to bzip it, can't we just tar -cvfj it one swoop adn get rid of the extra (slow) module all together ?

            $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" );
            print "chdir into ${root}/${dir}/${subdir}\n";
            chdir("${root}/${dir}/${subdir}");
            print "Calling /home/cpanel/buildcpanelsync\n";
            system("/home/cpanel/buildcpanelsync");

        }
        elsif ( $options{'t'} eq "lock" ) {
            print "Writing ${root}/${dir}/${subdir}/.cpanelsync.lock\n";
            open( LOCK, ">", "${root}/${dir}/${subdir}/.cpanelsync.lock" );
            print LOCK "locked";
            close(LOCK);
            next();
        }
        elsif ( $options{'t'} eq "unlock" ) {
            print "Writing ${root}/${dir}/${subdir}/.cpanelsync.lock\n";
            open( LOCK, ">", "${root}/${dir}/${subdir}/.cpanelsync.lock" );
            close(LOCK);
            next();
        }

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

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