<#PSScriptInfo

.VERSION 1.4.3

.GUID 539e5585-7a02-4dd6-b9a6-5dd288d0a5d0

.AUTHOR Microsoft

.COMPANYNAME Microsoft Corporation

.COPYRIGHT (c) Microsoft Corporation

.TAGS install vscode installer

.LICENSEURI https://github.com/PowerShell/vscode-powershell/blob/main/LICENSE.txt

.PROJECTURI https://github.com/PowerShell/vscode-powershell/blob/main/scripts/Install-VSCode.ps1

.ICONURI

.EXTERNALMODULEDEPENDENCIES

.REQUIREDSCRIPTS

.EXTERNALSCRIPTDEPENDENCIES

.RELEASENOTES
    02/06/2021 - Fix an architecture check issue with non-English localizations.
    --
    01/04/2021 - Fix host for downloading VSCode.
    --
    07/10/2019 - Fix a version check when installing user-builds with Windows Powershell greater than 5.
    --
    30/08/2019 - Added functionality to install the "User Install" variant of Stable Edition.
    --
    07/11/2018 - Added support for PowerShell Core and macOS/Linux platforms.
    --
    15/08/2018 - Added functionality to install the new "User Install" variant of Insiders Edition.
    --
    21/03/2018 - Added functionality to install the VSCode context menus.
                 Also, VSCode is now always added to the search path.
    --
    20/03/2018 - Fix OS detection to prevent error
    --
    28/12/2017 - Added functionality to support 64-bit versions of VSCode
                 and support for installation of VSCode Insiders Edition.
    --
    Initial release.
#>

<#
.SYNOPSIS
    Installs Visual Studio Code, the PowerShell extension, and optionally
    a list of additional extensions.

.DESCRIPTION
    This script can be used to easily install Visual Studio Code and the
    PowerShell extension on your machine.  You may also specify additional
    extensions to be installed using the -AdditionalExtensions parameter.
    The -LaunchWhenDone parameter will cause VS Code to be launched as
    soon as installation has completed.

    Please contribute improvements to this script on GitHub!

    https://github.com/PowerShell/vscode-powershell/blob/main/scripts/Install-VSCode.ps1

.PARAMETER Architecture
    A validated string defining the bit version to download. Values can be either 64-bit or 32-bit.
    If 64-bit is chosen and the OS Architecture does not match, then the 32-bit build will be
    downloaded instead. If parameter is not used, then 64-bit is used as default.

.PARAMETER BuildEdition
    A validated string defining which build edition or "stream" to download:
    Stable or Insiders Edition (system install or user profile install).
    If the parameter is not used, then stable is downloaded as default.


.PARAMETER AdditionalExtensions
    An array of strings that are the fully-qualified names of extensions to be
    installed in addition to the PowerShell extension.  The fully qualified
    name is formatted as "<publisher name>.<extension name>" and can be found
    next to the extension's name in the details tab that appears when you
    click an extension in the Extensions panel in Visual Studio Code.

.PARAMETER LaunchWhenDone
    When present, causes Visual Studio Code to be launched as soon as installation
    has finished.

.PARAMETER EnableContextMenus
    When present, causes the installer to configure the Explorer context menus

.EXAMPLE
    Install-VSCode.ps1 -Architecture 32-bit

    Installs Visual Studio Code (32-bit) and the powershell extension.
.EXAMPLE
    Install-VSCode.ps1 -LaunchWhenDone

    Installs Visual Studio Code (64-bit) and the PowerShell extension and then launches
    the editor after installation completes.

.EXAMPLE
    Install-VSCode.ps1 -AdditionalExtensions 'eamodio.gitlens', 'vscodevim.vim'

    Installs Visual Studio Code (64-bit), the PowerShell extension, and additional
    extensions.

.EXAMPLE
    Install-VSCode.ps1 -BuildEdition Insider-User -LaunchWhenDone

    Installs Visual Studio Code Insiders Edition (64-bit) to the user profile and then launches the editor
    after installation completes.

