#!/usr/local/bin/perl

###
###  Copyright 2000-2007 University of Illinois Board of Trustees
###  All rights reserved. 
###
###  from2to - Script to convert one DataStore format files to another
###
###  Campus Information Technologies and Educational Services
###  University of Illinois at Urbana-Champaign
###

use warnings;
no warnings 'once';
use Getopt::Std;
use File::Basename;

use PSGConf;

###
### Figure out what module we want to include to get the
### proper output
###
($convert_from, $convert_to) = split (/2/, basename ($0));
if ( $convert_to eq "Storable" ) {
	use Storable;
} elsif ( $convert_to eq "AppConfig" ) {
	eval "use PSGConf::Action::GenerateFile::$convert_to;";
}

&getopts ('hi:o:v');

if ( $opt_h )  {
	warn "$0: [-h] [-v] -i <filename> -o <filename>\n";
	warn "\t-h\tThis help screen\n";
	warn "\t-i <filename>\tInput file (REQUIRED)\n";
	warn "\t-o <filename>\tOutput file (REQUIRED)\n";
	warn "\t-v\tVerbose output\n";
	exit (0);
}

###
### Create a special psgconf_modules file so we guarentee
### that we get use DataStore::$convert_from.
###
$modules_file = '/etc/psgconf_modules';
$modules_tmp_file = (( -d  $ENV{'PSGCONF_TMPDIR'} )?
					$ENV{'PSGCONF_TMPDIR'}:
					'/var/tmp/')
				. '/psgconf_modules';
if ( -f $modules_file ) {
	my ($mod);
	open (FP, $modules_file )
		|| die "Could not find file ($modules_file)\n";
	while (<FP>) { $mod .= $_; };
	close FP;

	$mod =~ s/PSGConf::DataStore::.*$/
				PSGConf::DataStore::$convert_from config_file=$opt_i/;

	open (FP, '> ' . $modules_tmp_file ) 	
		|| die "Could not write out file ($modules_tmp_file)\n";
	printf FP $mod;
	close FP;
}

$psgconf = PSGConf->new({
	config_file => $opt_i,
	modules_file => $ENV{'PSGCONF_TMPDIR'} . '/psgconf_modules'
}) || die "Can not instantiate PSGConf module\n";

$psgconf->access_data_stores();

if ( $convert_to eq "Storable" ) {
	store $psgconf->{data}, $opt_o;
} elsif ( $convert_to eq "AppConfig" ) {
	$href = $psgconf->get_all_data();

	map {
     	$data->{$_} = $psgconf->data_obj($_)->get();
	} keys %$href;

	$action = PSGConf::Action::GenerateFile::AppConfig->new(
     	name => $opt_o,
     	mode => 0644,
     	vars => $data,
     	backup => 0
	);

	$action->check();
	$action->do();
}

unlink ( $modules_tmp_file );

exit (0);


syntax highlighted by Code2HTML, v. 0.9.1