#!/usr/bin/awk -f
#
#   http://code.google.com/media-translate/
#   Copyright (C) 2010  Serge A. Timchenko
#
#   This program 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 3 of the License, or
#   (at your option) any later version.
#
#   This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
#

function escape(str)
{
  gsub(/&/, "&amp;", str);
  gsub(/>/, "&gt;", str);
  gsub(/</, "&lt;", str);
  return str
}

BEGIN {
  track = 0 
  print "<?xml version='1.0' encoding='UTF-8'?>"
  print "<playlist version='1' xmlns='http://xspf.org/ns/0/'>"
  if( name != "" )
  {
    print "<title><![CDATA[" name "]]></title>"
    fn = (match(name, /(.+)\.[^\.]*$/, arr) != 0) ? arr[1] : name;
    print "<image><![CDATA[" path "/" fn ".jpg]]></image>"
  }
  print "<trackList>"
}

/^[Nn][Uu][Mm][Bb][Ee][Rr][Oo][Ff][Ee][Nn][Tt][Rr][Ii][Ee][Ss]/ { 
  gsub(/\r/, "");
  numberofentries=substr($0, index($0, "=")+1)
}

/^Title/ { 
  gsub(/\r/, "");
  idx=substr($0, 6, index($0, "=") - 6)
  title[idx]=substr($0, index($0, "=")+1)
}

/^File/ {
  gsub(/\r/, "");
  idx=substr($0, 5, index($0, "=") - 5)
  file[idx]=substr($0, index($0, "=")+1)
}

END {
  count=int(numberofentries)
  for(i=1; i<=count; i++)
  {
    f = file[i];
    t = title[i];
  
    if(f !~ /^[a-z]+:\/\// && f !~ /^\//)
    {
      gsub(/\\/, "/", f);
      location = path "/" f;
    }
    else
    {
      location = f;
    }
    match(location, /^(.+):\/\//, arr);
    protocol = tolower(arr[1]);
   
    isdir = location ~ /^(ftp:\/)?\/.*\/$/;
  
    print "<track>"
    if( t == "" )
    {
      match(f, /.*\/([^\/]+$)/, arr);
      if(arr[1] != "")
      {
        t = arr[1];
        if(isdir)
          t = "/" t "/";
      }
      else
      {
        t = f;
      }
    }
    
    print "<title><![CDATA[" t "]]></title>"
    
    if( t ~ / +TV$/ )
      print "<meta rel=\"translate\">Content-type:video/x-msvideo</meta>" 
  
    if( t ~ / +\((win-?|CP)1251\)$/ )
      print "<meta rel=\"translate\">Charset:CP1251</meta>" 
    
    match(location, /.*\.([^.\/]+)$/, arr);
    ext = tolower(arr[1]);
    
    if(ext != "")
      print "<meta rel=\"ext\"><![CDATA[" ext "]]></meta>"
  
    if(isdir)
      print "<meta rel=\"class\">directory</meta>"
    
    if(protocol == "")
      protocol = "file";
  
    print "<meta rel=\"protocol\"><![CDATA[" protocol "]]></meta>"
    
    print "<location><![CDATA[" location "]]></location>"
    print "</track>"
  }
  
  print "</trackList>"
  print "</playlist>"
}