#!/usr/bin/perl -w

# MySQL database initialisation script
# Copyright 2000, 2001, 2002 Jrme Marant <jerome@debian.org>
# Copyright 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_p $opt_o/;
getopts('a:d:u:h:p:o:') 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);
} else {
	$adminpass = '';
}

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

my $database = $opt_d;
my $host = $opt_h;
my $port = $opt_p;
my $options = $opt_o;

usage() if ($database eq "");

my $dsn = "DBI:mysql:database=mysql";

if ($host eq "") {
    $host = 'localhost';
}

# Set the hostname
if ($host ne 'localhost') {
    $dsn .= ";host=$host";

    # Set the port in case of a TCP connection.
    if ($port eq '') {
	$port = "3306";
    }

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

if ($options ne "") {
    $dsn .= ";$options";
}

my $clienthost = `hostname -f`;
chomp($clienthost);

# Connect to mysql
my $dbh = DBI->connect($dsn,
		       "root", $adminpass,
		       {'RaiseError' => 1});

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

if ($@) {
	exit 1;
}

# Create user sympa
my $command="GRANT ALL on $database.* TO sympa\@$host";
if ($userpass ne "") {
    $command .= " IDENTIFIED BY '$userpass'";
}
$dbh->do($command);
$dbh->disconnect();

sub usage {
    die "Usage: install-mysql-db.pl -d <database> [-a <adminpass>] [-u <userpass>] [-h <hostname>] [-p <port>]\n";
}

