#!/usr/bin/perl


# Copyright 2005 Aaron Wolfe, Jacint Balint
#
#    This file is part of tunequeue.
#
#    tunequeue 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; either version 2 of the License, or
#    (at your option) any later version.
#
#    tunequeue 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 tunequeue; if not, write to the Free Software      
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA


use CGI qw(:standard);
use DBI;
use Ogg::Vorbis::Header;

require "setup.pl";

my $dbh = DBI->connect($config{'DB_STRING'},$config{'DB_USER'},$config{'DB_PASS'});

$CGI::DISABLE_UPLOADS = 1;
$CGI::POST_MAX        = 102_400; # 100 KB

my $q = new CGI;

my $auser = $q->param( 'user' );
my $apass = $q->param( 'pass' );
my $action = $q->param( 'action' );
my $subaction = $q->param( 'sub' );
my $qdtid = $q->param( 'qdtid' );
my $mmsg = $q->param( 'mmsg' );

my %cookie_val = $q->cookie(-name => 'iruleyou');

$admin = 0;

# `echo 1 > /var/log/apache2/junk`;

if ($cookie_val{'admin'} == 1)
{
 $admin = 1;
 $user = $cookie_val{'user'};
 print $q->header("text/html");

 #load up some shit for later
 $sql = "SELECT ID,name,incomingpath,defaultplaylist FROM channels WHERE admin = ?";
 $out = $dbh->prepare($sql);
 $out->execute($user);
 
 ($channel,$channelname,$incomingpath,$defaultplaylist)=$out->fetchrow_array;
}
elsif ($auser ne "")
{
#log the bitch in
 $sql = "SELECT password FROM channels WHERE admin = ?";
 $out = $dbh->prepare($sql);
 $out->execute($auser);

 if (my($tpass)=$out->fetchrow_array)
 {
  if ($tpass eq $apass)
  {
   $admin = 1;
   $user = $auser;
   #set cookie

   %cookie_val = ();
   $cookie_val{ 'admin' } = 1;
   $cookie_val{ 'user' } = $auser;

   my $cookie = $q->cookie (
                -name    => 'iruleyou',
                -value   => \%cookie_val,
                -path    => '/',
                -expires => '+24h'
   );

   print $q->header(-cookie => [$cookie]);
  }
  else
  { 
   print $q->header("text/html");
  }
 }
}
else
{
 print $q->header("text/html");
}

print "<HTML><HEAD>";
print "<TITLE>SPOGBIPER - Administration</TITLE>";

print "<LINK HREF=\"/admin.css\" rel=\"stylesheet\" type=\"text/css\">";

print "</HEAD><BODY BGCOLOR=#004466 ALINK=#FFFFFF LINK=#FFFFFF VLINK=#FFFFFF>";

print "<IMG SRC=/spogbiper.gif>";
print "<h2><A HREF=/cgi-bin/admin.pl>[Main menu]</A> &nbsp;&nbsp;Channel: $channelname</h2><P>";

