#!/usr/bin/perl

# check_bzip.pl                    Copyright(c) 1997-2010 cPanel, Inc.
#                                          All rights Reserved.
# copyright@cpanel.net                      http://cpanel.net

use strict;
use warnings;

use POSIX;

exit; # Disabled by JD on 15 Apr 2015

my $home_dir = "/home/cpanel/cpanelsync";
unless ( -d $home_dir ) {
    die "Error: Missing $home_dir\n";
}
chdir $home_dir || die "Error: Unable to cd to $home_dir\n";

# Check if server has a publication in progress
if ( -e ".publish.lock" ) {
    print "Publication in progress.  Skipping bzip check for now. \n";
    exit;
}

opendir( DIR, $home_dir ) || die "Unable to open $home_dir for reading\n";
my $cpanelsync2bzip = "$home_dir/util/cpanelsync2bzip";
unless ( -x $cpanelsync2bzip ) {
    die "Error: Missing $home_dir/util/cpanelsync2bzip\n";
}

my @trees = grep !/^\.\.?$/, readdir(DIR);

foreach my $tree (@trees) {
    next if $tree =~ /^1/;    # Skip trees starting with 1 per Todd R.
    next unless -e "$tree/distlist-$tree";
    next if $tree eq 'cpaddons';
    print "Checking $tree\n";
    open DIST_FILE, "<$tree/distlist-$tree" || die "unable to open $tree/distlist-$tree for reading: $!";
    my @dist_dirs = <DIST_FILE>;
    foreach my $dist_dir (@dist_dirs) {
        chomp $dist_dir;
        if ( -d "$tree/$dist_dir" ) {
            print "   Checking $dist_dir\n";
            my $dir_mod_time = -M "$tree/$dist_dir";
            my $bz2_mod_time = 0;
            if ( -e "$tree/$dist_dir.tar.bz2" ) {
                $bz2_mod_time = -M "$tree/$dist_dir.tar.bz2";
            }
            else {
                rebuild_bzip($tree);
                print "  Missing $tree/$dist_dir.tar.bz2\n";
                $bz2_mod_time = -M "$tree/$dist_dir.tar.bz2";
            }
            if ( $dir_mod_time < $bz2_mod_time ) {
                print "  Found stale $tree/$dist_dir.tar.bz2\n";
                rebuild_bzip($tree);
                last;
            }
        }
    }
    close DIST_FILE;
}

sub rebuild_bzip {

    my $tree = shift;
    print "Running $cpanelsync2bzip -f $tree\n";

    if ( $ENV{'USER'} eq 'tux' ) {
        system("$cpanelsync2bzip -f $tree");
    }
    elsif ( $ENV{'USER'} eq 'root' ) {
        system("su tux -c '$cpanelsync2bzip -f $tree'");
    }
    else {
        die "Must run script as root or tux\n";
    }
}
