#!/usr/bin/perl

# AudioLink
#
# $Id: alsearch,v 1.25 2003/12/05 12:32:39 amitshah Exp $
#
# alsearch: Implements the 2nd module of the AudioLink software. This
# script searches the database for the required artist/song/album/...
#
# 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 strict;

use Getopt::Long; # for parsing command-line arguments
use DBI;          # for mysql database connectivity
use Pod::Usage;   # for printing out the usage information

# Optional arguments: The default values of these arguments can be
# stored in some file (eg., ~/.audiolink/config)

my $target_dir_name = ""; # The directory in which symlinks are to be
			  # created


my $maintain_dir_structure = "1"; # Do we maintain the directory
				  # structure, or create symlinks in
				  # the same directory?

# Fields below represent the actual columns in the database.
# NOTE: Keep updating these as columns in the database are added.
my $album = "";
my $genre = "";
my $year = "";
my $title = "";
my $ma1 = "";
my $ma2 = "";
my $fa1 = "";
my $fa2 = "";
my $band = "";
my @artist;
my $composer = "";
my $lyricist = "";
my $file_path = "";
my $comment   = "";

# modifiers
my $no_act = 0;
my $help = 0;

# Options for the database
$user = undef;
$password = undef;
$host = "localhost"; # use local mysql server by default

# FIXME: Add support for selecting which field eventually becomes the
# file name of the link. Currently, it's the song name from the
# database. This also assumes that the database won't have the song
# name field empty. (The field 'song' is set to NOT NULL in the
# database, but it seems MySQL doesn't support it...)
sub do_search_and_action {
    my $statement;

    # Note:: Please maintain the 2nd and 3rd positions of the path and
    # song fields in the following $statement. These values are used
    # as array indices later in the program.
    if ($no_act) {
	$statement = qq(SELECT song_nr, path, song, album,
		       year, ma1, ma2, fa1, fa2,
		       composer, lyricist, band, genre,
		       track, comment
		       FROM aldb WHERE song_nr IS NOT NULL );
    } else {
	$statement = qq(SELECT song_nr, path, song
			   FROM aldb
			   WHERE song_nr IS NOT NULL );
    }

    # song_nr added to the search criteria just to make the code
    # cleaner. Look below and see what I mean.

    if ($year)     { $statement .= "AND year LIKE '%$year%' "; }
    if ($title)    { $statement .= "AND song LIKE '%$title%' "; }
    if ($album)    { $statement .= "AND album LIKE '%$album%' "; }
    if ($genre)    { $statement .= "AND genre LIKE '%$genre%' "; }
    if ($comment)  { $statement .= "AND comment LIKE '%$comment%' "; }
    if ($composer) { $statement .= "AND composer LIKE '%$composer%' "; }
    if ($lyricist) { $statement .= "AND lyricist LIKE '%$lyricist%' "; }

    my $perf; # Performer
    foreach $perf ($ma1, $ma2, $fa1, $fa2, $band) {
	if ($perf) {
	    $statement .= qq(AND (ma1 LIKE '%$perf%' OR ma2 LIKE '%$perf%'
				  OR fa1 LIKE '%$perf%' OR fa2 LIKE '%$perf%' 
				  OR band LIKE '%$perf%') );
	}
    }

    my $sth = $dbh->prepare($statement);
    $sth->execute or die "$0: Error: Can't execute search query\n";

    my $nr_cols = $sth->{NUM_OF_FIELDS}; # number of columns
    my $nr_rows = $sth->rows; # number of rows.


    while ($nr_rows) {
	my @row = $sth->fetchrow_array;

	if ($no_act) {
	    my @temp = @row;
	    for(my $i = 0; $i < $nr_cols; $i++) {
		print "$temp[1], ";
		shift @temp;
	    }
	    print "\n";
	}

	if ($target_dir_name) {
	    symlink $row[1], $row[2]
		or print "couldn't create symlink for file $row[2]\n";
	}
	$nr_rows--;
    }
    
}

# execution starts here

# check for command-line arguments
if (not @ARGV) {
    pod2usage();
}


GetOptions(
	   'help'            => \$help,
	   'v|verbose'       => \$verbose,
	   'na|s'            => \$no_act,
	   'td=s'            => \$target_dir_name,
	   'ds=i'            => \$maintain_dir_structure,
	   'user=s'          => \$user,
	   'pass=s'          => \$password,
	   'host=s'          => \$host,
	   'user=s'          => \$user,
	   'album=s'         => \$album,
	   'year=i'          => \$year,
	   'title=s'         => \$title,
	   'ma1|ma=s'        => \$ma1,
	   'ma2=s'           => \$ma2,
	   'fa1|fa=s'        => \$fa1,
	   'fa2=s'           => \$fa2,
	   'band|b|artist=s' => \@artist,
	   'c|composer=s'    => \$composer,
	   'l|lyricist=s'    => \$lyricist,
	   'genre=s'         => \$genre,
	   'comment=s'       => \$comment
	   ) or pod2usage();

if ($help) {
    pod2usage();
}

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

if (-e $config_file) {
    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;
	}
    }
} else {
    warn "WARNING: config file not found. Use the audiolink script to create one.\n";
}

my $i = 0;

