#This script registers the CloudDrive.dll with the Framework.
#This is required for any Powershell SnapIns to be be found by PS.
SET-PSDEBUG -STRICT

function CheckForSnapin() {
# Check if the snapin already installed
  get-pssnapin -Registered CloudDriveSnapin -EA SilentlyContinue -EV err | out-null

  if ($err.Count -eq 0) {
    return $true
  }
  return $false
}

if ( (CheckForSnapin) -and $args.Count -ne 2) {
  return
}

if ($args.Count -lt 1) {
  Write-Host "Usage: InstallDrive.ps1 [/u] <Path-to-CloudDrive.dll>"
  return
}

if ($args.Count -eq 1) {
  $Path = $args[0]
} elseif ($args.Count -eq 2) {
  $path = $args[1]
} else {
  Write-Host "Usage: InstallDrive.ps1 [/u] <Path-to-CloudDrive.dll>"
  return
}


if (!(test-path $Path)) {
  Write-Error "You must provide a valid path to CloudDrive.dll. The path '$Path' is not a valid path"
  exit -1
}

# Test for admin rights
$id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$p = New-Object System.Security.Principal.WindowsPrincipal($id)

if (!($p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)))
{
  Write-Error "You must run this script as administrator to be able to register the DLL"
  exit -1
}

# Getting the framework directory from environment or by building it
if ($env:FrameworkdDir)
{
  $FrameworkDir = $env:FrameworkDir
  $FrameworkVersion = $env:FrameworkVersion
} else {
  $FrameworkDir = join-path $env:SystemRoot "\Microsoft.Net\Framework"
  $FrameworkVersion = "V2.0.50727"
}

$FrameworkDir64 = $FrameworkDir + "64"

if (! (test-path $FrameworkDir)) {
  Write-Error "Unable to find .Net framework at $FrameworkDir"
  exit -1
}

$x86InstallUtil =  join-path (join-path $FrameworkDir $FrameworkVersion) InstallUtil.exe
$x64InstallUtil =  join-path (join-path $FrameworkDir64 $FrameworkVersion) InstallUtil.exe


if (test-path $x86InstallUtil) {
  (Invoke-Expression -Command "$x86InstallUtil $args") | out-null
} else { 
  write-warning "WARNING: x86 framework install util not found, not installing for x86."
}

if (test-path $x64InstallUtil) {
  (Invoke-Expression -Command "$x64InstallUtil $args") | out-null
} else { 
  write-warning "WARNING: x64 framework install util not found, not installing for x64."
}

# Make sure the install succeeded
if ( !(CheckForSnapin) -and $args.Count -ne 2) {
  Write-Error "Errors while installing snapin. Please review the InstallUtil.InstallLog"
}