#!/usr/bin/perl -w
# lcg-ManageVOTag
# versions <= 2.2.1 by Patricia Mendez Lorenzo
# versions >= 3.0.0 by Maarten Litmaath

use strict;

my $version = '3.0.0';

(my $prog = $0) =~ s-.*/--;

my $lcg_tags = 'lcg-tags';

my ($force, $op, $tagfile, @tags, $target, $tgtopt, $vo);

sub usage()
{
    my $msg = "Usage: $prog [options] operation

	|Options:
	|    -f
	|    -file file_name
	|    -h | --help
	|    -host host_name
	|    -sc SubCluster
	|    -tag tag(s)
	|    -V | --version
	|    -vo VO

	|Operations:
	|    --add
	|    --clean
	|    --list
	|    --remove
	|    --replace
	";

    $msg =~ s/^[ \t]+\|//gm;
    print STDERR "$msg\n";
    exit 1;
}

while ($_ = shift @ARGV) {

    if (/^-?-(add|clean|list|remove|replace)$/) {
	usage() if defined $op;
	$op = $1;
	next;
    }

    if (/^-?-f$/) {
	$force = 1;
	next;
    }

    if (/^-?-(tag)?file$/) {
	$tagfile = shift @ARGV and $tagfile !~ /^-/ or usage();
	next;
    }

    if (/^-?-h(elp)$/) {
	usage();
    }

    if (/^-?-(host|ce)$/) {
	usage() if defined $target;
	$target = shift @ARGV and $target !~ /^-/ or usage();
	$tgtopt = '--ce';
	next;
    }

    if (/^-?-(subcluster|sc)$/) {
	usage() if defined $target;
	$target = shift @ARGV and $target !~ /^-/ or usage();
	$tgtopt = '--sc';
	next;
    }

    if (/^-?-tags?$/) {
	while ($_ = shift @ARGV) {
	    unshift @ARGV, $_ and last if /^-/;
	    push @tags, $_;
	}

	usage() unless @tags;
	next;
    }

    if (/^-?-(V|version)$/) {
	print "$version\n";
	exit 0;
    }

    if (/^-?-vo$/) {
	$vo = shift @ARGV and $vo !~ /^-/ or usage();
	next;
    }

    print STDERR "$prog: unknown option or operation: $_\n";
    usage();
}

usage() unless defined $target && defined $op && defined $vo;

my $tag_op = $op eq 'add' || $op eq 'remove' || $op eq 'replace';

usage() if  $tag_op && !@tags && !defined $tagfile;
usage() if !$tag_op && (@tags ||  defined $tagfile);

my $msg = "$prog: cannot execute '$lcg_tags'";

if ($tag_op) {
    my $tagstr = join(',', @tags) if @tags;
    my @cmd = ($lcg_tags, $tgtopt, $target, "--vo", $vo, "--$op");

    push @cmd, "--tags", $tagstr if @tags;
    push @cmd, "--tagfile", $tagfile if defined $tagfile;
    exec @cmd or die "$msg: $!\n";
}

if ($op eq 'clean' && !defined $force) {
    print "Do you really want to remove ALL tags for VO '$vo' from "
	. ($tgtopt eq "--ce" ? "host" : "SubCluster") . " $target ?\n"
	. "To confirm, type: yes\n";

    chomp(my $ans = <STDIN>);

    unless ($ans eq 'yes') {
	print STDERR "OK, nothing was changed.\n";
	exit 0;
    }
}

exec $lcg_tags, $tgtopt, $target, "--vo", $vo, "--$op" or die "$msg: $!\n";

