# This script checks the production server for the existence of all known Web.config files. 
# If a file is missing, emails are sent to InfoDevSupport, Todd, Kel and Elizabeth

# Create the array to hold the paths to Web.Config
$ServerPath = "\\nastntx95015\infodevsharehelpSTG\Stg\"
$WebConfigLogPath = $ServerPath + "Webconfig.log"
$SendEmail = $false
$ComputerName = $env:COMPUTERNAME
$RunningLog = ""

# Create and array to hold all paths
$array = @()
$array += $ServerPath + "Web.config"
$array += $ServerPath + "Assumptions\Web.config"
$array += $ServerPath + "C1Administration\Web.config"
#$array += $ServerPath + "Expere\Web.config"
$array += $ServerPath + "Mortgage\Web.config"
$array += $ServerPath + "OnlineApplication\Web.config"
$array += $ServerPath + "SecurityAdministration\Web.config"
$array += $ServerPath + "Vanceo\Web.config"
$array += $ServerPath + "Workflow\webhelp\Web.config"

# loop through each item in the array and report if the file exists
$DivisionLine = "================================================ from $ComputerName (InfoDev Staging server)"
Add-Content -Path $WebConfigLogPath -Value $DivisionLine
$RunningLog = $RunningLog + $DivisionLine + "`n"

foreach ($element in $array) {
    $date = Get-Date
    if (Test-Path $element){
        # Write-Output "$date Web.config exists: $element"
        $Exists = "$date Web.config exists: $element"
        $RunningLog = $RunningLog + $Exists + "`n"
        Add-Content -Path $WebConfigLogPath -Value $Exists
    }
    else{
        # Write-Output "$date *** Web.config MISSING: $element"
        $Missing = "$date *** Web.config MISSING: $element"
        $RunningLog = $RunningLog + $Missing + "`n"
        Add-Content -Path $WebConfigLogPath -Value $Missing
        $SendEmail = $true
    }
}
#Add blank line at end as a seperator
$EndLine = ""
Add-Content -Path $WebConfigLogPath -Value $EndLine
$RunningLog = $RunningLog + $EndLine


# If there was anything missing, send an email with the log attached
$log = $WebConfigLogPath


if ($SendEmail){
    $Server = "smtprelayptc.wkglobal.com"
    $Port = "25"
    $Subject = "Missing Web.config file identified"
    $From = "WKFS-InfoDevSupport@wolterskluwer.com"
    $To = "WKFS-InfoDevSupport@wolterskluwer.com"
    $recipients = "Kel Mankenberg <kelly.mankenberg@wolterskluwer.com>, Todd Stupnik <todd.stupnik@wolterskluwer.com>, Elizabeth McKibben <elizabeth.mckibben@wolterskluwer.com>"
    #$To = "kelly.mankenberg@wolterskluwer.com"
    #$recipients = "Kel Mankenberg <kelly.mankenberg@wolterskluwer.com>"
    [string[]]$CC = $recipients.Split(',')
    $PSEmailServer = "smtp.office365.com"
    $Body = "A Web.config file has been identified as missing on the Production server on $date" + "`n`n" + "$RunningLog"

    Send-MailMessage -SMTPServer $Server -Port $Port -To $To -Cc $CC -From $From -Subject $Subject -Body $Body -Attachments $log
}