import ctypes
import sys
from ctypes import *
from ctypes.wintypes import *

SW_SHOWNORMAL=1

class SHELLEXECUTEINFO(Structure):
# See http://python.net/crew/theller/ctypes/tutorial.html#structures-and-unions
# and mingw's shellapi.h
	_fields_ = [
		("cbSize", DWORD),
		("fMask", ULONG),
		("hwnd", HWND),
		("lpVerb", LPCWSTR),
		("lpFile", LPCWSTR),
		("lpParameters", LPCWSTR),
		("lpDirectory", LPCWSTR),
		("nShow", c_int),
		("hInstApp", HINSTANCE),
		("lpIDList", LPVOID),
		("lpClass", LPCWSTR),
		("hkeyClass", HKEY),
		("dwHotKey", DWORD),
		("hIconMonitorUnion", HANDLE),
		("hProcess", HANDLE),
	        ]

def RunAsAdministrator(cmd,args,block=False):
	commandLine = ""
	for arg in args:
		commandLine = commandLine + " " + arg

	isanadmin = ctypes.windll.shell32.IsUserAnAdmin()

	seis = SHELLEXECUTEINFO()
	seis.cbSize = ctypes.sizeof(seis)
	seis.hwnd = 0
	seis.fMask = 0x00000100|0x00000040
	seis.lpVerb = "open" 
	seis.lpFile = cmd
	seis.lpParameters = commandLine
	seis.lpDirectory = ''
	seis.nShow =SW_SHOWNORMAL 

	print cmd
	print commandLine
	if isanadmin:
		seis.lpVerb = "open" 
	else:
		seis.lpVerb = "runas" 

	ret = ctypes.windll.shell32.ShellExecuteExW(byref(seis))

	if ret and seis.hInstApp>32 and seis.hProcess and block:
		print "waiting"; sys.stdout.flush()
		waitret = ctypes.windll.kernel32.WaitForSingleObject( seis.hProcess, 0xFFFFFFFF)
		print "waited!!!", waitret; sys.stdout.flush()

if __name__ == "__main__":
	if  len(sys.argv) < 2: sys.exit()
	cmd = sys.argv[1]

	print "Doing command"; sys.stdout.flush()
	RunAsAdministrator(cmd,sys.argv[2:],block=True)
	print "Done command"; sys.stdout.flush()

