#!/usr/bin/ruby

require 'mysql'

# extend the String class so you can do html and sql escaping
class String
  def html_escape
    gsub(/&/, '&amp;').gsub(/</, '&lt;').gsub(/>/, '&gt;')
  end

  def sql_escape
    Mysql::quote self
  end
end

# get search string from command-line parameters, connect and query
# database, and store the results in 'res'
str = (ARGV.shift || '').sql_escape
db = Mysql::connect 'localhost', 'videos-ro', 'videos-ro'
res = db.query "select artist,title,filename from pablotron.videos where title like '%#{str}%' or artist like '%#{str}%' order by artist"

STDERR.puts 'number of results: ' << res.num_rows.to_s

# print initial html
puts <<EOH
<html>
<head>
  <title>Video Query: #{str.html_escape}</title>
</head>
<body bgcolor='#ffffff'>
EOH

# print column titles
puts '<table border="0">', "<tr>\n  <td><b>" <<
     (res.fetch_fields.map { |field|
        field.name.html_escape
      }.join "</b></td>\n  <td><b>") <<
     "</b></td>\n</tr>"

# print results
res.each { |r|
  puts "<tr>\n  <td>" <<
       (r.map { |i| i.html_escape }.join "</td>\n  <td>") <<
       "</td>\n</tr>"
}

# close connection to db
db.close

# finish off html
puts <<EOF
</table>
</body>
</html>
EOF


