#!/usr/bin/perl
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
# bos720 src/bos/usr/bin/cdat/cdat-list-nodes.pl 1.3 
#  
# 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 
# @(#)25    1.3  src/bos/usr/bin/cdat/cdat-list-nodes.pl, cdat, bos720 7/15/11 05:04:50
use warnings;
use strict;
use Getopt::Long;
use cdat;
use messages;

#
# Constants.
#
use constant NODES => 'nodes.txt';

######################################################################
# Function:	usage
# Purpose:	Display usage.
# Tasks:	Print usage and exit.
# Input:	None
# Output:	None
######################################################################
sub usage
{
    printf(STDERR catgets(MSG_CDAT_LIST_NODES_USAGE,
        "Usage: cdat list-nodes -h\n".
	"       cdat list-nodes [-f File ...]\n"));
    exit(1);
}

######################################################################
# Function:	main
# Purpose:	Entry point of the list-nodes subcommand.
# Tasks:	Parse nodes from file and print to standard output.
# Input:	None
# Output:	None
######################################################################
sub main
{
    my ($rc, @filenames);

    # Parse command line options
    Getopt::Long::Configure('bundling', 'no_ignore_case');
    $rc = GetOptions(
	'h'   => \&usage,
        'f=s' => \@filenames
	);
    if (!$rc || @ARGV != 0) {
        usage();
    }

    cdat::switch_user();

    if (@filenames == 0) {
        # no filename specified, use default nodes.txt from repository
        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);
        }
        @filenames = ( "$path/".NODES );
    }

    # Open and parse the nodes files. We don't use cdat::read_nodes_from_files
    # as it does not keep the original ordering from the nodes files.

    foreach (@filenames) {
        $rc = open(IN, $_);
        if (!$rc) {
            printf(STDERR catgets(MSG_CANNOT_OPEN_FILE,
	        "Cannot open file %s.\n"), $_);
            exit(2);
        }
        while (<IN>) {
            next if /^\s*#/;	# skip single-line comments from file
	    # ignore trailing comments
	    s/#.*$//;
	    s/\s+$//;
            chomp;
            # parse entry
            my ($name, %info) = cdat::get_node_info($_);
            next if !defined($name);

	    if (defined($info{user})) {
              print("$info{type} $info{user}\@$name\n");
	    } else {
	      print("$info{type} $name\n");
	    }
        }
        close(IN);
    }
}

main;
