#!/usr/bin/perl
#
# expireall - Expire all minivend catalogs
#

use Getopt::Std;

$VendRoot = $VendRoot || '/home/minivend/mvend';
## END CONFIGURABLE VARIABLES

BEGIN {
    eval {
        require 5.004;
        require FindBin;
        $VendRoot = $FindBin::RealBin;
        $VendRoot =~ s/.bin$//;
    };
    ($VendRoot = $ENV{MINIVEND_ROOT})
        if defined $ENV{MINIVEND_ROOT};
}

my $query;

$USAGE = <<EOF;
Expire all listed MiniVend catalogs. Will read information from
either:

	$VendRoot/minivend.cfg
	$VendRoot/catalogs.list

usage: expireall [-r]

	-r    Use reorganize parameter in command

EOF

getopts('r') or die "$@\n$USAGE\n";

if ($opt_r) {
	$flag = '-r';
}

# Parse the minivend.cfg file to look for script/catalog info
PARSECFG: {
	my $file;
	my @cfglines;

	$file = "$VendRoot/minivend.cfg";
	open(MVCFG, $file) or die "Couldn't read $file: $!\n";
	while(<MVCFG>) { push(@cfglines, $_) if /^\s*catalog\s+/i }
	close MVCFG;

	eval {
		$file = "$VendRoot/catalogs.list";
		open(MVCFG, $file) or die "Couldn't read $file: $!\n";
		while(<MVCFG>) { push(@cfglines, $_) if /^\s*catalog\s+/i }
		close MVCFG;
	};
	eval {
		$file = "$VendRoot/active.catalogs";
		open(MVCFG, $file) or die "Couldn't read $file: $!\n";
		while(<MVCFG>) { push(@cfglines, $_) if /^\s*catalog\s+/i }
		close MVCFG;
		rename $file, "$file.bak";
	};
	my %seen;
	@cfglines = grep !$seen{$_}++, @cfglines;

	for(@cfglines) {
		next unless /^\s*catalog\s+([-\w_]+)/i;
		push @cats, $1;
	}

}

for(@cats) {
	system "$VendRoot/bin/expire $flag -c $_";
}
