<#
  Original script taken from: https://github.com/MattiasC85/Scripts/blob/master/OSD/Download-AppxFromStore.ps1
#>

Param (
  [Parameter(Mandatory=$True)] [string] $StoreURL,
  [Parameter(Mandatory=$False)] [string] $SavePath
)

if ($StoreURL.EndsWith("/")) {
  $StoreURL=$StoreURL.Remove($StoreUrl.Length-1,1)
}

$wchttp = [System.Net.WebClient]::new()
$URI = "https://store.rg-adguard.net/api/GetFiles"
$myParameters = "type=url&url=$($StoreURL)"
$wchttp.Headers[[System.Net.HttpRequestHeader]::ContentType]="application/x-www-form-urlencoded"
$HtmlResult = $wchttp.UploadString($URI,$myParameters)

$start=$HtmlResult.IndexOf("<p>The links were successfully received from the Microsoft Store server.</p>")
if ($start -eq -1) {
  write-host "Could not get the links, please check the StoreURL."
  exit
}

$TableEnd=($HtmlResult.LastIndexOf("</table>")+8)
$SemiCleaned=$HtmlResult.Substring($start,$TableEnd-$start)

$newHtml=New-Object -ComObject "HTMLFile"
try {
  # This works in PowerShell with Office installed
  $newHtml.IHTMLDocument2_write($SemiCleaned)
} catch {
  # This works when Office is not installed    
  $src = [System.Text.Encoding]::Unicode.GetBytes($SemiCleaned)
  $newHtml.write($src)
}

if ( !$SavePath ) {
  $SavePath=($StoreURL -split "/").split()[-2]
}

if (!(test-path "$SavePath")) {
    write-host "Creating directory $SavePath"
    try {
        New-Item -ItemType Directory "$SavePath" -ErrorAction Stop | Out-Null
    } catch {
        write-host "Failed to create directory.$([System.environment]::NewLine)$_"
        write-host "Exiting..."
        exit
    }
}

$ToDownload=$newHtml.getElementsByTagName("a") | Select-Object textContent, href

Foreach ($Download in $ToDownload) {
  Write-host "Downloading $($Download.textContent)..."
  $wchttp.DownloadFile($Download.href, "$SavePath\$($Download.textContent)")
}

write-host "---------------------------------------"
write-host "Download is complete. Your files are in directory [ $SavePath ] ..." 

