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

import time

ps = '''
Param(
[string]$domain = "%(domain)s",
[string]$domainMode = "%(domainmode)s",
[string]$forestMode = "%(forestmode)s",
[string]$password = "%(password)s"
)

##################
# error handling #
##################

$ErrorActionPreference = "Stop"

# for external commands
trap {
	Write-Error $_
	exit 1
}

#############
# functions #
#############

function error ($msg) {
	Write-Host "[$Now] $msg" -ForegroundColor Red
	Exit(1)
}

function mapMode ($mode) {
	# forest/domain level
	# 0 -> 2000
	# 2 -> 2003
	# 3 -> 2008
	# 4 -> 2008R2
	if ($mode.ToUpper() -eq "WIN2000") {
		return 0
	}
	elseif ($mode.ToUpper() -eq "WIN2003") {
		return 2
	}
	elseif ($mode.ToUpper() -eq "WIN2008") {
		return 3
	}
	elseif ($mode.ToUpper() -eq "WIN2008R2") {
		return 4
	}
	elseif ($mode.ToUpper() -eq "WIN2012") {
		return 5
	}
	elseif ($mode.ToUpper() -eq "WIN2012R2") {
		return 6
	}
	elseif ($mode.ToUpper() -eq "WIN2016") {
		return 7
	}
	error("unknown forest/domain mode $mode")
}


function promoWithDCpromo ($domain, $domainMode, $forestMode, $password, $domainNetBios) {
	Write-Host "dcpromo.exe"
	$forestMode = mapMode($forestMode)
	$domainMode = mapMode($domainMode)
	"[DCINSTALL]" > c:\dcpr.txt
	"InstallDNS=yes" >> c:\dcpr.txt
	"NewDomain=forest" >> c:\dcpr.txt
	"NewDomainDNSName=$domain" >> c:\dcpr.txt
	"DomainNetBiosName=$domainNetBios" >> c:\dcpr.txt
	"ReplicaOrNewDomain=domain" >> c:\dcpr.txt
	"ForestLevel=$forestMode" >> c:\dcpr.txt
	"DomainLevel=$domainMode" >> c:\dcpr.txt
	"RebootOnCompletion=no" >> c:\dcpr.txt
	"SafeModeAdminPassword=$password" >> c:\dcpr.txt
	dcpromo /unattend:c:\dcpr.txt
}

function promoWithADDSDeployment ($domain, $domainMode, $forestMode, $password, $domainNetBios) {
	Write-Host "Install-ADDSForest"
	$forestMode = mapMode($forestMode)
	$domainMode = mapMode($domainMode)
	try {
		Import-Module ADDSDeployment
		Install-ADDSForest `
			-CreateDnsDelegation:$false `
			-DatabasePath 'C:\Windows\NTDS' `
			-DomainMode "$domainMode" `
			-DomainName "$domain" `
			-DomainNetbiosName "$domainNetBios" `
			-ForestMode "$forestMode" `
			-InstallDns:$true `
			-LogPath 'C:\Windows\NTDS' `
			-NoRebootOnCompletion:$true `
			-SysvolPath 'C:\Windows\SYSVOL' `
			-Force:$true `
			-SafeModeAdministratorPassword (ConvertTo-SecureString -String "$password" -AsPlainText -Force)
	}
	Catch {
		error("Exception occurred while promoting ad: $_")
	}
}

########
# MAIN #
########

$domainNetBios = $domain.Split(".")[0].ToUpper()
$global:Now = Set-PSBreakpoint -Variable Now -Mode Read -Action { $global:Now = Get-Date }

try {
	Import-Module Servermanager
	Install-WindowsFeature AD-Domain-Services -IncludeManagementTools
}
Catch {
	Write-Host "Servermanager not found of AD-Domain-Services not available"
}

if ((gwmi win32_computersystem).partofdomain -eq $true) {
	error("i am already joined")
}

if (Get-Module -ListAvailable | Where-Object { $_.name -eq "ADDSDeployment" }) {
	promoWithADDSDeployment `
		-domain "$domain" `
		-domainMode "$domainMode" `
		-forestMode "$forestMode" `
		-password "$password" `
		-domainNetBios "$domainNetBios"
}
else {
	promoWithDCpromo `
		-domain "$domain" `
		-domainMode "$domainMode" `
		-forestMode "$forestMode" `
		-password "$password" `
		-domainNetBios "$domainNetBios"
}

exit(0)
'''


name = 'promote-ad'
description = 'promote ad'
args = dict(
	domainmode=dict(help='username to use for the join', choices=['WIN2000', 'WIN2003', 'WIN2008', 'WIN2008R2', 'WIN2012', 'WIN2012R2', 'WIN2016']),
	forestmode=dict(help='username to use for the join', choices=['WIN2000', 'WIN2003', 'WIN2008', 'WIN2008R2', 'WIN2012', 'WIN2012R2', 'WIN2016']),
)


def pre(self):
	self.wait_for_client()


def post(self):
	try:
		self.plugins.reboot()
	except Exception:
		time.sleep(60)
		self.plugins.reboot()
	self.wait_until_client_is_gone()
	self.wait_for_client()
	# TODO install root ca
