# -*- coding: utf-8 -*-

name = 'create-user'
description = 'Create a user object in AD'
args = {
	'user-name': dict(help='Name of the user', required=True),
	'user-password': dict(help='Password of the user', default='Univention.99'),
	'group': dict(help='Add user to this group'),
	'directory-entry': dict(action='store_true', help='use System.DirectoryServices.DirectoryEntry instead of New-ADUser'),
}

ps = '''
$ErrorActionPreference = "Stop"

if ("%(directory_entry)s" -eq "True") {

	$domain = New-Object System.DirectoryServices.DirectoryEntry
	$searcher = New-Object System.DirectoryServices.DirectorySearcher($domain)
	$name = "%(user_name)s"
	$password = "%(user_password)s"
	$group = "%(group)s"
	$description = "winrm test user"
	$searcher.filter = "(sAMAccountName=$name)"
	$result = $searcher.FindOne()

	If ($result -ne $Null) {
		$user = $result.GetDirectoryEntry()
		$user.SetPassword($password)
		$user.SetInfo()
	} else {
		$user = $domain.Create("user", "CN=" + $name)
		$user.Put("givenName", $name)
		$user.Put("sn", $name)
		$user.Put("sAMAccountName", $name)
		$user.Put("Description", $description)
		$user.Put("displayName", $name)
		$user.SetInfo()
		$user.AccountDisabled = $false
		$user.SetPassword($password)
		$user.SetInfo()
	}
	if ($group -ne "None") {
		$searcher.filter = "(cn=$group)"
		$result = $searcher.FindOne()
		If ($result -ne $Null) {
			$grp = $result.GetDirectoryEntry()
			$is_member = $grp.member -contains $user.distinguishedName
			if (-Not $is_member) {
				$grp.add($user.adspath)
			}
		}
	}
} else {

	$description = "winrm test user"
	$password =  "%(user_password)s"| ConvertTo-SecureString -asPlainText -Force
	$group = "%(group)s"
	New-ADUser -Name "%(user_name)s" -ChangePasswordAtLogon 0 -Description "$description" -AccountPassword($password) -PassThru | Enable-ADAccount
	Get-ADUser "%(user_name)s" -Properties Enabled | Format-Table  Name, Enabled
	if ($group -ne "None") {
		Add-ADGroupMember "%(group)s" –Member "%(user_name)s"
	}
}

exit 0
'''
