#!/usr/bin/perl

# AudioLink
#
# $Id: audiolink,v 1.4 2003/12/05 12:20:49 amitshah Exp $
#
# audiolink:
#
# Copyright (C) 2003, Amit Shah <amitshah@gmx.net>
#
# This file is part of AudioLink.
#
# AudioLink is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License, or
# (at your option) any later version.
#
# AudioLink is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with AudioLink; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


use DBI;
use Getopt::Long;
use Pod::Usage;

# Options for the database
$user = undef;
$password = undef;
$host = undef;


# ask_for_configfile_and_input: This function asks if the user wants
# to create a config file for the mandatory data she hasn't provided
# us with (user/passwd/host for the database).
#
# arg 1: String field of what's to be asked for.
#
# return: -1:     User doesn't want to create a config file now.
#         string: the string typed in by the user. Implies she wants a
#                  config file.

sub ask_for_configfile_and_input {

    if ( $_[0] =~ /user/ or $_[0] =~ /password/) {
	print STDERR "
    You haven't specified the " . $_[0] . " field for the database. The
    easiest way of doing this is by storing it in the AudioLink
    configuration file. Would you like to do that now?  [Yes/no] ";

	chomp($input = <STDIN>);

	unless ($input) {
	    $input = "yes";
	}

	unless ($input =~ /yes/i) {

	    print "\n\tQuitting now. See the audiolink(1) man page for
	more information on the mandatory input information needed,
	the config file and alternate ways of specifying the
	information.\n";

	    # This is bad... don't quit from a subroutine!
	    close CONFFILE;
	    exit -1;
	}
    }

    $input = "";

    while (not $input) {
	print STDERR "Please enter the " . $_[0] . " field for the database: ";

	$_[0] =~ /host/ ? print "[localhost]" : 1 ;

	chomp($input = <STDIN>);
	if (not $input and $_[0] =~ /host/) {
	    $input = "localhost";
	}
    }
    return $input;
}

GetOptions(
	   'help'      => \$help,
	   'user=s'    => \$user,
	   'pass=s'    => \$password,
	   'host=s'    => \$host,
	   'verbose'   => \$verbose
	   ) or pod2usage();

if ($help) {
    pod2usage();
}

# Currently, we'll do the database setting up and the config file
# setting up here.

$config_file = "$ENV{HOME}/.audiolink/config";

# First, detect if there's a config file in the home dir.
if (-e $config_file) {
    # If the config file already exists, open it in read-write mode;
    # don't clobber contents (+< as opposed to +>)
    open(CONFFILE, '+<', $config_file);
} else {
    # If it doesn't exist, open it in write mode.
    open (CONFFILE, '>', $config_file);
}

# go through the config file
while (<CONFFILE>) {
    if (/^\s*user\s*\=+\s*(\w+)/) {
	chomp($user = $1) unless $user;
    } elsif ( /^\s*pass(word)?\s*=\s*(\w+)/) {
	chomp($password = $2) unless $password;
    } elsif ( /^\s*host\s*=\s*(\w+)/) {
	chomp($host = $1) unless $host;
    }
}

unless ($user) {
    $user = ask_for_configfile_and_input("username");
    print CONFFILE 'user = ' . $user . "\n";
}
unless ($password) {
    $password = ask_for_configfile_and_input("password");
    print CONFFILE 'pass = ' . $password . "\n";
}
unless ($host) {
    $host = ask_for_configfile_and_input("host");
    print CONFFILE 'host = ' . $host . "\n";
}

# connect to the database.
$dbi_string = "DBI:mysql:aldb:$host"; # using MySQL

$dbh = DBI->connect($dbi_string,$user,$password, 
		    { PrintError => 0,
		      AutoCommit => 1} )
    or warn "\n$0: WARNING: Could not connect to the database!\
 !! This probably means that the AudioLink database is not initialized,
 !! the MySQL server you are trying to connect to is not available,
 !! or the username/password for authentication are not valid.

 !! If you don't see a success message below, something is wrong.\n";
# If
# !! you have already created the database tables, answer "no" below and
# !! start the MySQL server. If you're running it on your local machine,
# !! executing `/etc/init.d/mysql restart` as root would suffice.\n";

$input = "";

# while (not $input) {
#     print "\nShould I initialize the AudioLink database [Yes/no]? ";
#     chomp($input = <STDIN>);

#     unless ($input) {
# 	$input = "yes";
#     }
# }

if ($input =~ /no/i) {
    exit -2;
}

$db_name = "aldb";

print "\nCreating the AudioLink database..." if $verbose;

$ret = system("mysqladmin -u$user -p$password -h$host create  $db_name 2>/tmp/audiolink.db.tmp");

#    or print "\nSome error occured.
# If the error reported that the database already exists, it's okay. You already had the database created.
# If it was some other error, consult the mysqladmin man page and/or notify the AudioLink developers.\n
# Anyways, continuing to create AudioLink tables.\n";

