#!/usr/bin/perl

use DBI;
use DBD::mysql;
use File::Path;
use Config::INI::Reader;

my $confcontents = Config::INI::Reader->read_file('/etc/homeaudio.ini');
my $Config = $confcontents->{_};

$dsn = "DBI:mysql:" . $Config->{DBNAME} . ":" . $Config->{DBHOST};
$dbh = DBI->connect($dsn, $Config->{DBUSER}, $Config->{DBPASS}, {RaiseError=>1});

$mp3dir = $Config->{MP3DIR};
$alphabetdir = $mp3dir . "Alphabetical/";

# Remove all of the soft links in the Alphabetical folder
opendir(DIR, $alphabetdir);
@alphadirs = grep { !/^\./ } readdir(DIR);
closedir DIR;
foreach $dir (@alphadirs) {
   rmtree($alphabetdir . $dir);
}

# Parse the "albums" based on path from the DB
$sth = $dbh->prepare("SELECT SUBSTRING(path, LENGTH(genre)+2, LENGTH(path)-LENGTH(genre)-2) AS albumdir, genre FROM songs WHERE genre NOT IN (SELECT genre FROM excludes) AND path <> CONCAT(genre, '/') GROUP BY albumdir ORDER BY albumdir");
$sth->execute();

# Let's walk through the album list returned from the DB
while ( @row = $sth->fetchrow_array() ) {
   $album = $row[0];
   $firstchar = substr($album, 0, 1);
   $genre = $row[1];
   $currentpath = $alphabetdir . $firstchar . "/";
   $target = "../../" . $genre . "/" . $album;
   unless ( -e $currentpath ) {
      mkdir $currentpath;
   }
   $newfile = $currentpath . $album;
   symlink($target, $newfile);
}

$sth->finish();
# Close the DB connection
$dbh->disconnect();