#!/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 $opt_w/;
getopts('a:d:u:h:p: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);
} 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;
my $user = $opt_w;

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

my $dsn = "DBI:mysql:database=mysql";
my $clienthost = 'localhost';

if ($host eq "") {
    $host = 'localhost';
} elsif ($host ne 'localhost') {
    $dsn .= ";host=$host";

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

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

	# Determine client host for database user
	$clienthost = `hostname -f`;
	chomp($clienthost);
}

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

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

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

if ($@) {
	die "$0: failed to create database $database: $@\n";
	exit 1;
}

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

if ($@) {
	die "$0: failed to create $database user $user: $@\n";
	exit 1;
}

$dbh->disconnect();

exit 0;

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

