$hash_file = <%= hash_file %>

Function Cleanup($disposable) {
  if (($disposable -ne $null) -and ($disposable.GetType().GetMethod("Dispose") -ne $null)) {
    $disposable.Dispose()
  }
}

Function Check-Files($h) {
  return $h.GetEnumerator() | ForEach-Object {
    $dst = Unresolve-Path $_.Value.target
    $dst_changed = $false
    if(Test-Path $dst -PathType Container) {
      $dst_changed = $true
      $dst = Join-Path $dst $_.Value.src_basename
    }
    New-Object psobject -Property @{
      chk_exists = ($exists = Test-Path $dst -PathType Leaf)
      src_sha1 = ($sMd5 = $_.Key)
      dst_sha1 = ($dMd5 = if ($exists) { Get-SHA1Sum $dst } else { $null })
      chk_dirty = ($dirty = if ($sMd5 -ne $dMd5) { $true } else { $false })
      verifies = if ($dirty -eq $false) { $true } else { $false }
      target_is_folder = $dst_changed
    }
  } | Select-Object -Property chk_exists,src_sha1,dst_sha1,chk_dirty,verifies,target_is_folder
}

Function Get-SHA1Sum($src) {
  Try {
    $c = [System.Security.Cryptography.SHA1]::Create()
    $bytes = $c.ComputeHash(($in = (Get-Item $src).OpenRead()))
    return ([System.BitConverter]::ToString($bytes)).Replace("-", "").ToLower()
  } 
  Finally {
    Cleanup $c
    Cleanup $in
  }
}

Function Unresolve-Path($path) {
  if ($path -eq $null) {
    return $null
  }
  else {
    return $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($path)
  }
}

Check-Files $hash_file | ConvertTo-Csv -NoTypeInformation
