#! /usr/perl5/bin/perl -w
#
# ident   "@(#)MetadataRepository.pm 1.1     03/11/27 SMI"
# 
# Copyright 2003 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

# 
# Module: ScSnapshot::MetadataRepository
# 
# Provides access to the information stored in the metadata repository.
#

package ScSnapshot::MetadataRepository;
use strict;

#
# Constructor
# Arguments:
#  1) Name of the file containing the metadata repository.
#     Cannot be undefined.
#
sub new {
  my $proto = shift;
  my $class = ref($proto) || $proto;
  my $self  = {};
  $self->{FILENAME} = shift;
  $self->{REPOSITORY} = undef;
  bless ($self, $class);
  $self->_init();
  return $self;
}

#
# Reads the file containing the metadata repository and fills in the
# hash holding the default values. Invoked by the class constructor.
#
sub _init {
  my $self = shift;
  $self->{REPOSITORY} = { ResourceGroups => {} , Resources => {} };
  open(DATAFILE, "<" . $self->filename) || 
    die ("INTERNAL ERROR: Cannot open metadata repository: $self->filename : $!"); 
  while (my $line = readline(*DATAFILE)) { 
    # drop commented lines and empty lines
    unless ($line =~ /^\#/ || $line =~ /^\s$/) {   
      my $properties; 
      # look for rg properties and remove trailing newline if any
      if (($line =~ s/^rg:(.*)\n/$1/) || ($line =~ s/^rg:(.*)/$1/)) {
	$properties = $self->resourcegroups();
      }
      # look for resource properties and remove trailing newline if any
      elsif (($line =~ s/^r:(.*)\n/$1/) || ($line =~ s/^r:(.*)/$1/)) {
	$properties = $self->resources();
      }
      
      # ignore malformed lines
      if ($properties) { 
	# look for properties with default value
	if ($line =~ s/(.*) \((.*)\)/$1 $2/) {
	  my $name = $line;
	  my $value = $line;
	  $name =~ s/ .*//;
	  $value =~ s/.* //;
	  $value =~ s/"(.*)"/$1/; # unquote value if needed
	  $value =~ s/null//; # replace value "null" by the empty 
	                      # string if needed
	  $properties->{$name} = $value;
	} else {
	  # no default value
	  $properties->{$line} = undef; 
	}
      }
    }
  }
  
  close(DATAFILE);
} 

#
# Gets/Sets the name of the file containing the metadata repository
#
sub filename {
  my $self = shift;
  if (@_) { 
    $self->{FILENAME} = shift;
  }
  return $self->{FILENAME};
}

#
# Gets/Sets the sub-hash of the metadata repository holding default values 
# for the resource groups.
#
sub resourcegroups {
  my $self = shift;
  if (@_) { 
    $self->{REPOSITORY}->{ResourceGroups} = shift;
  }
  return $self->{REPOSITORY}->{ResourceGroups};
}

#
# Gets/Sets the sub-hash of the metadata repository holding default values 
# for the resources.
#
sub resources {
  my $self = shift;
  if (@_) { 
    $self->{REPOSITORY}->{Resources} = shift;
  }
  return $self->{REPOSITORY}->{Resources};
}

# Return success for module load
1; 
