param(
    [Parameter(Mandatory=$true)][string]$Branch,
    [string]$Push = ""
)

$ConfirmPreference = 'None'

function Assert-LastExitCode {
    param([string]$Message)
    if ($LASTEXITCODE -ne 0) {
        Write-Error "FAILED ($LASTEXITCODE): $Message"
        exit $LASTEXITCODE
    }
}

Remove-Item -Recurse -Force -Confirm:$false -ErrorAction SilentlyContinue "fusion-white-label-branding"

Write-Host "Cloning Fusion-White-Label-Branding..."
git clone -b $Branch --depth 1 git@github.com:Theme-Fusion/Fusion-White-Label-Branding.git fusion-white-label-branding
Assert-LastExitCode "git clone Fusion-White-Label-Branding"

Set-Location fusion-white-label-branding
Write-Host "Installing & running Grunt on Fusion-White-Label-Branding..."
npm install
Assert-LastExitCode "npm install (Fusion-White-Label-Branding)"
Remove-Item -Recurse -Force -Confirm:$false -ErrorAction SilentlyContinue "languages"
New-Item -ItemType Directory -Force "languages" | Out-Null
grunt
Assert-LastExitCode "grunt (Fusion-White-Label-Branding)"

if ($Push -eq "push" -or $Push -eq "final") {
    git add .
    git commit -a -m "grunt - build script"
    git push origin $Branch
    Assert-LastExitCode "git push Fusion-White-Label-Branding"
}

@(
    ".git", ".circleci", "assets/less", "node_modules"
) | ForEach-Object { Remove-Item -Recurse -Force -Confirm:$false -ErrorAction SilentlyContinue $_ }

@(
    ".editorconfig", ".eslintrc.json", ".eslintignore", ".gitignore",
    ".jscsrc", ".jshintignore", ".jshintrc", "circle.yml", "composer.json",
    "composer.lock", "Gruntfile.js", "package.json", "package-lock.json",
    "README.md"
) | ForEach-Object { Remove-Item -Force -ErrorAction SilentlyContinue $_ }

Get-ChildItem -Path "." -Filter "phpcs.*" | Remove-Item -Force -ErrorAction SilentlyContinue

# Note: chmod is not applicable on Windows.
Set-Location ..

Remove-Item -Force -ErrorAction SilentlyContinue "fusion-white-label-branding.zip"

Write-Host "ZIP Fusion-White-Label-Branding..."
Compress-Archive -Path "fusion-white-label-branding" -DestinationPath "fusion-white-label-branding.zip" -CompressionLevel Optimal -Force

Write-Host "DONE!"
