SingleScripts/Import-Content.ps1

[CmdletBinding()]
Param(
  [Parameter(Mandatory=$true,Position=1)] [string] $DBAPIRootUrl,
  [Parameter(Mandatory=$True,Position=2)] [string] $DBAPIKey,
  [Parameter(Mandatory=$True,Position=3)] [string] $SourceFile,
  [Parameter(Mandatory=$False,Position=4)] [switch] $Overwrite,
  [Parameter(Mandatory=$False,Position=5)] [string] $DBPathToImport = "/",
    [Parameter(Mandatory=$False,Position=5)] [bool] $DeleteFolderIfExists = $false
)

[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12

$DBAPIUrl = $DBAPIRootUrl.Trim('/') + "/api/2.0/workspace/import"

$headers = @{
  Authorization = "Bearer $DBAPIKey"
  "Content-Type" = "application/json"
}
Write-Information "Loading Source File from $SourceFile ..."
$importFile = Get-Item $SourceFile

$importFileFormat = $importFile.Extension.ToUpper().Trim(".")
$importFileDbPath = "$DBPathToImport$($importFile.BaseName -replace "__", "/")/"
  
$importFileBytes = [IO.File]::ReadAllBytes($importFile.FullName)
$importFileContentB64 = [Convert]::ToBase64String($importFileBytes)
  
$body = @{
  path = $importFileDbPath
  format = $importFileFormat
  content = $importFileContentB64
}

if($DeleteFolderIfExists){
  #Write-Information "Deleting folder at path $importFileDbPath (DeleteFolderIfExists)"
  $x = .\Scripts\Functions\Delete-Folder.ps1 -DBAPIRootUrl $DBAPIRootUrl -DBAPIKey $DBAPIKey -FolderPath $importFileDbPath -Recursive -Force -ErrorAction SilentlyContinue
}

if ($importFileFormat -eq "DBC") {   
    Write-Information "Creating folder $importFileDbPath ..."
    $x = .\Scripts\Functions\Create-Folder.ps1 -DBAPIRootUrl $DBAPIRootUrl -DBAPIKey $DBAPIKey -FolderPath $importFileDbPath 
    
    if ($Overwrite.IsPresent) {
        #Write-Information "Deleting folder at path $importFileDbPath ... (Overwrite)"
        $x = .\Scripts\Functions\Delete-Folder.ps1 -DBAPIRootUrl $DBAPIRootUrl -DBAPIKey $DBAPIKey -FolderPath $importFileDbPath -Recursive -Force -ErrorAction SilentlyContinue
    }

    Write-Information "Folder Created: $importFileDbPath !"
}
else 
{
    $body += @{overwrite = $Overwrite}
}

$bodyJson = $body | ConvertTo-Json
Write-Information "Starting import of $($importFile.Name) to $importFileDbPath ..."
$result = Invoke-RestMethod -Uri $DBAPIUrl -Method POST -Headers $headers -Body $bodyJson
Write-Information "Import Finished!"
$result