# $Id: AcidDB.pm,v 1.1 2004/11/15 14:23:01 jari Exp $

# Description:
# Maintains a connection to a database.

package AcidDB;

use strict;

use Carp;
use Carp qw(cluck);

use DBI;

use AcidConfig;
use ResultSet;



sub connect {
    my $this = shift;
    my %params = @_;

    unless( exists $params{'connect'} ) {
	cluck 'Must have connect parameter.';
	return 1;
    }
    my $handle=DBI->connect($params{'connect'},
			    $params{'id'},$params{'password'});
    unless($handle) {
	cluck 'Could not connect to database.';
	return 1;
    }
    $this->{'handle'} = $handle;
    return 0;
}



sub disconnect {
    my $this = shift;
    if (exists $this->{'handle'}) {
	$this->{'handle'}->disconnect() or cluck "Error trying to disconnect.";
    }
}



sub new {
    my $class = shift;
    my $this = {};
    bless($this, $class);
    return $this;
}



sub query {
    my $this = shift;
    my $sql = shift;

    if (!exists($this->{'handle'})) {
	cluck 'Not connected to any database.';
	return undef;
    }
    unless ($sql) {
	cluck 'Must have a SQL string as parameter.';
	return undef;
    }

    my $sth = undef;
    unless ($sth = $this->{'handle'}->prepare($sql)) {
	cluck 'Could not prepare SQL string.';
	return undef;
    }
    unless ($sth->execute()) {
	cluck 'Could not execute.';
	return undef;
    }
    return ResultSet->new($sth);
}



sub ssh_setup() {
    if (!AcidConfig->ssh()) {
	print "ssh tunneling is not required by AcidConfig.\n";
	return 1;
    }
    else {
	print "Setting up ssh tunneling.\n";
    }
    my $acid_localport=AcidConfig->ssh_localport("acid");
    my $remote_host=AcidConfig->mysqlhost("acid");
    my $ssh_cmd=(AcidConfig->ssh_cmd() . " $acid_localport:$remote_host:" .
		 AcidConfig->ssh_remoteport("acid") . " " .
		 AcidConfig->ssh_user("acid") . "\@$remote_host");
    my $status=system($ssh_cmd);
    if ($status) {
	return $status;
    }
    my $genome_localport=AcidConfig->ssh_localport("genome");
    print "\t$ssh_cmd\n";
    if ($acid_localport eq $genome_localport) {
	return $status;
    }
    else {
	print "two is needed\n";
	$remote_host=AcidConfig->mysqlhost("genome");
	$ssh_cmd=(AcidConfig->ssh_cmd() . " $genome_localport:$remote_host:" .
		  AcidConfig->ssh_remoteport("genome") . " " .
		  AcidConfig->ssh_user("genome") . "\@$remote_host");
    }
    print "\t$ssh_cmd\n";
    return system($ssh_cmd);
}

1;
