Java.psm1

function RetrievePackages
{
    param($path, $registry)
    
    $packages = @()
    $key = $registry.OpenSubKey($path) 
    $subKeys = $key.GetSubKeyNames() |% {
        $subKeyPath = $path + "\\" + $_ 
        $packageKey = $registry.OpenSubKey($subKeyPath) 
        $package = New-Object PSObject 
        $package | Add-Member -MemberType NoteProperty -Name "DisplayName" -Value $($packageKey.GetValue("DisplayName"))
        $package | Add-Member -MemberType NoteProperty -Name "UninstallString" -Value $($packageKey.GetValue("UninstallString")) 
        $packages += $package    
    }
    return $packages
}

function Get-InstalledSoftwares
{
    $installedSoftwares = @{}
    $path = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall" 
    $registry32 = [microsoft.win32.registrykey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, [Microsoft.Win32.RegistryView]::Registry32)
    $registry64 = [microsoft.win32.registrykey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, [Microsoft.Win32.RegistryView]::Registry64)
    $packages = RetrievePackages $path $registry32
    $packages += RetrievePackages $path $registry64

    $packages.Where({$_.DisplayName}) |% { 
        if(-not($installedSoftwares.ContainsKey($_.DisplayName)))
        {
            $installedSoftwares.Add($_.DisplayName, $_) 
        }
    }
    $installedSoftwares.Values
}

function Get-Java
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$false, Position=0)]
        [Path] $Path = $Env:Temp
    )

    if([Environment]::Is64BitOperatingSystem)
    {
        $uri = "http://javadl.sun.com/webapps/download/AutoDL?BundleId=109708"
    }
    else
    {
        $uri = "http://javadl.sun.com/webapps/download/AutoDL?BundleId=109706"
    }
    
    if(-not(Test-Java))
    {

        "Downloading Java to $Path" | Write-Verbose

        $fileName = $uri.SubString($uri.LastIndexOf("/") + 1)

        Invoke-WebRequest -Uri $uri -OutFile (Join-Path $Path $fileName)

        "Installing java sdk" | Write-Verbose

        $arguments = "/s REBOOT=Supress SPONSORS=0 /L $Env:Temp\jdk_install.log"

        $proc = Start-Process (Join-Path $Path $fileName) -ArgumentList $arguments -Wait -NoNewWindow -PassThru
        if($proc.ExitCode -ne 0) 
        {
            throw "Unexpected error installing java"
        }
        [Environment]::SetEnvironmentVariable('JAVA_HOME', "C:\Program Files\Java\jre1.8.0_60\bin", "Machine")
    }
    else
    {
        "Java already installed on your machine" | Write-Verbose
    }
}

function Test-Java
{
    $javaPackage = Get-InstalledSoftwares |? {$_.DisplayName.Contains('Java 8 Update 60')}
    return $javaPackage -ne $null
}


Export-ModuleMember *Java