import time

name = 'logon-as'
description = 'logon as user'
args = dict(
	username=dict(help='logon user', required=True),
	userpwd=dict(help='logon user password', required=True),
	command=dict(help='command to runOnce, escape " with `" in commands', action='append', required=False),
)
ps = '''
$RegPath = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"
$RegROPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce"
Set-ItemProperty $RegPath "AutoAdminLogon" -Value "1" -type String
Set-ItemProperty $RegPath "DefaultUsername" -Value "%(username)s" -type String
Set-ItemProperty $RegPath "DefaultDomainName" -Value "%(domain)s" -type String
Set-ItemProperty $RegPath "DefaultPassword" -Value "%(userpwd)s" -type String
Set-ItemProperty $RegPath "AutoLogonCount" -Value "1" -type DWord
Set-ItemProperty $RegROPath "(Default)" -Value "" -type String
$commands = @(%(command)s)
$counter = 0
foreach ($command in $commands) {
	Set-ItemProperty $RegROPath "misc$counter" -Value "$command" -type String
	$counter += 1
}
Restart-Computer -Force
'''


def pre(winrm):
	if 'command' not in vars(winrm.args):
		winrm.args.command = None
	if winrm.args.command is None:
		winrm.args.command = ""
	else:
		winrm.args.command = '"' + '","'.join(winrm.args.command) + '"'
	if not winrm.args.domain:
		winrm.parser.error('argument --domain is required')


def post(winrm):
	winrm.wait_until_client_is_gone()
	winrm.wait_for_client()
	for i in range(180):
		winrm.run('query user /server:localhost')
		if winrm.last_stdout and winrm.args.username.lower() in winrm.last_stdout.lower():
			break
		time.sleep(1)
	else:
		winrm.error('logon as user {0} failed'.format(winrm.args.username))
