#!/usr/bin/env ruby require 'rubygems' require 'optparse' require 'rbconfig' require 'open-uri' require 'imgkit/configuration' require 'imgkit/version' GOOGLE_CODE_URL = ENV['GOOGLE_CODE_URL'] || "http://code.google.com/p/wkhtmltopdf/downloads/list?can=1" def detect_architecture case arch = Config::CONFIG['arch'] when /x86_64-linux/i 'amd64' when /linux/i 'i386' when /darwin/i 'OSX' else cant_find_binaries(arch) end end def cant_find_binaries(arch) puts "Sorry, I couldn't find the binary for your architecture (#{arch}) \n at #{GOOGLE_CODE_URL}" puts "Please go to that page, unzip the appropriate binary, and install" exit(1) end def cleanup(install_to) `rm -rf wkhtmltoimage*` rescue nil `rm #{install_to}` rescue nil end def download_wkhtmltoimage(arch) if ENV['BZIP'] download = "wkhtmltoimage-0.10.0_beta4-static-#{arch}.tar.bz2" url = "http://wkhtmltopdf.googlecode.com/files/wkhtmltoimage-0.10.0_beta4-static-#{arch}.tar.bz2" else page = open(GOOGLE_CODE_URL).read download = page.match(/href=".*name=(.*wkhtmltoimage-.*#{arch}.*?)&/) or cant_find_binaries(arch) download = download[1] url = "http://wkhtmltopdf.googlecode.com/files/#{download}" end puts "Downloading #{download} from #{url}" `curl #{url} > #{download}` download end def install(download, arch, install_to) puts "Installing #{download} to #{install_to}" if download =~ /.tar.bz2$/ `sudo tar xjvf #{download}` `sudo mv wkhtmltoimage #{install_to}` elsif download =~ /.tar.lzma$/ raise "couldn't extract archive: lzcat not found" unless system("which lzcat > /dev/null 2>/dev/null") puts "Warning: lzcat is broken on Ubuntu. Re-run with --use-bzip to install alternate version" `sudo lzcat #{download} | tar x` `sudo mv wkhtmltoimage-#{arch} #{install_to}` else `sudo mv #{download} #{install_to}` end `sudo chmod +x #{install_to}` end @command = Proc.new { puts "Nothing to do: use --help"} OptionParser.new do |parser| parser.banner = "IMGKit\n\nOptions are:" parser.on("--use-bzip", "Force bzip download for Ubuntu because lzcat is broken") do ENV['BZIP'] = 'true' end parser.on("--install-wkhtmltoimage", "Install wkhtmltoimage binaries (TO=/usr/local/bin ARCHITECTURE=i386)") do @command = Proc.new do architecture = ENV['ARCHITECTURE'] || detect_architecture install_to = ENV['TO'] || IMGKit.configuration.wkhtmltoimage Dir.chdir '/tmp' cleanup(install_to) download = download_wkhtmltoimage(architecture) install(download, architecture, install_to) end end parser.on("--version", "Show Version.") do @command = Proc.new do puts IMGKit::VERSION end end parser.on("-h", "--help", "Show this.") { puts parser; exit } end.parse! @command.call