.NOTES
    This script is licensed under the MIT License:

    Copyright (c) Microsoft Corporation.

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.
#>
[CmdletBinding(SupportsShouldProcess=$true)]
param(
    [parameter()]
    [ValidateSet('64-bit', '32-bit')]
    [string]$Architecture = '64-bit',

    [parameter()]
    [ValidateSet('Stable-System', 'Stable-User', 'Insider-System', 'Insider-User')]
    [string]$BuildEdition = "Stable-System",

    [Parameter()]
    [ValidateNotNull()]
    [string[]]$AdditionalExtensions = @('GitHub.copilot','GitHub.copilot-chat','eamodio.gitlens','ms-vscode.powershell', `
        'ms-python.vscode-pylance','ms-azuretools.vscode-containers''ms-python.python','ms-python.debugpy', `
        'ms-vscode.vscode-node-azure-pack','ms-windows-ai-studio.windows-ai-studio','TeamsDevApp.vscode-ai-foundry', `
        'ms-azuretools.vscode-azureappservice','ms-azuretools.vscode-azurecontainerapps','ms-azuretools.vscode-cosmosdb', `
        'ms-azuretools.azure-dev','ms-azuretools.vscode-azurefunctions','ms-azure-load-testing.microsoft-testing', `
        'ms-azuretools.vscode-azureresourcegroups','ms-azuretools.vscode-azurestaticwebapps','ms-azuretools.vscode-azurestorage', `
        'ms-vscode.vscode-node-azure-pack','ms-azuretools.vscode-azurevirtualmachines','naumovs.color-highlight', `
        'ms-azuretools.vscode-azure-github-copilot','hashicorp.terraform','redhat.ansible','ms-vscode-remote.remote-ssh', `
        'ms-vscode-remote.remote-ssh-edit','ms-vscode.remote-explorer','vscode-icons-team.vscode-icons'),

    [switch]$LaunchWhenDone,

    [switch]$EnableContextMenus
)

