#!/usr/bin/perl
#
#  perl script for automatic mp3 location and web page generation
#
#  current configfile commands:
#  ---------------------------
#  mp3_info_dir "directory"   =   the directory to serve out of
#  ignoredir "regexp"         =   directory to ignore when catalogging mp3s
#  lookatdir "directory"      =   directory to look at specifically (mp3s not in locate db)
#
use strict;
use File::Basename;

my $version    = "0.02";
my $configfile = ".mpservrc";

my $host = `hostname -s`;
chomp $host;

my $domain = `hostname -d`;
chomp $domain;

my $fqdn = "$host.$domain";

# -------------------------
# begin config file reading
my $conf = &read_conf;
die("No mp3_info_dir specified in config file!\n") unless (defined $$conf{mp3_info_dir}[0]);
# end config file reading
# -----------------------

open MP3, ">$$conf{mp3_info_dir}[0]/index.html";
open TEXT, ">$$conf{mp3_info_dir}[0]/index";

# grab all the .mp3 files out of the locate database
my @files = `locate .mp3`;
# grab all the files in user specified directories
my (@dirfilelist,$dirfile);
for (my $i = 0; $i <= $#{@{$$conf{lookatdir}}}; $i++) {
  @dirfilelist = `ls -1 $conf->{lookatdir}[$i]/*.mp3`;
  foreach $dirfile (@dirfilelist) {
    print "Adding file $dirfile";
    push @files, "$dirfile";
  }
}

my (%index,$ignorefile);
while(@files) {
  $_ = shift @files;
  chomp($_);
  
  my $dir = dirname($_);
  next if ($dir =~ m|$$conf{mp3_info_dir}[0]|);  # skip the mp3_dir_info files!!!
  
  $ignorefile = 0;
  for (my $i = 0; $ignorefile == 0 && $i <= $#{@{$$conf{ignoredir}}}; $i++) {
    $ignorefile++ if ($dir =~ m|$conf->{ignoredir}[$i]|);
  }
  if ($ignorefile != 0) {
    print "Ignoring file in $dir\n";
    next;
  }

  my $base = basename($_);
  my $name = $base;
  $base =~ s/ /_/g;
  symlink $_, $$conf{mp3_info_dir}[0].'/'.$base;
  $base =~ s/.mp3//;
  $name =~ s/.mp3//;
  open MPS, ">$$conf{mp3_info_dir}[0]/$base.mps";
  $index{$name} = "<a href=\"http://$fqdn/mp3/$base.mps\">$name</a><br>\n";
  print TEXT "http://$fqdn/mp3/$base.mp3\t$name\n";
  print MPS "http://$fqdn/mp3/$base.mp3";
  close MPS;
}

close TEXT;

print MP3 "<html><head><title>MP3 List</title></head>\n";
print MP3 "<body bgcolor=\"#000000\" text=\"\#FFFFFF\" link=\"\#D0D0FF\" vlink=\"\#A060A0\">\n";
# this prints an alphabetical list by name
foreach (sort keys %index) {
  print MP3 $index{$_};
}
print MP3 "</body></html>\n";

close FILES;
close MP3;


sub read_conf {
  my (@line,%conf);
  open(CONFIG,"$ENV{HOME}/$configfile") 
    or die("\nCouldn't open configuration file \"$ENV{HOME}/$configfile\"!\n");
  while (<CONFIG>) {
    next if /^\#/;
    next if /^\s+$/;
    chomp;
    @line = split /=/;
    push @{$conf{$line[0]}}, $line[1];
    print "conf{$line[0]} --> $line[1]\n";
  }
  return(\%conf);
}
