ps = '''
$ErrorActionPreference = "Stop"
$password =  "%(domainpassword)s"| ConvertTo-SecureString -asPlainText -Force
$username = "%(domain)s\%(domainuser)s"
$credential = New-Object System.Management.Automation.PSCredential($username,$password)
Add-Computer -DomainName %(domain)s -Credential $credential
'''
name = 'domain-join'
description = 'Join windows client into domain'
args = dict(
	dnsserver=dict(help='DNS Server to use for join', required=True),
	domainuser=dict(help='the domain user', required=True),
	domainpassword=dict(help='the domain users password', required=True),
)


def pre(winrm):
	if not winrm.args.domain:
		winrm.parser.error('argument --domain is required')
	winrm.plugins.set_dns_server()
	winrm.plugins.disable_firewall(state='off')


def post(winrm):
	winrm.plugins.reboot()
	winrm.wait_until_client_is_gone()
	winrm.wait_for_client()
	winrm.plugins.domain_user_validate_password()

	# add domain users to local remote desktop users group
	ps = '''
$domain = New-Object System.DirectoryServices.DirectoryEntry
$domain_sid = (New-Object System.Security.Principal.SecurityIdentifier($domain.objectSid[0],0)).value
$domain_users_sid = $domain_sid + "-513"

$auth = New-Object System.Security.Principal.SecurityIdentifier($domain_users_sid)
$domain_users_name = $auth.Translate([System.Security.Principal.NTAccount]).Value.Split("\\")[1]
$domain_users = [ADSI]"WinNT://%(domain)s/$domain_users_name,group"

$computer = $env:COMPUTERNAME
$ADSIComputer = [ADSI]("WinNT://$computer,computer")
$auth = New-Object System.Security.Principal.SecurityIdentifier("S-1-5-32-555")
$local_group_name = $auth.Translate([System.Security.Principal.NTAccount]).Value.Split("\\")[1]
$local_group = $ADSIComputer.psbase.children.find($local_group_name, 'Group')

$local_group.Add($domain_users.Path)
''' % vars(winrm.args)
	winrm.args.credssp = True
	winrm.run(ps)