if ($admin)
{
 # LOGGED IN...
 if ($action ne "")
 {
  if ($action eq "import")
  {
   if ($subaction ne "")
   {
    if ($subaction eq "ls")
    {
     #directory

     print "Files in $incomingpath<P>";

     @ls = `ls -1 $incomingpath`;
 
     print "<TABLE CELLPADDING=3>";

     print "<TR><TD><B>Filename</TD><TD><B>Artist</TD><TD><B>Title</TD><TD><B>Album</TD><TD><B>Length</TD></TR>";

     foreach $f (@ls)
     {
      chomp($f);
  
      print "<TR><TD>$f</TD>";
      $fn = $incomingpath . "/" . $f;

      $artist = "Unknown";
      $album = "Unknown";
      $time = "Unknown";
      $title = "Unknown";


      if (substr($f,-3) eq "ogg")
      {
       $ogg = Ogg::Vorbis::Header->new($fn);

       ($artist) =  $ogg->comment("artist");
       ($album) = $ogg->comment("album");
       ($title) = $ogg->comment("title");

       ($time) = $ogg->info("length");
      }

      print "<TD>$artist</TD><TD>$title</TD><TD>$album</TD><TD>$time</TD></TR>";

     }    
     print "</TABLE>";
    }
    elsif ($subaction eq "convert")
    {
     print "<H2>Converting...wait a while</H2><P>";
     @ls = `ls -1 $incomingpath/*.mp3`;
     foreach $f (@ls)
     {
      chomp($f);
      $o = `cd $incomingpath;mp32ogg --delete "$f"`;
      print "$o<P>";
     }	
     print "<h2>DONE</h2>";
    }
    elsif ($subaction eq "import")
    {
     print "<H2>Importing oggs...into default playlist with random play turned on, thats what you get for now.</H2><P>";

     @ls = `cd $incomingpath;ls -1 *.ogg`;
     foreach $f (@ls)
     {
      chomp($f);     

      $fn = $incomingpath . "/" . $f;

      $ogg = Ogg::Vorbis::Header->new($fn);

      my ($artist) =  $ogg->comment("artist");
      my ($album) = $ogg->comment("album");
      my ($title) = $ogg->comment("title");

      my ($time) = $ogg->info("length");

      unless (defined $artist) { ($artist)= $ogg->comment("ARTIST"); }
      unless (defined $album) { ($album)= $ogg->comment("ALBUM"); }
      unless (defined $title) { ($title)= $ogg->comment("TITLE"); }

      unless (defined $artist) { $artist="Unknown"; }
      unless (defined $album) { $album="Unknown"; }
      unless (defined $title) { $title="Unknown"; }

      $realfn = "/usr/local/tunes/" . $f;
   
      $qry2 = "SELECT ID FROM tunes WHERE (artist = ?) and (album = ?) and (title = ?)";
      $out2 = $dbh->prepare($qry2);
      $out2->execute($artist,$album,$title);
  
      if (my($ass,$ass2,$ass3)=$out2->fetchrow_array)
      {
       print "<B>DUP: $title by $artist ($album)</B><BR>";
      }
      else
      { 
       ##tunes insert
       $qry2 = "INSERT INTO tunes (filename,added,artist,album,title,time)
          VALUES (?,NOW(),?,?,?,?)";

       $out2 = $dbh->prepare($qry2);
       $out2->execute($realfn,$artist,$album,$title,$time);

       $qry2 = "SELECT ID from tunes WHERE (filename = ?)";
       $out2 = $dbh->prepare($qry2);
       $out2->execute($realfn);

       ##channel insert
       if (my($tuneid)=$out2->fetchrow_array)
       {
        $qry2 = "INSERT INTO channeltunes (tuneid,channelid,added,randomplay)
          VALUES (?,?,NOW(),?)";

        my $out2 = $dbh->prepare($qry2);
        $out2->execute($tuneid,$channel,1);
       `mv "$fn" "/usr/local/tunes/$f"`;

       }
   
print "added $l [\"$title\" by $artist ($album) $time]\n   chan:$channel<BR>";
      }
     }
    }
   }
   else
   {
    #import menu 
    print "<A HREF=/cgi-bin/admin.pl?action=import&sub=ls>Show incoming directory</A><P>";
    print "<A HREF=/cgi-bin/admin.pl?action=import&sub=convert>Convert mp3s to ogg</A><P>";
    print "<A HREF=/cgi-bin/admin.pl?action=import&sub=import>Import ogg files to channel tunes</A><P>";

   }

  
  }
  elsif ($action eq "manageshows")
  {
   if ($subaction ne "")
   {
    if ($subaction eq "list")
    {
     print "<B>Show Schedule<P>";
  
     $qry2 = "SELECT showname,showdesc,showstart,showend,scheduletype,enabled
              FROM shows WHERE (channelid = ?) ORDER BY showstart";
     $out2 = $dbh->prepare($qry2);
     $out2->execute($channel);

     print "<TABLE><TR><TD><B>Show Name</TD><TD><B>Description</TD><TD><B>Start</TD><TD><B>End</TD><TD><B>Type</TD><TD><b>Enabled</TD></TR>";

     while (my($showname,$showdesc,$showstart,$showend,$scheduletype,$enabled)=$out2->fetchrow_array)
     {
      print "<TR><TD>$showname</TD><TD>$showdesc</TD><TD>$showstart</TD><TD>$showend</TD><TD>$scheduletype</TD><TD>$enabled</TD></TR>";
     }
    print "</TABLE>";
  
    }
   }
   else
   {
    # manage shows menu
    print "<A HREF=/cgi-bin/admin.pl?action=manageshows&sub=list>List show schedule</A><P>";
#    print "<A HREF=/cgi-bin/admin.pl?action=manageshows&sub=list>List show schedule</A><P>"; 
   }
  }
  elsif ($action eq "managequeue")
  {
   if ($subaction eq "remove")
   {
    $qry = "UPDATE channeltunes SET lastplayed = NOW(), cancels = cancels + 1 
           WHERE (tuneid = ?) AND (channelid = ?)";
    $out = $dbh->prepare($qry);
    $out->execute($qdtid,$channel);
    print "<H3>\"Played\" tune $qdtid in channel $channel</H3>";
   }

   print "<P><B>Coming up:<P>";

   $qry2 = "SELECT tunes.id,tunes.artist,tunes.title,tunes.album,schedule.request,schedule.showid,schedule.seq,tunes.filename,channeltunes.lastplayed
            FROM tunes,schedule,channeltunes
            WHERE (tunes.id = schedule.TuneID) AND (tunes.id = channeltunes.tuneid)
            AND (schedule.channelid = ?) AND (channeltunes.channelid = ?)
            ORDER BY schedule.added";
   $out2 = $dbh->prepare($qry2);
   $out2->execute($channel,$channel);

   print "<TABLE><TR><TD><B>ID</TD><TD><B>Artist</TD><TD><B>Song</TD><TD><B>Album</TD>";
   print "<TD><B>Filename</TD><TD><B>Last Played</TD><TD><B>Req/Show/Seq</TD></TR>";

   while (my($tid,$artist,$title,$album,$request,$showid,$seq,$filename,$lastplayed)=$out2->fetchrow_array)
   {
    
    $filename =~ s/\/usr\/local\/tunes\///;
    print "<TR><TD>$tid</TD><TD>$artist</TD><TD>$title</TD><TD>$album</TD>";
    print "<TD>$filename</TD><TD>$lastplayed</TD><TD><CENTER>$request / $showid / $seq</TD></TR>";
   }
   print "</TABLE>";

   print "<P><B>Songs eligible to be added next:<P>";

   @sched = `/usr/local/tunequeue/scheduletunes.pl $channel`;

   foreach $line (@sched)
   {
    print $line;
   }
 
  
  }
  elsif ($action eq "managecovers")
  {

   print "<B>Albums with no cover art:</B><P>";

   $qry = "SELECT DISTINCTROW tunes.artist,tunes.album
        FROM tunes,channeltunes WHERE (tunes.ID = channeltunes.tuneid) and (channeltunes.channelid = $channel)
        ORDER BY artist,title";

   my $out = $dbh->prepare($qry);

   $out->execute;

   while (my($artist,$album)=$out->fetchrow_array)
   {

    $filename =~ s/\|/'/g;
    $artist =~ s/\|/'/g;
    $album =~ s/\|/'/g;
    $title =~ s/\|/'/g;

    unless ((-e "/var/www/www.spogbiper.com/coverart/$artist - $album.jpg") or (-e "/var/www/www.spogbiper.com/coverart/$album.jpg")) {  print "$artist - $album<br>"; }
   }
  }
  elsif ($action eq "meta")
  {
   @oms = qw(crap stream.ogg stream2.ogg stream3.ogg);
   @mms = qw(crap mp3 mp3-2 mp3-3);

   `wget -q -O - "http://admin:00ps00ps\@www.spogbiper.com:8000/admin/metadata?mount=/$oms[$channel]&mode=updinfo&song=$mmsg"`; 
   `wget -q -O - "http://admin:00ps00ps\@mp3.spogbiper.com:8000/admin/metadata?mount=/$mms[$channel]&mode=updinfo&song=$mmsg"`;

   print "metadata for channel $channel set to: $mmsg";
  }
 }
 else
 {
  #menu
  print "<A HREF=/cgi-bin/listeners.pl>Listeners</A><P>";
  print "<A HREF=/cgi-bin/admin.pl?action=import>Import tunes</A><P>";
  print "<A HREF=/cgi-bin/admin.pl?action=managequeue>Manage queue</A><P>";
  print "<A HREF=/cgi-bin/songman.pl>Manage tunes</A><P>";
  print "<A HREF=/cgi-bin/admin.pl?action=manageshows>Manage shows</A><P>";
  print "<A HREF=/cgi-bin/admin.pl?action=managecovers>Manage cover art</A><P>";
  print "<A HREF=/cgi-bin/admin.pl?action=managelyrics>Manage lyrics</A><P>";

  print "<FORM>&nbsp;&nbsp;&nbsp;Set metadata for channel (the next song will overwrite):<br>&nbsp;&nbsp; <INPUT id='mmsg' TYPE=TEXT SIZE=34 NAME=mmsg>&nbsp;";
  print "<INPUT TYPE=HIDDEN NAME=action VALUE=meta>";
  print "<INPUT TYPE=SUBMIT Name=search VALUE=Set id='search'></FORM>";
 }



}
else
{
 print "<FONT COLOR=#FFFFFF><H3>What it is</H3>";
 print "<FORM>";
 print "<TABLE><TR><TD><FONT COLOR=#FFFFFF>Name: </TD><TD><INPUT TYPE=TEXT NAME=user></TD></TR>";
 print "<TR><TD><FONT COLOR=#FFFFFF>Password: </TD><TD><INPUT TYPE=PASSWORD NAME=pass></TD></TR>";
 print "<TR><TD COLSPAN=2><CENTER><INPUT TYPE=Submit VALUE=Login></TD></TR></TABLE>";
 print "</FORM>";
}

print "</BODY></HTML>";

