#!/usr/bin/env python

# detail: http://bbs.pediy.com/showthread.php?t=195495

import os
import sys
import time
import plist
from imobiledevice import *

# mount /Developer image before test
# ideviceimagemounter /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/8.0/DeveloperDiskImage.dmg{,.signature}

def lockdown_get_service_client(service_class):
	ld = LockdownClient(iDevice())
	return ld.get_service_client(service_class)

def get_pangunew_Container(bundle_id="com.pangu.ipa1"):
	instproxy = lockdown_get_service_client(InstallationProxyClient)
	client_options = plist.Dict({
		"ApplicationType": "User",
		"ReturnAttributes": plist.Array([
			"CFBundleIdentifier",
			"CFBundleExecutable",
			"Container",
		]),
	})
	result_list = instproxy.browse(client_options)
	for app in result_list:
		if app["CFBundleIdentifier"] == bundle_id:
			return "%s" % app["Container"]
	return ""

def get_pangunew_Path(bundle_id="com.pangu.ipa1"):
	instproxy = lockdown_get_service_client(InstallationProxyClient)
	return instproxy.get_path_for_bundle_identifier(bundle_id)

def debugserver_inject_neagent(app_container, app_path, dylib):
	debugserver = lockdown_get_service_client(DebugServerClient)

	with DebugServerCommand("QSetWorkingDir:", 1, [app_container]) as cmd:
		print debugserver.send_command(cmd)

	print debugserver.set_environment_hex_encoded("DYLD_INSERT_LIBRARIES=%s/%s" % (app_path, dylib))
	print debugserver.set_argv(1, ["/usr/libexec/neagent"])

def main():
	bundle_id = "com.pangu.ipa1"
	#dylib = "xuanyuansword.dylib"
	dylib = "demo_dylib.dylib"

	app_container = get_pangunew_Container(bundle_id)
	print "Container: %s" % app_container
	app_path = get_pangunew_Path(bundle_id)
	app_path = os.path.dirname(app_path)
	print "Path: %s" % app_path

	debugserver_inject_neagent(app_container, app_path, dylib)

if __name__ == '__main__':
	main()
