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

#
# Module: ScSnapshot::CodeGenerator
# 

package ScSnapshot::CodeGenerator;
use strict;
use Sun::Solaris::Utils qw(gettext);

#
# Constructor.
# Arguments:
#   1) The instance of ScSnapshot::InternalViewDumper to be used for
#      generating the code.
#      Cannot be undefined.
#
sub new
{
    my $proto = shift;
    my $class = ref($proto) || $proto;
    my $self = {};
    $self->{DUMPER} = shift;
    $self->{EXIT_CODE} = shift;
    bless ($self, $class);
    return $self;
}

#
# Generates the code representing a given view into the given file.
# If the file is not specified, the standard output is used instead.
# Arguments:
#   1) The view for which the code should be generated.
#      Cannot be undefined.
#   2) The name of the destination file.
#      May be undefined.
#
sub generate 
{
    my $self = shift;
    my $view = shift;
    my $filename = shift;
    if (defined($filename)) {

      # If a similar file is already present, rename it with .old sufffix
      if(open(OUTFILE, "<" . $filename)) {
	
	if(system('/usr/bin/mv', $filename, $filename . ".old") != 0) {
	  print STDERR gettext ("FATAL ERROR: Unable to rename file:")
	    . "\n\t[" . $filename . "] --> [" . $filename . ".old]\n";
	  exit $self->{EXIT_CODE}->getCode("EIO");
	}
	close(OUTFILE);
      }
      
      if(!open(OUTFILE, ">" . $filename)) {
	print STDERR gettext("FATAL ERROR: Unable to open file for writing:") 
	  . "\n\t[" . $filename . "]\n";
	exit $self->{EXIT_CODE}->getCode("EIO");
      }
      
      $self->{DUMPER}->dump($view, *OUTFILE);
      close(OUTFILE);
    } else {
      $self->{DUMPER}->dump($view, *STDOUT);
    }
} 

# Return success for module load
1; 
