#!/usr/bin/env ruby
#
# itunes_artwork.rb 0.0.3
# - a script to extract and display track artwork from iTunes
#
# Released into the public domain
#
# Please send bug reports and improvements to
# christoffer.sawicki@gmail.com

require "rubygems"
require "rbosa"
require "pathname"

def error(message)
  puts message
  exit 1
end

itunes = OSA.app("iTunes")

unless itunes.player_state == OSA::ITunes::EPLS::PLAYING
  error "Sorry, iTunes is not playing any music right now."
end

track = itunes.current_track

if track.artworks.empty?
  error "Sorry, no artwork available for the currently playing track."
end

 dirname = Pathname("~/Desktop").expand_path
basename = [track.artist, track.album].compact.join(" - ") + ".jpg"

path = dirname.join(basename)

path.open("w") do |file|
  file << track.artworks.first.data
end

puts "Wrote #{path}..."

system "open", path