#############################
#
#      Backup Intranet
#
#############################

# Setting path for vboxmanage
$Env:Path = "c:\Program Files\Oracle\VirtualBox\"

# creating backup paths
$remoteBackupPath = "\\freenas\programas\VM_Backup"
$backupDriveLetterMount = "L"
$backupFilename = $backupDriveLetterMount + ":\" + [string](Get-Date).Year + [string](Get-Date).Month + [string](Get-Date).Day + "_Intranet_Backup.ova"
$vmName = "2018_intranet"
$logFile = "C:\Users\administrador.DMCL\Documents\vmbackup\VMBackup.log"

# Email Setup
$EmailTo1 = ""
$EmailTo2 = ""
$SMTPServer = "smtp.gmail.com" 
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
$SMTPClient.EnableSsl = $true 
$user = "xxx@gmail.com"
$pw = ConvertTo-SecureString "Password" -AsPlainText -Force
$SMTPClient.Credentials = New-Object System.Management.Automation.PSCredential($user, $pw) 
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = $user
$emailMessage.To.Add($EmailTo1)
$emailMessage.To.Add($EmailTo2)

# Appending new header line to log file
$Time=Get-Date
"################ Starting Intranet Backup at $Time ######################" | out-file $logFile -append

# mounting backup path New-PSDrive -Name L -Root \\freenas\programas\VM_Backup\ -Persist -PSProvider FileSystem
Try
{
    New-PSDrive -Name $backupDriveLetterMount -Root $remoteBackupPath -Persist -PSProvider FileSystem
    $Time=Get-Date
    "[Success] Mounting Backup Path at $Time" | out-file $logFile -append
}
Catch
{
    $Time=Get-Date
    "[Error] Mounting Backup Path at $Time" | out-file $logFile -append
    $_.Exception.Message | out-file $logFile -append
    $_.Exception.ItemName | out-file $logFile -append
    $emailMessage.Subject = "Error Mounting Backup Path"
    $emailMessage.Body = "Error Mounting Backup Path $Time"
    $emailMessage.Attachments.Add($logFile)
    $SMTPClient.Send($emailMessage)
    Break
}

# Stopping VM
Try
{
    $vmanagerStopVM = "VBoxManage.exe"
    $vmanagerStopVM += @(" controlvm ")
    $vmanagerStopVM += @($vmName)
    $vmanagerStopVM += @(" poweroff")
    Write-host "$vmanagerStopVM"
    Invoke-Expression "$vmanagerStopVM"
    $Time=Get-Date
    "[Success] Stop VM at $Time" | out-file $logFile -append
}
Catch
{   
    $Time=Get-Date
    "[Error] to Stop VM at $Time" | out-file $logFile -append
    $_.Exception.Message | out-file $logFile -append
    $_.Exception.ItemName | out-file $logFile -append
    $emailMessage.Subject = "Error Stopping VM Intranet"
    $emailMessage.Body = "Error Stopping VM Intranet at $Time"
    $emailMessage.Attachments.Add($logFile)
    $SMTPClient.Send($emailMessage)
    Break
}

# Backing Up VM
Try
{
    $vmanagerBackup = "VBoxManage.exe"
    $vmanagerBackup += @(" export ")
    $vmanagerBackup += @($vmName)
    $vmanagerBackup += @(" --ovf10")
    $vmanagerBackup += @(" -o ")
    $vmanagerBackup += @([string]$backupFilename)
    Write-host "$vmanagerBackup"
    Invoke-Expression "$vmanagerBackup"
    $Time=Get-Date
    "[Success] Backing Up VM at $Time" | out-file $logFile -append
}
Catch
{
    $Time=Get-Date
    "[Error] Backing Up VM at $Time" | out-file $logFile -append
    $_.Exception.Message | out-file $logFile -append
    $_.Exception.ItemName | out-file $logFile -append
    $emailMessage.Subject = "Error Creating Backup VM Intranet"
    $emailMessage.Body = "Error Creating Backup at $Time"
    $emailMessage.Attachments.Add($logFile)
    $SMTPClient.Send($emailMessage)
    Break
}

# Start VM after Backup
Try
{
    $vmanagerStart = "VBoxManage.exe"
    $vmanagerStart += @(" startvm ")
    $vmanagerStart += @($vmName)
    $vmanagerStart += @(" -type headless")
    Write-host "$vmanagerStart"
    Invoke-Expression "$vmanagerStart"
    $Time=Get-Date
    "[Success] Starting VM at $Time" | out-file $logFile -append
}
Catch
{
     $Time=Get-Date
    "[Error] Starting VM at $Time" | out-file $logFile -append
    $_.Exception.Message | out-file $logFile -append
    $_.Exception.ItemName | out-file $logFile -append
    $emailMessage.Subject = "Error Starting VM Intranet"
    $emailMessage.Body = "Error Starting VM Intranet at $Time"
    $emailMessage.Attachments.Add($logFile)
    $SMTPClient.Send($emailMessage)
    Break
}
# remove old Backups
$backupFileCount = ( Get-ChildItem -Filter *.ova $remoteBackupPath | Measure-Object ).Count
$backupPath = $backupDriveLetterMount + ":\"

DO
{
    $Item = Get-ChildItem -Path $remoteBackupPath -Filter *.ova | Sort CreationTime | select -First 1            
    Write-Host "Oldest file/folder in $FolderName is $($Item.FullName)"
    Try
    {
        Remove-Item -Path $($Item.FullName) -Force
        $Time=Get-Date
        "[Success] Deleting old backup at $Time" | out-file $logFile -append
    }
    Catch
    {
        $Time=Get-Date
        "[Error] Deleting old backup at $Time" | out-file $logFile -append
        $_.Exception.Message | out-file $logFile -append
        $_.Exception.ItemName | out-file $logFile -append
        $emailMessage.Subject = "Error Deleting Old Backup VM Intranet"
        $emailMessage.Body = "Error Deleting Old Backup VM Intranet at $Time"
        $emailMessage.Attachments.Add($logFile)
        $SMTPClient.Send($emailMessage)
    }
    $backupFileCount = ( Get-ChildItem -Filter *.ova $remoteBackupPath | Measure-Object ).Count
} While ($backupFileCount -gt 3)

# removing Network drive
Try
{
    Remove-PSDrive -Name $backupDriveLetterMount
}
Catch
{
    $Time=Get-Date
    "[Error] Umounting Network drive at $Time" | out-file $logFile -append
    $_.Exception.Message | out-file $logFile -append
    $_.Exception.ItemName | out-file $logFile -append
    $emailMessage.Subject = "Error Unmounting Backup Path"
    $emailMessage.Body = "Error Unmounting Backup Path at $Time"
    $emailMessage.Attachments.Add($logFile)
    $SMTPClient.Send($emailMessage)
    Break
}

$emailMessage.Subject = "Backup Intranet Done!"
$emailMessage.Body = "Backup Intranet Done! $Time"
$SMTPClient.Send($emailMessage)