@echo off
set POWERSHELL_BAT_ARGS=%*
set PS_SCRIPT_DIR=%~dp0
if defined POWERSHELL_BAT_ARGS set POWERSHELL_BAT_ARGS=%POWERSHELL_BAT_ARGS:"=\"%
PowerShell -ExecutionPolicy Bypass -Command Invoke-Expression $('$args=@(^&{$args} %POWERSHELL_BAT_ARGS%);'+[String]::Join([Environment]::NewLine,$((Get-Content '%~f0' ^| select -skip 6) -notmatch '^^@@^|^^:'))) & goto :EOF

$CHECKSUM_NAME = "./checksum.txt"
$MANIFEST_NAME = "./manifest.json"
$PACKAGEDIRNAME = Split-Path -Path $pwd -Leaf
$REPORT_NAME = "./report_" + $PACKAGEDIRNAME + ".txt"

Remove-Item "$REPORT_NAME" -ErrorAction SilentlyContinue
$exclude = "map_key.txt","fpl.pln","import.json","variables.txt","import.csv","toolbar_panel_events.txt"
$errors = @()
$result = @()

$result += "Verifying package integrity...","Package directory:$PACKAGEDIRNAME","Manifest file:"
$contents = Get-Content -Path $MANIFEST_NAME
$result += $contents
$files = @()

$contents = Get-Content -Path $CHECKSUM_NAME
$contents.ForEach({
	$splitted = $_.Split(" ")
	$checksum = $splitted[1]
	$fullfilename = $splitted[0]
	$splitted2 = $fullfilename.Split("\\")
	$filename = $splitted2[$splitted2.Count - 1]
	if($exclude -contains $filename) {return}
	$hash = Get-FileHash -Algorithm MD5 $fullfilename |select -exp Hash;
	$line = $fullfilename + ":" + $checksum + ":" + $hash
	if($hash -eq $checksum) {
		$line += " -> OK"
	}
	else {
		$errors += $line
		$line += " -> ERROR"
	}
	$files += $line
})
if($errors.Count) {
	$result += "Errors for the following files:"
	$result += $errors
}
else {
	$result += "*** NO ERRORS ***"
}
$result += "Detail:"
$result += $files
Write-Output $result
Add-Content -Path $REPORT_NAME -Value $result
