#!/usr/bin/ruby -w
require 'open-uri'

IPHONE_USER_AGENT = "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3" 

def download_movie(url)
  # Get html for movie page (as an iPhone UA)
  htm = open(url, {'User-Agent', IPHONE_USER_AGENT}).read

  # Get the pid of the movie
  pid = htm.match(/pid\s+:\s+'([a-z0-9]+)'/i)[1]

  # Get the pid of the movie
  title = htm.match(/prog\s+=\s+"\s*(.*)\s*"/i)[1]
  dest = "#{title}.mov" 

  # Download the mp4 file (uses wget)
  puts "Downloading mp4 file of #{title} (http://www.bbc.co.uk/mediaselector/3/auth/iplayer_streaming_http_mp4/#{pid} to (#{dest})"  
  system "wget -O\"#{dest}\" http://www.bbc.co.uk/mediaselector/3/auth/iplayer_streaming_http_mp4/#{pid}" 
end

if ARGV.length == 1
  download_movie(ARGV.first)
else
  puts "usage: ruby iplayer_download.rb " 
end