#!/usr/bin/perl -w

# PostgreSQL database initialisation script
# Copyright 2000, 2001, 2002 Jrme Marant <jerome@debian.org>
# Copyright 2003, 2004, 2005 Stefan Hornburg (Racke) <racke@linuxia.de>

use strict;
use warnings;

use Getopt::Std;
use DBI;

use vars qw/$opt_a $opt_d $opt_u $opt_h $opt_i $opt_p $opt_o $opt_w/;
getopts('a:d:u:h:ip:o:w:') or die "$0: $@\n";

my ($adminpass, $userpass);

if ($opt_a && -f $opt_a) {
	open(PWD, $opt_a) || die "$0: Couldn't open file $opt_a: $!\n";
	chomp($adminpass = <PWD>);
	close(PWD);
}

if ($opt_u && -f $opt_u) {
	open(PWD, $opt_u) || die "$0: Couldn't open file $opt_u: $!\n";
	chomp($userpass = <PWD>);
	close(PWD);
}

my $database = $opt_d;
my $host = $opt_h || 'localhost';
my $port = $opt_p;
my $options = $opt_o;
my $user = $opt_w;

# Now we switch to user "postgres" if necessary
if ($opt_i) {
	my $uid = (getpwnam('postgres'))[2];
	unless ($uid) {
		die "Failed to determine UID for postgres user\n";
	}
	$> = $uid;
}

my $dsn = "DBI:Pg:dbname=template1";

# Set the hostname
if ($host ne 'localhost') {
    $dsn .= ";host=$host";
	
    # Set the port in case of a TCP connection.
    if ($port eq '') {
	$port = "5432";
    }

    $dsn .= ";port=$port";
}

if (defined $options && $options =~ /\S/) {
    $dsn .= ";$options";
}

# Connect to template1
my $dbh;

if ($opt_i) {
	$dbh = DBI->connect($dsn,
						"postgres", '',
						{'RaiseError' => 1});
} else {
	$dbh = DBI->connect($dsn,
						"postgres", $adminpass,
						{'RaiseError' => 1});
}

# Create database
eval {$dbh->do("CREATE DATABASE $database")};

if ($@) {
	warn "Failed to create database $database: $@\n";
	exit 1;
}

# Create user sympa
#$dbh->do("DELETE FROM pg_shadow WHERE usename='sympa'");

eval {$dbh->do("CREATE USER $user with password '".$userpass."' nocreateuser nocreatedb");};

if ($@) {
	warn "Failed to create user $user: $@\n";
	exit 1;
}

$dbh->disconnect();

