#!/usr/bin/perl
#
# Perl wrapper to call various xsync-* scripts
#

use Getopt::Long;
use File::Basename;
use strict;

Getopt::Long::Configure ("bundling");

my ($help, $dir, $noop, $quiet, $debug, $verbose);
my %select = ();
GetOptions( 
  'help|h|?' => \$help,
  'dir|d:s' => \$dir,
  'verbose|v' => \$verbose,
  'quiet|q' => \$quiet,
  'debug' => \$debug,
  'n'=> \$noop,
  # Selection args
  'packages' => \$select{packages},
  'services' => \$select{services},
  'scripts' => \$select{scripts},
  'apt' => \$select{apt},
  'yum' => \$select{yum},
  'cpan' => \$select{cpan},
  'remove' => \$select{remove},
  'restart' => \$select{restart},
);
$dir ||= '/etc/xsync';
# --packages = --remove --apt --yum --cpan
delete @select{qw(remove apt yum cpan)} if $select{packages};
# --services includes --restart
delete $select{restart} if $select{services};

if ($help) {
  print "usage: " . basename($0) . " [-n] [-v] [-q] [-d <xsyncdir>]\n";
  print "  selectors:\n";
  print "    --packages - select package removals and installs\n";
  print "    --services - select service checking\n";
  print "    --restart  - select service restarts\n";
  print "    --scripts  - select xsync script execution\n";
  print "  (finer-grain selectors are also available - 'man xsync' for details)\n";
  exit 0;
}

# Propogate some args to child scripts
my @args;
push @args, '-n' if $noop;
push @args, '-q' if $quiet;
push @args, '-v' if $verbose;
push @args, "-d$dir";

unless (-d $dir) {
  print "Error: invalid directory $dir\n";
  exit 1;
}

print "dir: $dir\n" if $verbose && $dir ne '/etc/xsync';

# Assemble the xsync directory globlist
my %glob = (
  remove   => "$dir/*-remove.d",
  apt      => "$dir/apt-install.d",
  yum      => "$dir/yum-install.d",
  cpan     => "$dir/cpan-install.d",
  restart  => "$dir/service-restart.d",
  packages => "$dir/*-remove.d $dir/[ay]*-install.d $dir/cpan-install.d",
  services => "$dir/*-off.d $dir/*-on.d",
  scripts  => "$dir/scripts*.d",
);
my @glob = qw(remove packages apt yum cpan services scripts restart);
my $glob;
# Check for non-empty select values
if (grep { $_ } values %select) {
  $glob = join(' ', map { $glob{$_} } grep { $_ if $select{$_} } @glob);
} else {
  $glob = join(' ', map { $glob{$_} } @glob);
}
print "glob: $glob\n" if $debug;
my @globset = glob $glob;
# print "globset: " . join(' ', @globset) . "\n" if $debug;

chdir dirname $0;

my %done = ();
for my $i (@globset) {
  next if $done{$i};
  $done{$i} = 1;
  $i = 'xsync-' . basename($i);
  $i =~ s/\.d$//;
  if (! -f $i || ! -x $i) {
    print "Error: problems with xsync script $i - aborting\n";
    exit 1;
  }
  print "\n** $i **\n\n" if $verbose;
  system "./$i", @args;
}


# arch-tag: 775d117a-8599-4442-9dc5-d009f59a4f19
