#!/usr/bin/perl
use strict;
use warnings;

my $sync_dir = '/home/cpanel/cpanelsync';

foreach my $tree (@ARGV) {
    my $tree_dir = "$sync_dir/$tree";

    # Create the tree directory if it does not already exist
    if ( !-e $tree_dir ) {
        mkdir( $tree_dir, 0755 )
          or die "Could not create directory $tree_dir: $!";
    }
    elsif ( !-d $tree_dir ) {
        die "Tree $tree_dir exists but is not a directory";
    }

    chdir($tree_dir) or die "Could not use directory $tree_dir";

    # Lock the main directory and one level of subdirectories
    my @dirs = split( /\n/, `find . -maxdepth 1 -type d` );
    foreach my $dir (@dirs) {
        lockdir($dir);
    }

    # Special case for cPanel/WHM product
    if ( -d 'base/3rdparty' ) {
        lockdir('base/3rdparty');
    }
}

# Lock the directory
sub lockdir {
    my ($dir) = @_;
    my $lockfile = "$dir/.cpanelsync.lock";
    if ( open( my $fh, '>', $lockfile ) ) {
        print {$fh} 'locked';
        close($fh);
    }
    else {
        die "Failed to lock directory $dir: $!";
    }
}