# Determine the OS and architecture   
Function Test-IsOsArchX64 {

    If ($PSVersionTable.PSVersion.Major -lt 6) {
        Return (Get-CimInstance -ClassName Win32_OperatingSystem).OSArchitecture -match '64'
    }

    Return [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture -eq [System.Runtime.InteropServices.Architecture]::X64
}


# Determine the OS
Function Get-CodePlatformInformation {
    Param(
        [Parameter(Mandatory=$true)]
        [ValidateSet('32-bit', '64-bit')]
        [string]
        $Bitness,

        [Parameter(Mandatory=$true)]
        [ValidateSet('Stable-System', 'Stable-User', 'Insider-System', 'Insider-User')]
        [string]
        $BuildEdition
    )

    If ($Bitness -ne '64-bit' -and $os -ne 'Windows') {
        throw "Non-64-bit *nix systems are not supported"
    }

    If ($BuildEdition.EndsWith('User') -and $os -ne 'Windows') {
        throw 'User builds are not available for non-Windows systems'
    }

    Switch ($BuildEdition) {
        
        'Stable-System' {
            $appName = "Visual Studio Code ($Bitness)"
            $exePath = "$installBase\Microsoft VS Code\bin\code.cmd"
            $channel = 'stable'
            Break
        }

        'Stable-User' {
            $appName = "Visual Studio Code ($($Architecture) - User)"
            $exePath = "${env:LocalAppData}\Programs\Microsoft VS Code\bin\code.cmd"
            $channel = 'stable'
            $platform += '-user'
            Break
        }

        'Insider-System' {
            $appName = "Visual Studio Code - Insiders Edition ($Bitness)"
            $exePath = "$installBase\Microsoft VS Code Insiders\bin\code-insiders.cmd"
            $channel = 'insider'
            Break
        }

        'Insider-User' {
            $appName = "Visual Studio Code - Insiders Edition ($($Architecture) - User)"
            $exePath = "${env:LocalAppData}\Programs\Microsoft VS Code Insiders\bin\code-insiders.cmd"
            $channel = 'insider'
            $platform += '-user'
            Break
        }
    }

    $ext = 'exe'

    Switch ($Bitness) {
        
        '32-bit' {
            $platform = 'win32'

            If (Test-IsOsArchX64) {
                $installBase = ${env:ProgramFiles(x86)}
                BBreak
            }

            $installBase = ${env:ProgramFiles}
            Break
        }

        '64-bit' {
            $installBase = ${env:ProgramFiles}

            If (Test-IsOsArchX64) {
                $platform = 'win32-x64'
                Break
            }

            Write-Warning '64-bit install requested on 32-bit system. Installing 32-bit VSCode'
            $platform = 'win32'
            Break
        }
    }

    $info = @{
        AppName = $appName
        ExePath = $exePath
        Platform = $platform
        Channel = $channel
        FileUri = "https://update.code.visualstudio.com/latest/$platform/$channel"
        #"https://code.visualstudio.com/sha/download?build=$($BuildEdition)&os=$($bitVersion)"
        Extension = $ext
    }

    Return $info
}

Function Save-WithBitsTransfer {
    Param(
        [Parameter(Mandatory=$true)]
        [string]
        $FileUri,

        [Parameter(Mandatory=$true)]
        [string]
        $Destination,

        [Parameter(Mandatory=$true)]
        [string]
        $AppName
    )

    Write-Host "`nTéléchargement de la dernière version $AppName ..." -ForegroundColor Yellow

    Remove-Item -Force $Destination -ErrorAction SilentlyContinue

    $bitsDl = Start-BitsTransfer $FileUri -Destination $Destination -Asynchronous

    while (($bitsDL.JobState -eq 'Transferring') -or ($bitsDL.JobState -eq 'Connecting')) {
        Write-Progress -Activity "Downloading: $AppName" -Status "$([math]::round($bitsDl.BytesTransferred / 1mb))mb / $([math]::round($bitsDl.BytesTotal / 1mb))mb" -PercentComplete ($($bitsDl.BytesTransferred) / $($bitsDl.BytesTotal) * 100 )
    }

    Switch ($bitsDl.JobState) {

        'Transferred' {
            Complete-BitsTransfer -BitsJob $bitsDl
            Break
        }

        'Error' {
            write-host 'Erreur de téléchargement du média d installation.'
        }
    }
}


# User builds can only be installed on Windows systems
If ($BuildEdition.EndsWith('User') -and -not ($IsWindows -or $PSVersionTable.PSVersion.Major -lt 6)) {
    write-host 'Les builds des utilisateurs ne sont pas disponibles pour les systèmes non Windows.'
}

Try {
    $prevProgressPreference = $ProgressPreference
    $ProgressPreference = 'SilentlyContinue'

    # Obtenir les informations nécessaires à l'installation
    $codePlatformInfo = Get-CodePlatformInformation -Bitness $Architecture -BuildEdition $BuildEdition

    # Télécharger le programme d'installation
    $tmpdir = [System.IO.Path]::GetTempPath()

    $ext = $codePlatformInfo.Extension
    $installerName = "vscode-install.$ext"

    $installerPath = [System.IO.Path]::Combine($tmpdir, $installerName)

    If ($PSVersionTable.PSVersion.Major -le 5) {
        Save-WithBitsTransfer -FileUri $codePlatformInfo.FileUri -Destination $installerPath -AppName $codePlatformInfo.AppName
    }
    # We don't want to use RPM packages -- see the installation step below
    Elseif ($codePlatformInfo.Extension -ne 'rpm') {
        If ($PSCmdlet.ShouldProcess($codePlatformInfo.FileUri, "Invoke-WebRequest -OutFile $installerPath")) {
            Invoke-WebRequest -Uri $codePlatformInfo.FileUri -OutFile $installerPath
        }
    }

    # Installer le VSCode
    $exeArgs = '/verysilent /tasks=addtopath'
    If ($EnableContextMenus) {
        $exeArgs = '/verysilent /tasks=addcontextmenufiles,addcontextmenufolders,addtopath'
    }

    If (-not $PSCmdlet.ShouldProcess("$installerPath $exeArgs", 'Start-Process -Wait')) {
        Break
    }

    Start-Process -Wait $installerPath -ArgumentList $exeArgs
    Break

    $codeExePath = $codePlatformInfo.ExePath

    # Installer les extensions
    $extensions = @("ms-vscode.PowerShell") + $AdditionalExtensions
    If ($PSCmdlet.ShouldProcess(($extensions -join ','), "$codeExePath --install-extension")) {

        Foreach ($extension in $extensions) {
            Write-Host "`nInstallation de l'extension $extension ..." -ForegroundColor Yellow
            & $codeExePath --install-extension $extension
        }

    }

    # Lancement si demandé
    If ($LaunchWhenDone) {
        $appName = $codePlatformInfo.AppName

        If (-not $PSCmdlet.ShouldProcess($appName, "Lancer avec $codeExePath")) {
            Return
        }

        Write-Host "`nInstallation complète, démarrage $appName...`n`n" -ForegroundColor Green
        & $codeExePath
        Return
    }

    If ($PSCmdlet.ShouldProcess('Installation est terminée!', 'Write-Host')) {
        Write-Host "`nInstallation est terminée!`n`n" -ForegroundColor Green
    }
}
Finally {
    $ProgressPreference = $prevProgressPreference
}