Param(
  [Parameter(Mandatory=$true)]
   [string]$clientid,
	
   [Parameter(Mandatory=$true)]
   [string]$appurl,

   [AllowNull()]
   [string]$outfile = "Wizdom365.app",

   [AllowNull()]
   [string]$title = "Wizdom 365",

   [AllowNull()]
   [string]$name = "Wizdom365",

   [AllowNull()]
   [string]$productid = "6adc8642-831b-48dc-92cd-d3b4f40c56bb"
)

# Ensure no / after appurl
$appurl = $appurl.TrimEnd('/')
$packagename = "GUI.SP.App.app"

#UNZIP
$apppackagepath = (Resolve-Path ("util\" + $packagename)).Path
Add-Type -assembly "system.io.compression.filesystem"
$folder = ((Resolve-Path ".").Path + "/appunzipped") 
Remove-Item ((Resolve-Path ".").Path + "/appunzipped") -force -Recurse -ErrorAction SilentlyContinue
[io.compression.zipfile]::ExtractToDirectory($apppackagepath, $folder)

#Do replaces
$s = Get-Content ($folder + "\AppManifest.xml")
$s = $s -replace 'ClientId=".*?"', ('ClientId="' +  $clientid + '"')
$s = $s -replace '<StartPage>https://wizdom365v2.azurewebsites.net', ('<StartPage>' + $appurl)
if ($title -ne "") {$s = $s -replace '<Title>.*</Title>', ('<Title>' +  $title + '</Title>')}
if ($name -ne "") {$s = $s -replace ' Name=".*?"', (' Name="' +  $name + '"')}
if ($productid -ne "") {$s = $s -replace ' ProductID=".*?"', (' ProductID="' +  $productid + '"')}
$s | Set-Content ($folder + "\AppManifest.xml")

#ZIP
$zipfiledest = (Resolve-Path ".").Path +  "/apppackagenew.app"
If(Test-path $zipfiledest) {Remove-item $zipfiledest}

# zip file created using "[io.compression.zipfile" won't work. zip.exe from info-zip seems to work (6+ hours used! )
cd appunzipped
..\util\zip.exe -r ("..\" + $outfile) *.*
cd ..

Remove-Item ((Resolve-Path ".").Path + "/appunzipped") -force -Recurse -ErrorAction SilentlyContinue
