# -src is the source dirtory where the *.patch files exist
# -archive is the directory to move the *.patch files to once they have been applied
param([string]$src="", [string]$archive="")

# env to redirect git output
$env:GIT_REDIRECT_STDERR = '2>&1'

# check to ensure -src is provided
if ($src -eq "") 
{
    Write-Error "-src must be provided."
    exit 1
}

# resolve -src to absolute path
$src = resolve-path $src

# ensure -src exists
if (![System.IO.Directory]::Exists($src)) {
    Write-Error "-src must exist"
    exit 1;
}

# ensure -archive is provided
if ($archive -eq "") 
{
    Write-Error "-archive must be provided."
    exit 1
}

# resolve -archive to absolute path
$archive = resolve-path $archive

# ensure -archive exists
if (![System.IO.Directory]::Exists($archive)) {
    Write-Error "-archive must exist"
    exit 1
}

# check to ensure git is clean
$statusOutput = git status --short | Out-String
if ($statusOutput -ne "") {
    Write-Error "Git is dirty. Please clean up git directory before patching."
    exit 1
}

# remember how many we've done
$count = 0

# iterate over all patch files
Get-ChildItem $src -Filter *.patch | Foreach-Object {

    # remember how many we have
    $count++

    # write something useful
    Write-Host "Applying " + $_.FullName

    # apply the file
    git am -C10 --reject --ignore-space-change --ignore-whitespace ""$_.FullName""

    # remember the exit code from git
    $gitExitCode = $LASTEXITCODE
    
    # move the file to the archive since its been applied
    mv $_.FullName ([io.path]::Combine($archive, $_.Name))
    
    # bail when the file causes issues
    if ($gitExitCode -ne 0) {
        Write-Error "error: Git Patch Failed for $($_.Name). Please resolve."
        exit $LASTEXITCODE;
    }
}

# something nice when no files exist
if ($count -eq 0) {
    Write-Host "No patch files found in $($src)."
}

# exit with no error code
exit 0