#!/usr/bin/perl -w
#-------------------------------------------------------------------------------
# playsongs.pl - this lists the contents of a folder of songs as clickable links
# written by Eric Pence
#-------------------------------------------------------------------------------
use strict;
use CGI qw(-oldstyle_urls :standard);
use CGI::Carp qw(fatalsToBrowser);
use IO::File;
use Data::Dumper;

# Define global variables
use vars qw($curr_dir $log_file);

#-------------------------------------------------------------------------------
# Grab the current directory from $0. The following regular expression
# looks for 'CURR_DIR\xxxxx.xxx' or 'CURR_DIR/xxxxx.xxx'. Place it in
# the BEGIN block so we can use it to include modules
#-------------------------------------------------------------------------------
BEGIN {
  $0 =~ '(.*[\\\/])\w+\.\w+$';
  $curr_dir = $1 || "./";

  # Set up error log file
  $log_file = "error_log.txt";
  use CGI::Carp qw(carpout);
  open(LOG, ">>${curr_dir}${log_file}")
        or die "Unable to append to error log: $!";
  carpout(*LOG);
}

use lib ( $curr_dir );
use FileHandle;

$| = 1; # Disable buffering

my $count = 0;
my $files = '';

# Get the list of the songs to display
my @dir_contents = '';
my $ipod_dir = $curr_dir."../../ipod";
opendir(DIR,$ipod_dir) || die("Cannot open directory $ipod_dir!\n");
@dir_contents = sort readdir(DIR);
closedir(DIR);

# Format the songs as clickable links
foreach my $filename (@dir_contents) {
  if (lc($filename) =~ /\.mp3/) {
    # Create name without file extension
    my $shortname = $filename;
    $shortname =~ s/\.mp3//;
    $shortname =~ s/\.MP3//;
    my $m3u_file = "../../ipod/$shortname"."\.m3u";
    if (!(-e $m3u_file)) {
      # Create M3U file for streaming if it doesn't exist
      open( M3U_FILE, ">$m3u_file" ) || die "Can't open m3u file: '$m3u_file'";
     my $no_space_name = replace_spaces($filename);
      print M3U_FILE "http://www.penceland.com/ipod/$no_space_name";
      close M3U_FILE;
    }
    my $display_name = $shortname;
    # Replace certain characters with entities on display
    $display_name =~ s/&/&/g;
    $display_name =~ s/\//⁄/g;
    # Get the file size
    my $audio_file = "../../ipod/$filename";
    my @stats = stat($audio_file);
    my $filesize = int($stats[7]/1000).'kb';
    $m3u_file = replace_spaces($m3u_file);
    $audio_file = replace_spaces($audio_file);
    $files = "$files
        &nbsp; &nbsp; <img align=\"absmiddle\" src=\"../../images/wbullet.gif\" title=\"o\" width=\"15\" height=\"15\">
        <span title=\"$display_name\"><a href=\"$m3u_file\">$display_name</a> \/ <a href=\"$audio_file\">mp3</a></span> <font color=\"#555555\">($filesize)</font>
        <br><img src=\"../../images/clearspacer.gif\" height=\"4\"><br>";
    $count++;
  }
}

print header();
print "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">
<html>
<head>
<link href=\"../../penceland.css\" rel=\"stylesheet\" type=\"text/css\">
</head>
<body background=\"../../images/myback.gif\">
<p>
<table>
  <tr>
    <td width=\"30\">&nbsp;</td>
    <td valign=\"top\"><img src=\"../../images/dot.gif\" width=\"4\" height=\"10\" title=\"o\" hspace=\"2\"></td>
    <td valign=\"top\" nowrap><a href=\"JavaScript:void(0)\"><font color=\"#333399\">Song Title</font></a></td>
    <td valign=\"top\" width=\"10\" align=\"center\">&ndash;</td>
    <td valign=\"top\">
      Click on the song title to <span title=\"Stream an audio file\"><a href=\"../../music.html#streamaudio\" class=\"green\">stream</a></span> the song (play it as it downloads).
    </td>
    <td width=\"10\">&nbsp;</td>
</tr>
  <tr>
    <td width=\"30\">&nbsp;</td>
    <td valign=\"top\"><img src=\"../../images/dot.gif\" width=\"4\" height=\"10\" title=\"o\" hspace=\"2\"></td>
    <td valign=\"top\"><a href=\"JavaScript:void(0)\"><font color=\"#333399\">mp3</font></a></td>
    <td valign=\"top\" width=\"10\" align=\"center\">&ndash;</td>
    <td valign=\"top\">
      This is a direct link to the audio file (size is shown).
      To copy a file <i>right</i> click on this link and choose <i>Save&nbsp;Link/Target&nbsp;As...</i>.
    </td>
    <td width=\"10\">&nbsp;</td>
</tr>
</table>
<img src=\"../../images/clearspacer.gif\" height=\"8\"><br>

$files
  
<img src=\"../../images/clearspacer.gif\" height=\"8\"><br>
&nbsp; &nbsp;$count songs
<p>

</body>
</html>";

# Format access data
my $remote_addr = $ENV{'REMOTE_ADDR'} || '';
# Filter out my computers
if (($remote_addr !~ /^38\.97\.67\./) && ($remote_addr !~ /^24\.147\.129\./)) {
  my $access_file = "access_log.txt";
  open(ACCESS_FILE, ">>$access_file") || die "Can't open '$access_file'";
  my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
  $year = $year + 1900;
  if ($min < 10) {$min = "0".$min;}
  $mon++;
  my $timeData = "$mon/$mday/$year - $hour:$min";
  print ACCESS_FILE "playsongs.pl: $timeData - $remote_addr\n";
  close(ACCESS_FILE);
}

#-------------------------------------------------------------------------------
# replace_spaces() - replaces spaces with %20 for URI compliance
#-------------------------------------------------------------------------------
sub replace_spaces {
my ($str) = @_;
  $str =~ s/\s/%20/g;
  return $str;
}