#!/usr/bin/ruby

# Dropzone Destination Info
# Name: Send to Kindle
# Description: Drop an ebook and it will be converted to MOBI and sent to your Kindle. Hold Option to convert via Amazon service.
# Handles: NSFilenamesPboardType
# Events: Clicked, Dragged
# Creator: Artem Sapegin
# URL: http://sapegin.me
# OptionsNIB: Login
# IconURL: https://raw.github.com/sapegin/dotfiles/master/dropzone/icons/kindle.png
#
# Require:
# - Calibre - http://calibre-ebook.com/download (install command line tools from Calibre’s settings)
# - mutt - brew install mutt --sidebar-patch
# - msmtp - https://gist.github.com/nerab/1410840 - http://www.tuaw.com/2010/05/04/msmtp-a-free-tool-to-send-email-from-terminal/
# - anytomobi - https://github.com/sapegin/dotfiles/blob/master/bin/anytomobi
#
# Setup:
# - Open Dropzone Kindle destination settings and type your Kindle email in Username field and any string to assword field.


require "tmpdir"


# http://stackoverflow.com/a/8791484
def in_tmpdir
	path = File.expand_path "#{Dir.tmpdir}/#{Time.now.to_i}#{rand(1000)}/"
	FileUtils.mkdir_p path
	yield path
ensure
	FileUtils.rm_rf(path) if File.exists?(path)
end


def dragged
	if not ENV["USERNAME"]
		$dz.error("Kindle destination not configured", "Open Dropzone Kindle destination settings and type your Kindle email in Username field and any string to assword field.")
		exit()
	end

	convert_by_amazon = ENV["KEY_MODIFIERS"] == "Option"

	$dz.determinate(false)

	in_tmpdir do |tmp_dir|
		for file in $items
			filename = File.basename(file)
			ext = File.extname(file)
			pdf = ext == '.pdf'
		
			if not pdf and not convert_by_amazon
				$dz.begin("Converting #{filename}…")
				output = `anytomobi #{file} #{tmp_dir} 2>&1` ; result = $?.success?
				if not result
					$dz.error("Cannot convert #{filename} to MOBI.", output)
					$dz.finish(false)
					exit()
				end
				filename = File.basename(file, ext) + '.mobi'
				file = "#{tmp_dir}/#{filename}"
			end

			$dz.begin("Sending #{filename}…")
			subject = convert_by_amazon ? " -s CONVERT" : ""
			output = `echo 'Yay!' | mutt #{subject} -a '#{file}' -- #{ENV['USERNAME']} 2>&1` ; result = $?.success?
			if not result
				$dz.error("Cannot send #{filename} to Kindle.", output)
				$dz.finish(false)
				exit()
			end
		end
	end

	$dz.finish("Enjoy reading!")
	$dz.url(false)
end

def clicked
	if File.directory?("/Volumes/Kindle")
		system("open /Volumes/Kindle/documents/")
	else
		$dz.error("Kindle not mounted", "Connect your Kindle to computer if you want to open documents folder.")
	end
	$dz.url(false)
end