<#
.SYNOPSIS
    Creates an Active Directory user/service account for the nd.gov domain
.DESCRIPTION
    Creates an Active Directory user/service account for the nd.gov domain.
.NOTES
    The PasswordstateList parameter must be validated.  If a Passwordstate Password List to the options, ensure that the ndgov\svcitdiaasauto Active Directory has modify access on the Password List.

    Requires Integrated or Agent environment.  If not chosen, an erroneous error is caused during the invocation of New-ITDADServiceAccount when the PSCredential object is created to be returned to the user, see below.
        [error] Exception calling ".ctor" with "2" argument(s): "Cannot process argument because the value of argument "password" is null. Change the value of argument "password" to a non-null value." 
        The agent environment is selected to reduce parameter during script execution, and Run As Credential is enforced as svcitdpsuwin
.LINK
    https://northdakota.service-now.com/kb_view.do?sysparm_article=KB0016867
#>

[CmdletBinding()]
param (
    [Parameter(Mandatory = $true,
        HelpMessage = "Only nd.gov domain is supported at this time.")]
    [ValidateSet("nd.gov")]
    [string]
    $DomainName = 'nd.gov',

    [Parameter(Mandatory = $true,
        HelpMessage = "This is the account name.  This value will also be set on the Active Directory Surname attribute (GivenName or Surname are required for ServiceNow lookups)")]
    [string]
    $SamAccountName,

    [Parameter(Mandatory = $true,
        HelpMessage = "Will be set on the respective Passwordstate record property and Active Directory attribute.  '1120' will automatically be appended to the entry.")]
    [string]
    $Description,

    [Parameter(Mandatory = $true,
        HelpMessage = "What goes into the Passwordstate record Title field.  Generally a FQDN for the server that will use this service account.")]
    [string]
    $PasswordstateTitle,

    [Parameter(Mandatory = $true,
        HelpMessage = "The Passwordstate Password List where the credentials to be saved.  Go here to retrieve the password for the new account.")]
    [ValidateSet('CSRC', 'VMware_Systems','Peoplesoft Share PW')]
    [string]
    $PasswordstateList
)

Write-Verbose -Message "Prepare variables / SQL connection based on PSU server" -Verbose
$RequestedBy = $UAJob.Identity.Name # user that started the job
$PSUJobId = $UAJob.Id

$StartDateTime = (Get-Date)
$EndDateTime = $StartDateTime.AddMinutes(1)

Write-Verbose -Message ("UAJob.ComputerName = " + $UAJob.ComputerName) -Verbose
switch ($UAJob.ComputerName) {
    "ITDWINAUTOT1" {
        $ServerInstance = "itdintsql22p1.nd.gov\INTSQL22P1"
        $Database = "ITD-Systems-Automation"
        $SnapshotTable = "Infra_ActiveDirectory_Object_NewITDADServiceAccount_NPD"
        $ServiceNowEnvironment = 'Test'
    }
    "ITDWINAUTOP1" {
        $ServerInstance = "itdintsql22p1.nd.gov\INTSQL22P1"
        $Database = "ITD-Systems-Automation"
        $SnapshotTable = "Infra_ActiveDirectory_Object_NewITDADServiceAccount_PRD"
        $ServiceNowEnvironment = 'Production'
    }
}

Write-Verbose -Message "fix samaccountname" -Verbose
$SamAccountName = $SamAccountName.Tolower()

# add to SQL
Write-Verbose -Message "Add request to SQL" -Verbose
$SqlQuery = "INSERT INTO [$SnapshotTable] (PSUJobId,RequestedBy,DateTime,Status,DomainName,SamAccountName,Description,PasswordstateTitle,PasswordstateList) Values ('$PSUJobId', '$RequestedBy', '$StartDateTime','Requested','$DomainName','$SamAccountName', '$Description', '$PasswordstateTitle', '$PasswordstateList');"
Write-Verbose -Message $SqlQuery -Verbose
Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQuery -Credential $Secret:sql_itdpsu1 -Verbose

# Do the work
Write-Verbose -Message "Create the account in Active Directory, and Passwordstate record" -Verbose
New-ITDADServiceAccount -SamAccountName $SamAccountName -Description $Description -PasswordstateList $PasswordstateList -PasswordstateTitle $PasswordstateTitle -Credential $Secret:ndgov_svcitdpsuad -Verbose
Write-Verbose -Message "Executing Get-ADUser -Identity $SamAccountName" -Verbose

# Validate the user
$ADUser = Get-ADUser -Identity $SamAccountName
If ($ADUser) {
    Write-Output $ADUser

    Write-Verbose -Message "Create CHG request for the work" -Verbose
    New-ITDServiceNowSession -Environment $ServiceNowEnvironment -Credential $Secret:snow_vmcred
    $NewITDServiceNowChangeRequestParams = @{
        TemplateName              = 'NDIT-SPS-Server Add/Chg/Del'
        RequestedByUsername       = $RequestedBy.split('@')[0] -replace 'prv';
        Category                  = 'Systems Platforms - Systems';
        Subcategory               = 'Windows';
        Impact                    = 3;
        ShortDescription          = "New $DomainName Active Directory service account $SamAccountName created - PSU Job Id $PSUJobId";
        Description               = "New $DomainName Active Directory service account $SamAccountName created";
        Justification             = "New $DomainName Active Directory service account required for zero-trust policies, following guidelines found in KB0016867";
        Implementation            = "PSUniversal execution";
        RiskImpactAnalysis        = "Low";
        BackoutPlan               = "Delete the new user account"
        TestPlan                  = "n/a"
        WhoIsImpacted             = "Windows System Administrators";
        StartTime                 = $StartDateTime
        EndTime                   = $StartDateTime.AddMinutes(1);
        AssignmentGroup           = 'NDIT-Computer Systems Windows';
        ChangeManagerUsername     = 'khellman';
        ChangeCoordinatorUsername = 'gpgolberg';
        AssignedToUsername        = $RequestedBy.split('@')[0] -replace 'prv';
    }

    $CHG = New-ITDServiceNowChangeRequest @NewITDServiceNowChangeRequestParams -Verbose
    $CHGNum = $CHG.Number.value

    Write-Verbose -Message ("Completing SNow " + $CHG.Number.value) -Verbose
    $CompleteITDServiceNowChangeRequestParams = @{
        Number     = $CHG.Number.value
        CloseCode  = "Successful"
        CloseNotes = ("New $DomainName Active Directory account " + $obj.ADDomain + "\" + $obj.SamAccountName + " created.")
    }
    Complete-ITDServiceNowChangeRequest @CompleteITDServiceNowChangeRequestParams -Verbose

    Write-Verbose -Message "Status Success" -Verbose
    $SQLStatus = "Succcess"
}
Else {
    Write-Verbose -Message "Status Failure" -Verbose
    $SQLStatus = "Failure"
}
#>

Write-Verbose -Message "Update SQL with that CHG num and update Status" -Verbose
$SqlQueryUpdate = ("UPDATE [$SnapshotTable] SET Status = '$SQLStatus', SNowCHGNum = '$CHGNum' WHERE PSUJobId = " + $PSUJobId)
Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQueryUpdate -Credential $Secret:sql_itdpsu1 -Verbose