functions/Import-RegentSolution.ps1

Write-Verbose "Entering PackAndImport.ps1"

Import-Module "$PsScriptRoot\Get-Config.ps1"
Import-Module "$PsScriptRoot\Get-SolutionImportLog.ps1"

function Import-RegentSolution {
  <#
    .SYNOPSIS
    Move a solution from source control to a specified CRM system.
     
    .DESCRIPTION
    This command is used to move a solution from source control to a particular CRM. This is accomplished by first packaging the raw componenets of the solution up into a .zip file using the Solution Packager, then importing that solution into the specified system. Whether the import succeeds or fails, a log is generated in the target CRM. That log is downloaded into the ./log directory of the solution repository, and, if an email (or list of emails) is provided, the log is also emailed the given address(es).
 
    .EXAMPLE
    Here's an example usage to import the solution "MyImportantSolution" as an unmanaged solution into CRMRECRUITTEST, and then email the results to several recipients
    Import-RegentSolution -SolutionName MyImportantSolution -CrmInstance CRMRECRUITTEST -Managed $false -Emails "dhines@regent.edu;bryatho@regent.edu;estevens@regent.edu"
 
  #>

  Param(
    # The unique name of the solution to import. This must correspond to a folder already in the solution repository.
    [Parameter(Mandatory = $true)]
    [string]$SolutionName, 

    # Determines which CRM instance the solution will be imported to. Note that these are hard-coded - any changes will require changes to this script module's source code or it will break!
    [ValidateSet("CRMRECRUIT", "CRMRECRUITTEST", "CRMADVISE", "CRMADVISETEST")]
    [Parameter(Mandatory = $true)]
    $CrmInstance,
    
    # Provide $true or $false. If set to $true, the solution will be imported as a managed solution.
    [Parameter(Mandatory = $true)]
    [bool]$Managed, 
    
    # Provide $true or $false (defaults to $true). If set to $true and the import succeeds, all customizations will be published once the import is finished.
    [bool]$PublishCustomizations = $true,
    
    # A list of of emails to receive the notification, seperated by semicolons. E.g "user1@regent.edu;user2@regent.edu"
    [Parameter(Mandatory = $true)]
    [string]$Emails,
    
    # A credential object used to connect to the CRM
    [Parameter(Mandatory = $true)]
    [pscredential]$Credential
  )

  $ErrorActionPreference = "Stop"

  $Config = Get-Config
  $conn = Get-RegentConnection -CrmInstance $CrmInstance
  $RepositoryPath = $Config.RepositoryPath # The path to Git repository with the unpacked solutions

  if ($Managed) {
    $type = "Managed"
    $solutionPath = "$RepositoryPath\$($solutionName)_managed.zip"
  }
  else {
    $type = "Unmanaged"
    $solutionPath = "$RepositoryPath\$solutionName.zip"
  }
    
  # Specify path to solution packager
  $solutionPackager = (Split-Path $PsScriptRoot -Parent) + "\lib\SolutionPackager.exe"
    
  #Pack the solution
  Write-Output "Packing Solution"
  $packOuput = & "$solutionPackager" /action:Pack /zipfile:"$solutionPath" /folder:"$RepositoryPath\$solutionName" /packagetype:"$type" /errorlevel:Info | Write-Host
  if ($LASTEXITCODE -ne 0) {
    throw "Solution Packager extied with error code: $LASTEXITCODE"
  }

  #Set-XrmSolutionVersionInFolder -SolutionFilesFolderPath "$RepositoryPath\$solutionName" -Version "1.3"
  
  Write-Host "Beginning Import of solution $solutionPath"
  try {
    $tempLog = "$env:APPDATA\temp-import-log.txt"
    if ($PublishCustomizations) {
      Import-CrmSolution `
        -conn $conn `
        -SolutionFilePath $solutionPath `
        -PublishChanges `
        -ErrorAction Stop `
        -ErrorVariable 'importError' *> $tempLog
    }
    else {
      Import-CrmSolution `
        -conn $conn `
        -SolutionFilePath $solutionPath `
        -ErrorAction Stop `
        -ErrorVariable 'importError' *> $tempLog
    
    }
    $ImportID = (
      Select-String `
        -Path $tempLog `
        -Pattern "([A-Z0-9]){8}-([A-Z0-9]){4}-([A-Z0-9]){4}-([A-Z0-9]){4}-([A-Z0-9]){12}"
    ).Matches[0].Value
    $title = "Solution $SolutionName Import Succeeded"
    $message = "Solution import succeeded! To see more details, open the attached log file in Excel."
    Write-Host -ForegroundColor Green "Import Successful"
  }
  catch {
    $title = "Solution $SolutionName Import Failed"
    $message = 
    @"
    Solution import failed with the following message:
    $($importError[0])
    $(if ($ImportID) {"To see more details, open the attached log file in Excel."})
"@

    throw $importError[0]
  }
  finally {
    $currTime = Get-Date -Format "mm-dd-yyyy HH-mm"
    $logPath = "$RepositoryPath\logs\$SolutionName $currTime.xml"
    if ($ImportID) {
      Get-SolutionImportLog -CrmInstance $CrmInstance `
        -ImportJobId $ImportID `
        -ExportPath $logPath `
        -Credential $Credential
    }

    if ($Emails) {
      # Send the results via email
      Write-Host "Sending results via email to the following recipients"
      $EmailArr = $Emails.Split(";", [System.StringSplitOptions]'RemoveEmptyEntries')
      # Write-Host $EmailArr
      if ($ImportID) {
        Send-MailMessage `
          -From dhines@regent.edu `
          -Subject $title `
          -To  $EmailArr `
          -Attachments $logPath `
          -Body $message `
          -SmtpServer smtp.regent.edu
      }
      Send-MailMessage `
        -From dhines@regent.edu `
        -Subject $title `
        -To  $EmailArr `
        -Body $message `
        -SmtpServer smtp.regent.edu

      Write-Host "Message Sent"
    }
    # Delete the unnecessary .zip files
    Remove-Item -Path "$RepositoryPath/*" -Filter "$SolutionName*.zip"
  }
}