$band = $artist[$i++];
unless ($ma1) {$ma1 = $artist[$i++];}
unless ($ma2) {$ma2 = $artist[$i++];}
unless ($fa1) {$fa1 = $artist[$i++];}
unless ($fa2) {$fa2 = $artist[$i++];}

if ($verbose) {
    print "The search criteria are:\n";
    if ($year)     { print "Year: $year\n"; }
    if ($title)    { print "Title: $title\n"; }
    if ($album)    { print "Album: $album\n"; }
    if ($genre)    { print "Genre: $genre\n"; }
    if ($band)     { print "Artist 1: $band\n"; }
    if ($ma1)      { print "Artist 2: $ma1\n"; }
    if ($ma2)      { print "Artist 3: $ma2\n"; }
    if ($fa1)      { print "Artist 4: $fa1\n"; }
    if ($fa2)      { print "Artist 5: $fa2\n"; }
    if ($composer) { print "Composer: $composer\n"; }
    if ($lyricist) { print "Lyricist: $lyricist\n"; }
    if ($comment)  { print "Comment: $comment\n"; }

    print"\nOther options set are:\n";
    if ($target_dir_name) { print "Target directory: $target_dir_name\n"; }
    if ($maintain_dir_structure) { 
	print "Maintaining directory structure (default) \n";
    } else { print "Creating all links in the target directory\n"; }
}

$dbi_string = "DBI:mysql:aldb:$host"; # using MySQL

# connect to the database.
$dbh = DBI->connect($dbi_string,$user,$password) 
    or die "$0: Error: Could not connect to the database! \
 Check the user, password and host fields for the MySQL connection.";

if ($target_dir_name) {
    unless (-d $target_dir_name)  {
	mkdir $target_dir_name or 
	    die "\n$0: Error: can't create directory $target_dir_name\n";
    }
    chdir $target_dir_name or die "can't chdir to $target_dir_name\n";
} else {
    unless ($no_act) {
	die "\n$0: Error: You need to specify a target directory with this option\n";
    }
}

do_search_and_action();

=pod

=head1 NAME

alsearch - Search the AudioLink database for music

=head1 SYNOPSIS

B<alsearch> [I<OPTION>]... I<search_option>... I<--td=/some/path/to/create/links/>

B<alsearch> [I<OPTION>]... I<search_option>... I<-s>

=head1 DESCRIPTION

You can use this script to search for songs in the AudioLink
database. You can specify one or several options for the artist,
composer, lyricist, album, etc., as the search criteria.

You can specify several I<search_option> options to search for
particular music files. See the section on L<"search options"> for the
list of options.

The search is not case sensitive. B<alsearch> looks for strings as
well as sub-strings in the fields being searched. See the
L<"examples"> section for more information.

Specifying the B<--td> (target directory) option is mandatory for
creating links to the actual files. This directory will contain the
symbolic links to the actual audio files. The directory will be
created if it doesn't exist.

Creating symbolic links to the actual files is analogous to creating
playlists in audio-playing software. Symbolic links are actually just
point to the actual files on the hard disk. This way of creating and
storing playlists is very useful in several ways, some of which are:

=over

=item 1. Compatible across various audio players

Since the "playlists" are actually files represented on your hard
disk, you can add whole directories generated by the B<alsearch>
program in the playlist of your audio software. If you switch to
another music player for whatever reason, you still have your
playlists. You don't have to bother about compatibility between the
playlist formats of the two players.

=item 2. Can be seen and operated upon in a file browser

As the symbolic links are present on a file-system, your playlist
collection can be viewed by using normal file operations in the shell
or using a GUI-based file browsing program. If the file browsing
program is supports file traversals and symlinks, it'll show you the
information of the actual song.

=back

=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<-s>, B<--na>

Just displays the search results, doesn't create links (simulation
mode)

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

Target-directory in which to create links

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

Username for the database

=item B<-v>, --verbose

Displays some extra information. Useful for spotting errors and
sending debug information.

=back

=head1 SEARCH OPTIONS

=over

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

Search in the "album" field

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

Search in the artist/band/performers fields. You can give this option
multiple times, for example:

C<alsearch --artist=kishore --artist=asha --td=/songs/asha_kishore>

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

Search in the "comment" field

=item B<-c>, B<--composer>=I<xxx>

Search in the "composer" field

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

Search in the "genre" field

=item B<-l>, B<--lyricist>=I<xxx>

Search in the "lyricist" field

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

Search in the "title" field

=back

=head1 EXAMPLES

The options that take arguments can be specified in two ways:

C<alsearch --artist="kishore kumar" --td=/songs/kishore>

C<alsearch --artist "kishore kumar" --td /songs/kishore>

That is, the option and the argument can be separated with a 'I< >'
(space) or an 'I<=>' (equal) sign.

In case you want to search for a string that has spaces, enclose the
string in " ".

C<alsearch --artist=kishore --composer=burman --lyricist=bakshi>

Will search for songs sung by *Kishore*, composed by *Burman* and
written by *Bakshi*. Any name in the composer field which have
"burman" in them will be matched. This means, it'll find songs
composed by RD Burman, SD Burman, etc. This is true for all search
fields.

=head1 SEE ALSO

=begin man

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

=end man

=begin html

<em><a href="audiolink_doc.html">audiolink(1)</a></em>,
<em><a href="alfilldb_doc.html">alfilldb(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
