#!/usr/bin/perl
#
# check-pg-version
#   get current postgres version and return it
#
# Copyright 1999 -- 2001, onShore Development Inc. <URL:http://www.onshore-devel.com/>
#
#
# This program is free software under the terms of the GNU General Public
# License (GPL). A copy of the GPL, "COPYING", should have been made
# available with this software.  If not, a copy may be obtained at 
# http://www.fsf.org/copyleft/gpl.html
#
# $Id: check-pg-version,v 1.4 2001/08/29 22:22:59 adam Exp $
#
$|=1; 
use Getopt::Long; 

&GetOptions( "sql_interpreter=s" => \$sql_interpreter,
	      "dbname=s" =>  \$dbname, 
             "v7" => \$check_for_v7,
             );

if ( ! $sql_interpreter ) {
    $sql_interpreter = "psql";  # default
}

if ( ! $dbname ) {
    $dbname = "template1";  # default
}

@sql_interp_list = ( $sql_interpreter, '-d', $dbname, '-t', '-q' );

# the version() function was added in 6.4
open(DB_SHELL, 
     join(" ", @sql_interp_list, '-c', "\"select version()\"")
     . "|")
    or die "ERROR: '$sql_interpreter' exited with error\n";

local $SIG{PIPE} = sub { die "ERROR: '$sql_interpreter' pipe broke\n" };

$_ = <DB_SHELL>;
close DB_SHELL
    or exit(10);
    
if ( /^\s*$/m ) {
    warn "WARNING: obsolete version of postgresql installed, get 6.4 or better\n";    
    $version = "6.3 or older";
    $exitval = 5;
} else {
    chomp($version = $_);
    $version =~ s/^[^0-9]*([0-9.]*).*$/$1/;
    $exitval = 0;
    
    # with this switch, this script is just returning 0 for v7, non-0 otherwise
    if ( $check_for_v7 and $version !~ m/^7/ ) {
        $exitval = 1;
    }
}


print "$version\n";
exit($exitval);



