## Configuration Values
Param(
  [string]$server = 'localhost',
  [string]$databaseName = 'BimlFlex',
  [string]$authentication = 'WindowsAuthentication',
  [string]$userId = '',
  [string]$password = '',
  [string]$tennantId = '',
  [System.IO.FileInfo]$dacpacPath = './bimlflex.dacpac',
  [System.IO.FileInfo]$scriptPath = './BimlFlex_PreDacpac_Deployment.sql'
)

$sqlCmdAuthPart = "";
switch ($authentication) {
		"WindowsAuthentication" { $sqlCmdAuthPart = "-E"; break }
		"SqlServerAuthentication" { $sqlCmdAuthPart = "-U $($userId) -P $($password)"; break }
		"AadPasswordAuthentication" { $sqlCmdAuthPart = "-U $($userId) -P $($password) -G"; break }
		"AadMultiFactorAuthentication" { $sqlCmdAuthPart = "-U $($userId) -G"; break }
    "AadIntegratedAuthentication" { $sqlCmdAuthPart = "-G"; break }
		default { $sqlCmdAuthPart = "-E"; break }
}

$authPart = "";
switch ($authentication) {
		"WindowsAuthentication" { $authPart = "Integrated Security=SSPI;"; break }
		"SqlServerAuthentication" { $authPart = "User ID=$($userId);Password=$($password);"; break }
		"AadPasswordAuthentication" { $authPart = "Authentication=Active Directory Password;User ID=$($userId);Password=$($password);"; break }
		"AadMultiFactorAuthentication" { $authPart = "Authentication=Active Directory Interactive;User ID=$($userId);"; break }
    "AadIntegratedAuthentication" { $authPart = "Authentication=Active Directory Integrated;"; break }
		default { $authPart = "Integrated Security=SSPI;"; break }
}
$connectionString = "Data Source=$($Server);Initial Catalog=$($DatabaseName);$($authPart)TrustServerCertificate=True;"; 

function GetSqlPackagePath {
  $sqlPackagePath = Resolve-Path "$PSScriptRoot\..\sqlpackage-windows\sqlpackage.exe"
  if (-not (Test-Path -Path $sqlPackagePath)) { 
    if (-not (Test-Path -Path "$PSScriptRoot\..\sqlpackage-windows.zip")) { 
      Write-Host "Downloading sqlpackage-windows" -ForegroundColor Blue 
      Invoke-WebRequest -Uri https://aka.ms/sqlpackage-windows -OutFile "$PSScriptRoot\..\sqlpackage-windows.zip";
    }
    Write-Host "Expanding sqlpackage-windows" -ForegroundColor Blue 
    Expand-Archive -LiteralPath "$PSScriptRoot\..\sqlpackage-windows.zip" -DestinationPath "$PSScriptRoot\..\sqlpackage-windows" -Force
  }
  return $sqlPackagePath
}
$sqlPackagePath = GetSqlPackagePath;

$sqlCmdPath = Resolve-Path "$PSScriptRoot\..\MsSqlCmdLnUtils.msi"
$sqlCmdArgumentList = "/i $($sqlCmdPath) IACCEPTMSSQLCMDLNUTILSLICENSETERMS=YES"
try {
  $sqlcmdVersion = (sqlcmd -?)
  $sqlcmdVersion = [int]($sqlcmdVersion[1].Substring(8, 2))
  if ($sqlcmdVersion -lt 15) {
    if (-not (Test-Path -Path $sqlCmdPath)) {
      Invoke-WebRequest -Uri https://go.microsoft.com/fwlink/?linkid=2142258 -OutFile $sqlCmdPath; 
    }
    Start-Process msiexec.exe -Wait -ArgumentList $sqlCmdArgumentList;
  }
}
catch {
  if (-not (Test-Path -Path $sqlCmdPath)) {
    Invoke-WebRequest -Uri https://go.microsoft.com/fwlink/?linkid=2142258 -OutFile $sqlCmdPath; 
  }
  Start-Process msiexec.exe -Wait -ArgumentList $sqlCmdArgumentList;
}

try {
  $dbExists = (sqlcmd -S $server -d $databaseName $sqlCmdAuthPart -Q "SET NOCOUNT ON; SELECT COUNT(*) FROM [sys].[databases] WHERE [Name] = '$($DatabaseName)'")
  if ($dbExists[-1].Trim() -eq "1") {
    Write-Host "Pre-deploy for BimlFlex DB::[$DatabaseName]" -ForegroundColor Blue
    sqlcmd -S $server -d $databaseName $sqlCmdAuthPart -i "$($scriptPath)"
    Write-Host "Pre-deploy for BimlFlex DB::[$DatabaseName]::Complete" -ForegroundColor Green
  }

  ## Run SQLPackage to deploy dacpac to database
  Write-Host "Deploy BimlFlex DB::[$databaseName]::Starting" -ForegroundColor Blue
  if ($tennantId) {
    & "$sqlPackagePath" /Action:Publish /tsn:"$server" /sf:$dacpacPath /tdn:$databaseName /ua /tid:$tennantId /p:AllowIncompatiblePlatform=$true
  }
  else {
    & "$sqlPackagePath" /Action:Publish /SourceFile:"$dacpacPath" /TargetConnectionString:"$connectionString" /p:AllowIncompatiblePlatform=$true
  }
  Write-Host "Deploy BimlFlex DB::[$databaseName]::Completed" -ForegroundColor Green
}
catch {
  Write-Error "Failed:: [$_]"
  return
}