open (DBOP, "/tmp/audiolink.db.tmp");
while (<DBOP>) {
    if ( /database exists/i) {
	print "The database already exists.\n" if $verbose;
    } else {
	die "\nSome error occured while creating the database:\n$_\n"
	    . "Ask for help on the audiolink-users\@lists.sourceforge.net mailing list.\n";
    }
}

close DBOP;

print "\nCreating the AudioLink tables..." if $verbose;

$ret = system ("mysql -u$user -p$password -h$host $db_name < /usr/share/doc/audiolink/mysql.schema 2>/tmp/audiolink.tb.tmp");
#    or print "\nSome error occured.
# If the error reported that the table already exists, it's okay. You already had the table created.
# If it was some other error, consult the mysql man page and/or notify the AudioLink developers.\n";

open (DBOP, "/tmp/audiolink.tb.tmp");

while (<DBOP>) {
    if ( /already exists/i) {
	print "The table already exists.\n" if $verbose;
    } else {
	die "\nSome error occured while creating the table:\n$_"
	    . "Ask for help on the audiolink-users\@lists.sourceforge.net mailing list.\n";
    }
}

$dbh->disconnect;

print "\nAudioLink is setup and ready to run. Take a look at the AudioLink documentation\n";
print "available via the three man pages: audiolink(1), alfilldb(1), alsearch(1)\n";
print "\nReport positive or negative feedback on the audiolink-users\@lists.sourceforge.net mailing list.\n";

exit 0;

=pod

=head1 NAME

audiolink - Create AudioLink config file, databases and tables

=begin later
audiolink - Music collection manager

--- when everything is integrated

=end later

=head1 SYNOPSIS

audiolink [I<OPTION>]...

=head1 DESCRIPTION

AudioLink is a set of programs which help you manage your music
collection. It makes searching for music on your local storage media
easier and faster. Your searches can include a variety of criteria,
like male artists, female artists, band, genre, etc.

It supports music files of MP3 and Ogg Vorbis formats.

B<audiolink> assists you in creating a configuration file for oft-used
options passed to the AudioLink programs and creating the MySQL
database and tables which the AudioLink programs, L<alfilldb(1)> and
L<alsearch(1)> use.

The options specified on the command prompt override the options
specified in the config file.

=head1 OPTIONS

=over

=item B<--help>

Brief usage information

=item B<--host>=I<xxx>

Connects to the MySQL server on the target host. Default is localhost.

=item B<--pass>=I<xxx>

Password for the database

=item B<--user>=I<xxx>

Username for the database

=item B<--verbose>

Display extra information about what's going on

=back

=head1 MORE INFORMATION

The user and password fields for the database have to be
specified. There are three ways of doing this:

=over

=item 1. Command-line arguments

By specifying them via the --user and --pass command-line arguments to
the programs:

C<alfilldb --user=mysql_username --pass=mysql_password --prompt=basic /songs/>

C<alsearch --user=mysql_username --pass=mysql_password --artist=kishore --td=/songs/kishore>


=item 2. Environment variables

Setting the DBI_USER and DBI_PASS environment variables:


If you are using bash, ksh, zsh or sh do this:


C<export DBI_USER=mysql_username>

C<export DBI_PASS=mysql_password>


If you are using csh or tcsh, do this:


C<setenv DBI_USER mysql_username>

C<setenv DBI_USER mysql_password>


Consult the man page of the respective shell interpreter that you
use for help on environment variables.

=item 3. Config file

Specifying them in the config file (the most convenient). The config
file is stored in each user's home directory in the
S<F<~/.audiolink/config>> location.

=back

=head1 CONFIGURATION FILE

The AudioLink configuration file F<config> resides in the
F<.audiolink/> directory in the user's home directory
(F<$HOME/.audiolink/config>).

The format of the current config file is pretty easy to understand:
Just put in C<a = b> on separate lines for all the options you want the
AudioLink scripts to use by default. Here, a is the option name, like
user, password, host, etc., and b is the value you wish to associate
the option with. For example, to set the username for accessing the
database to 'root', you would put this in the config file:

C<user = root>

=head1 SEE ALSO

=begin man

L<alfilldb(1)>, L<alsearch(1)>

=end man

=begin html

<em><a href="alfilldb_doc.html">alfilldb(1)</a></em>,
<em><a href="alsearch_doc.html">alsearch(1)</a></em>

=end html

The current version of this man page is available on the AudioLink
website at E<lt>http://audiolink.sourceforge.net/E<gt>.

=head1 BUGS

Report bugs related to the AudioLink software or the man pages to the
audiolink-devel mailing list E<lt>audiolink-devel@lists.sourceforge.netE<gt>.

=head1 AUTHOR

This manual page is written and maintained by Amit Shah E<lt>amitshah@gmx.netE<gt>

=head1 COPYRIGHT

The AudioLink package is Copyright (C) 2003, Amit Shah
E<lt>amitshah@gmx.netE<gt>. All the programs and the documentation that come
as part of AudioLink are licensed by the GNU General Public License v2
(GPLv2).

=cut
