#!/usr/bin/perl
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
# bos720 src/bos/usr/bin/cdat/cdat-delete.pl 1.6 
#  
# Licensed Materials - Property of IBM 
#  
# COPYRIGHT International Business Machines Corp. 2010,2011 
# All Rights Reserved 
#  
# US Government Users Restricted Rights - Use, duplication or 
# disclosure restricted by GSA ADP Schedule Contract with IBM Corp. 
#  
# IBM_PROLOG_END_TAG 
# @(#)23    1.6  src/bos/usr/bin/cdat/cdat-delete.pl, cdat, bos720 7/15/11 04:16:53
use warnings;
use strict;
use Getopt::Long;
use Fcntl ':flock';	# LOCK_* constants
use XML::LibXML;
use cdat;
use messages;

#
# Constants.
#
my $XMLFILE = 'cdat.xml';

######################################################################
# Function:	usage
# Purpose:	Display usage.
# Tasks:	Print usage and exit.
# Input:	None
# Output:	None
######################################################################
sub usage
{
    printf(STDERR catgets(MSG_CDAT_DELETE_USAGE,
        "Usage: cdat delete -h\n".
	"       cdat delete -p PMR\n".
	"       cdat delete Id\n"));
    exit(1);
}

######################################################################
# Function:	main
# Purpose:	Entry point of the delete subcommand.
# Tasks:	Parse command line and delete collects matching query.
# Input:	None
# Output:	None
######################################################################
sub main
{
    my ($rc, $pmr, $id);

    # Parse command line options
    Getopt::Long::Configure('bundling', 'no_ignore_case');
    $rc = GetOptions(
	'h'   => \&usage,
	'p=s' => \$pmr,
	);
    if (!$rc) {
	usage();
    }

    # make sure we have -p or a collect id, but not both
    if (!defined($pmr)) {
	# no -p specified, use collect id
        usage() if (@ARGV != 1);
        $id = shift @ARGV;
    }
    usage() if (@ARGV != 0);

    # validate PMR number
    if (defined($pmr) && !($pmr =~ m/\d{5,}(,[0-9A-Za-z]{3,}){2}/)) {
	printf(STDERR catgets(MSG_INVALID_PMR,
	    "Invalid PMR '%s', format should be 'PMR#,BRANCH#,COUNTRY#'.\n"), $pmr);
	exit(1);
    }

    my $path = cdat::odm_get_path;
    if (!defined($path)) {
	printf(STDERR catgets(MSG_DIR_NOT_DEFINED,
	    "The cdat directory path is not defined.\n".
	    "Please, run 'cdat init' first.\n"));
	exit(2);
    }

    cdat::switch_user();

    my $fh;
    if (!open($fh, "+<", "$path/$XMLFILE")) {
	printf(STDERR catgets(MSG_CANNOT_OPEN,
	    "Cannot open %s.\n"), "$path/$XMLFILE");
	exit(2);
    }
    # Try to acquire exclusive write access to the XML file (but do not block)
    if (!flock($fh, LOCK_EX | LOCK_NB)) {
        printf(STDERR catgets(MSG_BUSY,
	    "Another instance of the cdat command is running.\n".
	    "Please wait until this instance terminates.\n"));
        exit(2);
    }

    my $parser = XML::LibXML->new();
    if (!defined($parser)) {
        printf(STDERR catgets(MSG_CANNOT_CREATE_XML_PARSER,
	    "Cannot create XML parser.\n"));
        exit(2);
    }
    my $tree = $parser->parse_fh($fh);
    if (!defined($tree)) {
        printf(STDERR catgets(MSG_CANNOT_PARSE,
	    "Cannot parse %s.\n"), "$path/$XMLFILE");
	exit(2);
    }
    my $root = $tree->getDocumentElement;

    #
    # Iterate over all collect elements to see if it should be removed.
    #
    my $found = 0;
    my @collects = $root->getElementsByTagName('collect');
    foreach my $collect (@collects) {
        if (defined($id)) {
	    # check if the collect id matches
            next if ($collect->getAttribute('id') ne $id);

	} else {	# -p specified
	    # check if this collect has a PMR number
	    my @pmrs = $collect->getElementsByTagName('pmr');
	    next if (@pmrs == 0);
	    # check if the PMR number matches
	    next if ($pmrs[0]->textContent ne $pmr);
	}

	# Find data location for this collect
	my @locations = $collect->getElementsByTagName('location');
	next if (@locations == 0);	# should not happen
	my $dir = $locations[0]->textContent;
	$dir =~ s/\/+$//;	# remove trailing "/"

	# We have found one collect that matches our query
        $found = 1;

	# Remove the directory from the repository
	printf(catgets(MSG_REMOVING_DIRECTORY,
	    "Removing directory %s from the repository...\n"), "$path/$dir");
	system("rm -fr '$path/$dir'");
	if ($? != 0) {
	    # Warn if something went wrong
	    printf(STDERR catgets(MSG_CANNOT_REMOVE_DIR,
	        "Cannot remove directory %s.\n"), "$path/$dir");
	} else {
	    printf(catgets(MSG_DONE, "Done.\n"));
	}

	# Remove the collect element from the XML file
	$root->removeChild($collect);
	last if defined($id);	# there can be only one collect with that id
    }
    if (!$found) {
        printf(STDERR catgets(MSG_NO_MATCHING_COLLECT_FOUND,
	    "No matching collect found.\n"));
	exit(2);
    }

    # Dump the updated cdat.xml file
    seek($fh, 0, Fcntl::SEEK_SET);
    truncate($fh, 0);
    $tree->toFH($fh, 1);
}

main;
