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

# ./ucs-winrm.py run-ps  --cmd 'set-GPPrefRegistryValue -Name "FB1" -Context User -key "HKCU\Environment" -ValueName MYUSERGPO -Type String -value TEST2 -Action Update'
# ./ucs-winrm.py run-ps  --cmd "Get-ChildItem Env:"

import xmltodict

name = 'check-applied-gpos'
description = 'check if the gpo is applied on the system'
args = dict(
	usergpo=dict(help='check for this user gpo (name)', action='append'),
	computergpo=dict(help='check for this computer gpo (name)', action='append'),
	username=dict(help='check gpos for this user', required=True),
	userpwd=dict(help='password for user who\'s gpos should be checked', required=True),
)
ps = '''
#$check = get-windowsfeature -name RSAT-AD-PowerShell
#if ($check.Installed -ne "True") {
#	Add-WindowsFeature RSAT-AD-PowerShell
#}
$check = get-windowsfeature -name gpmc
if ($check.Installed -ne "True") {
	Add-WindowsFeature gpmc
}
Import-Module grouppolicy
$xml_file = 'c:\gpo.xml'
If (Test-Path $xml_file) { Remove-Item $xml_file }
Get-GPResultantSetOfPolicy -Computer $env:computername  -User %(nb_domain)s\%(username)s -ReportType Xml -Path $xml_file
'''


def pre(winrm):
	if not winrm.args.domain:
		winrm.parser.error('argument --domain is required')
	# logon as user, seems to be the only way to apply user gpo's
	winrm.plugins.logon_as()
	return


def parse_gpo(data):
	gpos = dict()
	if type(data['GPO']) is not list:
		data['GPO'] = [data['GPO']]
	for i in data['GPO']:
		name = i['Name']
		uuid = i['Path']['Identifier']['#text']
		sel = i
		if uuid == 'LocalGPO':
			continue
		if \
			i['FilterAllowed'] == 'true' and \
			i['Enabled'] == 'true' and \
			i['IsValid'] == 'true' and \
			i['AccessDenied'] == 'false':
			gpos[name] = dict(name=name, uuid=uuid, data=sel)
	return gpos


def convert_to_dict(data):
	# get the actual xml without the <?xml (encoding wrong)
	# replace all non ascii chars
	xml = ""
	found = False
	for line in data.split('\n'):
		if line.startswith('<?xml'):
			found = True
		if found:
			xml += line.decode('ascii', 'replace') + '\n'
	return xmltodict.parse(xml)


def post(winrm):
	winrm.run('more C:\gpo.xml', silent=True)
	gpos = convert_to_dict(winrm.last_stdout)
	user_gpos = parse_gpo(gpos['Rsop']['UserResults'])
	name = gpos['Rsop']['UserResults']['Name']
	print('gpresult for {0}'.format(name))
	assert name.lower() == winrm.args.nb_domain.lower() + '\\' + winrm.args.username.lower()
	computer_gpos = parse_gpo(gpos['Rsop']['ComputerResults'])
	print('user GPOs:')
	for i in user_gpos:
		print('\t{0} {1}'.format(i, user_gpos[i].get('uuid')))
	print('computer GPOs:')
	for i in computer_gpos:
		print('\t{0} {1}'.format(i, computer_gpos[i].get('uuid')))
	if winrm.args.usergpo:
		for i in winrm.args.usergpo:
			print('checking {0} in user GPOs'.format(i)),
			assert i in user_gpos
			print('OK')
	if winrm.args.computergpo:
		for i in winrm.args.computergpo:
			print('checking {0} in computer GPOs'.format(i)),
			assert i in computer_gpos
			print('OK')
