# encoding: ascii
# api: powershell
# title: Get-WebFile
# description: cls
# version: 3.1
# type: script
# author: Joel Bennett
# license: CC0
# x-poshcode-id: 2802
# x-archived: 2012-09-17T19:02:09
# x-published: 2012-07-18T21:48:00
#
# function Using-Disposable {
# param (
# [System.IDisposable] $inputObject = $(throw “The parameter -inputObject is required.”),
# [ScriptBlock] $scriptBlock = $(throw “The parameter -scriptBlock is required.”)
# )
# Try {
# &$scriptBlock
# } 
# Finally {
# if ($inputObject -ne $null) {
# if ($inputObject.psbase -eq $null) {
# $inputObject.Dispose()
# } else {
# $inputObject.psbase.Dispose()
# }
# }
# }
# }
# function Test-Url {
# param(
# [string]$url = $(throw “The parameter $url is required.”)
# )
# try {
# [Net.WebRequest]$request = [Net.HttpWebRequest]::Create($url);
# $request.Method = “HEAD”; # Just get the document headers, not the data.
# $request.Credentials = [System.Net.CredentialCache]::DefaultCredentials;
# # This may throw a WebException:
# Using-Disposable ([Net.HttpWebResponse] $response = [Net.HttpWebResponse]$request.GetResponse(),
# {
# if ($response.StatusCode == [Net.HttpStatusCode]::OK)
# {
# # If no exception was thrown until now, the file exists and we 
# # are allowed to read it. 
# return $true;
# }
# else
# {
# # Some other HTTP response – probably not good.
# # Check its StatusCode and handle it.
# return $false;
# }
# })
# }
# catch [System.Net.WebException]
# {
# # Cast the WebResponse so we can check the StatusCode property
# [Net.HttpWebResponse] $webResponse = [Net.HttpWebResponse]$_.Exception.Response;
# # Determine the cause of the exception, was it 404?
# if ($webResponse.StatusCode -eq [Net.HttpStatusCode]::NotFound)
# {
# return $false;
# }
# else
# {
# # Handle differently…
# return $false;
# }
# }
# }
#
## Get-WebFile.ps1 (aka wget for PowerShell)
##############################################################################################################
## Downloads a file or page from the web
## History:
## v3.1 - Unwrap the filename when it has quotes around it
## v3   - rewritten completely using HttpWebRequest + HttpWebResponse to figure out the file name, if possible
## v2   - adds a ton of parsing to make the output pretty
##      - added measuring the scripts involved in the command, (uses Tokenizer)
##############################################################################################################
#function wget {
   param( 
      $url = (Read-Host "The URL to download"),
      $fileName
   )
   
   $req = [System.Net.HttpWebRequest]::Create($url);
   $res = $req.GetResponse();

   if($fileName -and !(Split-Path $fileName)) {
      $fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName
   } 
   elseif(($fileName -eq $null) -or (Test-Path -PathType "Container" $fileName))
   {
#  if( -and !((Test-Path -PathType "Leaf" $fileName) -or ((Test-Path -PathType "Container" (Split-Path $fileName)) -and -not )))
      [string]$fileName = ([regex]'(?i)filename=(.*)$').Match( $res.Headers["Content-Disposition"] ).Groups[1].Value
      $fileName = $fileName.trim("\/""'")
      if(!$fileName) {
         $fileName = $res.ResponseUri.Segments[-1]
         $fileName = $fileName.trim("\/")
         if(!$fileName) { 
            $fileName = Read-Host "Please provide a file name"
         }
         $fileName = $fileName.trim("\/")
         if(!([IO.FileInfo]$fileName).Extension) {
            $fileName = $fileName + "." + $res.ContentType.Split(";")[0].Split("/")[1]
         }
      }
      $fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName
   }

   if($res.StatusCode -eq 200) {
      $reader = new-object System.IO.StreamReader $res.GetResponseStream()
      $writer = new-object System.IO.StreamWriter $fileName
      # TODO: stick this in a loop and give progress reports
      $writer.Write($reader.ReadToEnd())
      
      $reader.Close();
      $writer.Close();
   }
   $res.Close(); 
   ls $fileName
#}
