# $Id: Entry.pm,v 1.2 2004/12/06 20:38:06 jkremer Exp $
# Copyright 2004 Sun Microsystems, Inc., All Rights Reserved.
# Sun Proprietary/Confidential: For Internal Use Only
package Catalog::Entry;

use vars qw($CACHE);
use strict;

BEGIN {
  $CACHE = { device => {},
				 catalogDir => "/opt/SUNWstade/System/Catalog/",
				 commonDir  => "/opt/SUNWstade/System/Catalog/common/",
				 deviceDir  => "/opt/SUNWstade/System/Catalog/device/"
			  };
}

sub getCacheEntry {
  my ($class, $type, $entry) = @_;
  return $CACHE->{device}->{$type}->{$entry}
}

sub listEntries {
  my ($class) = @_;
  my %devmap;

  my $ETC = "/etc/storade";
  opendir(O, $ETC);
  my @pfiles = readdir(O);
  foreach my $f (@pfiles) {
	 if ($f =~ /(.+)\.conf/) {
		my $hash = $class->file2hash($f);
		$devmap{$1}=$hash->{BASE_DIR};
	 }
  }
  close(O);
  my $DEVDIR = "/opt/SUNWstade/System/Catalog/device/";
  opendir(O, $DEVDIR);
  my @dfiles = readdir(O);
  foreach my $f (@dfiles) {
	 next if ("." eq $f);
	 next if (".." eq $f);
	 next if ($devmap{$f});
	 $devmap{$f} = $DEVDIR."/".$f;
  }
  close(O);
  return \%devmap;
}

# Define load to load entry data.
sub load { }

sub findFile {
  my ($this) = @_;

  if (!$this->{dir}){
	 $this->{dir} = $this->getDeviceDir($this->{type});
  }
  $this->{file} = $this->{dir} . "/" . $this->{entry};
}

sub loadEntry {
  my ($this) = @_;
  $this->findFile();

  my $dev = $CACHE->{device}->{$this->{type}};
  if ($dev){
	 my $cat = $dev->{$this->{entry}};
	 # TODO check dir is same?
	 return $cat if ($cat);
  }

  $this->load();
  if (!$this->{error}){
	 if (!$dev){
		$CACHE->{device}->{$this->{type}} = {};
		$dev = $CACHE->{device}->{$this->{type}};
	 }
	 $dev->{$this->{entry}} = $this;
  }
  return $this;
}

sub getCommonDir {
  my ($this) = @_;
  return $CACHE->{commonDir};
}

sub getDeviceDir {
  my ($this, $type) = @_;
  if (!$type){
	 return $CACHE->{deviceDir};
  }
  if (-d $CACHE->{deviceDir}.$type){
	 return $CACHE->{deviceDir}.$type;
  }
  my $confFile = "/etc/storade/$type.conf";
  if (-f $confFile){
	 my $hash = $this->file2hash($confFile);
	 return $hash->{BASE_DIR};
  }
  return "./";
}

sub setError {
  my ($this, $error) = @_;
  if ($this->{error}){
	 $this->{error} = $error . "\n" . $this->{error};
  }
  else {
	 $this->{error} = $error;
  }
}

sub error {
  my ($this) = @_;
  return $this->{error};
}


sub file2hash {
  my ($class, $file) = @_;
  open(O, "$file");
  my @L = <O> ; close(O);
  my %HASH;
  foreach my $l (@L) {
	 my $line = $l;
	 my $sindex = index($line, "=");
	 next if ($sindex <= 0);
	 next if (index($line, "#") == 0);
	 my $value = substr($line, $sindex+1);
	 chomp $value;
	 $HASH{ substr($line, 0, $sindex) } = $value
  }
  return \%HASH;
}

1;

