#! perl -w

eval ("use DBI");
if ($@) { die "This system does not have the DBI installed....\n"; }

my ($dbh, $dbh2);

my $ConnStr = 'dbi:Sybase:server='. $ARGV[0];
my $arg_sysuser = $ARGV[1];
my $arg_syspwd = $ARGV[2];
$dbh = DBI->connect( $ConnStr, $arg_sysuser, $arg_syspwd, {RaiseError => 1, AutoCommit => 1} );
$dbh->{syb_err_handler} = \&err_handler;

my $sqlStatement = "select name from master..sysdatabases";
my $sth = $dbh->prepare($sqlStatement);
unless ($sth->execute) {
  print LOGFILE "errors: $dbh->errstr \n";
  print LOGFILE "\nErrors were encountered during string insertion, exiting...\n";
}
$dbh2 = $dbh->clone;
while (my $dbName = $sth->fetchrow) {
  my $sqlStatement2 = "select dbid from master..sysdatabases where name = '$dbName'";
  my $sth2 = $dbh2->prepare($sqlStatement2);
  unless ($sth2->execute) {
    print LOGFILE "errors: $dbh->errstr \n";
    print LOGFILE "\nErrors were encountered during string insertion, exiting...\n";
  }
  my $dbID = $sth2->fetchrow;
  print "Database ->ID: $dbID";
  $sth2->finish;
  print "\t->Name: $dbName\n";
}
$sth->finish;
exit;

###############################################################################
# Need to take care of Sybases sp_* "print" messages
sub err_handler {
  my($err, $sev, $state, $line, $server, $proc, $msg, $sql, $err_type) = @_;
  my @msg = ();
  if (($sev != 0) && ($sev != 10)) {
    if($err_type eq 'server') {
      push @msg, ('', 'Server message',
            sprintf('Message number: %ld, Severity %ld, State %ld, Line %ld', $err,$sev,$state,$line),
            (defined($server) ? "Server '$server' " : '') .
            (defined($proc) ? "Procedure '$proc'" : ''),
            "Message String:$msg");
    } else {
      push @msg, ('', 'Open Client Message:',
            sprintf('Message number: SEVERITY = (%ld) NUMBER = (%ld)', $sev, $err),
            "Message String: $msg");
    }
    print STDERR join("\n",@msg);
  }
  return 0; ## CS_SUCCEED
}
###############################################################################

