#!/usr/bin/perl

# $Id: ep,v 1.1 2002/11/22 18:58:04 jhorwitz Exp $

# Oracle Perl Procedure Library

# Copyright (c) 2001, 2002 Jeff Horwitz (jeff@smashing.org).
# All rights reserved.

# This package is free software; you can redistribute it and/or modify it under
# the same terms as Perl itself.

use DBI;

sub usage
{
	print STDERR <<_DONE_;
usage: ep export <database> <table>
       ep import <database> <table> <file>
_DONE_
}
         
sub get_userpass
{
	print STDERR "Username: ";
	my $username = <STDIN>;
	chomp($username);
	print STDERR "Password: ";
	system("stty -echo");
	my $password = <STDIN>;
	chomp($password);
	system("stty echo");
	print STDERR "\n";
	return ($username, $password);
}

my $cmd = shift @ARGV;

if ($cmd eq 'import') {
	if ($#ARGV != 2) {
		usage();
		exit(1);
	}

	my ($db, $table, $file) = @ARGV;

	print STDERR "Importing code to $table in $db\n";

	my ($username,$password) = get_userpass();

	open(FILE, $file) or die $!;
	my ($l, $buf);
	while (defined($l = <FILE>)) {
		$buf .= $l;
	}
	close(FILE);

	# escape single quotes for oracle
	$buf =~ s/'/''/g;

	my $dbh = DBI->connect("dbi:Oracle:$db", $username, $password,
		{ AutoCommit => 0 });
	unless ($dbh) {
		die "connection to $db failed: $DBI::errstr";
	}

	my $sql = "delete from $table";
	$dbh->do($sql) or die $dbh->errstr;
	$sql = "insert into $table (CODE) values ('$buf')";
	unless ($dbh->do($sql)) {
		$dbh->rollback();
		die $dbh->errstr;
	}

	$dbh->commit();

	$dbh->disconnect();

	print STDERR "Code successfully imported.\n";
}

elsif ($cmd eq 'export') {
	if ($#ARGV != 1) {
		usage();
		exit(1);
	}

	my ($db, $table) = @ARGV;

	print STDERR "Exporting code from $table in $db.\n";

	my ($username,$password) = get_userpass();
	my $dbh = DBI->connect("dbi:Oracle:$db", $username, $password);
	unless ($dbh) {
		die "connection to $db failed: $DBI::errstr";
	}

	my $sql = "select code from $table";
	$dbh->{LongReadLen} = 8192;
	my $sth = $dbh->prepare($sql);
	$sth or die $dbh->errstr;
	die $dbh->errstr unless ($sth->execute());
	if ($sth->rows > 1) {
		$dbh->disconnect();
		die "more than one row found in $table";
	}
	my $h = $sth->fetchrow_hashref();
	$sth->finish();

	print STDOUT ${$h}{'CODE'};

	$dbh->disconnect();

	print STDERR "Code successfully exported.\n";
}

else {
	usage();
	exit(1);
}

exit(0);
