## Usage: 
## perl -s galaxy-My2Pg_fix-seq.pl <parameters>
## The parameters are mandatory. Here is the list:
## -tdb=<target database name>
## -tdbhost=<target database host>
## -tdbuser=<target database user>
## -tdbpwd=<target database password for user>

#use strict; # commented cause it's annoying for parameters and I'm much too lazy to fix the issue
use warnings;
use DBI qw(:sql_types);
use DBD::Pg qw(:pg_types);
use utf8;
use Encode;

checkparam($odb, $odbhost, $odbuser, $odbpwd);

my $dbhp;
my $reqp;

my $dbhp = DBI->connect("DBI:Pg:dbname=$tdb;host=$tdbhost", "$tdbuser", "$tdbpwd", {AutoCommit => 1, RaiseError => 1, PrintError => 1});

my @tableslist;
$reqp = $dbhp->prepare("SELECT * FROM pg_tables WHERE tableowner = '$tdbuser';");
$reqp->execute;

while (my $refp = $reqp->fetchrow_hashref()) {
	push(@tableslist, $refp->{'tablename'});
}

foreach my $table (@tableslist) {
	
	$reqp = $dbhp->prepare("SELECT column_name FROM information_schema.columns WHERE table_schema = 'public' AND table_name = '$table';");
	$reqp->execute;
	while (my $refp = $reqp->fetchrow_hashref()) {
		if ($refp->{'column_name'} eq "id") {
			$reqp = $dbhp->prepare("SELECT setval( '".$table."_id_seq', (SELECT MAX(id) FROM $table) +1 );");
			$reqp->execute;
			last;
		}
	}
}

$dbhp->disconnect();

sub checkparam {
	for(my $i = 0; $i < 4; $i++) {
		if (!defined $_[$i] || $_[$i] eq "") { die "Execution aborted: All arguments are mandatory, see comments for more info."; }
	}
}
