public/Read-ChocolateyUpdateConfig.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
function Read-ChocolateyUpdateConfig() {
    Param(
        [Parameter(Position = 0, ValueFromPipeline = $true)]
        [String] $Uri,

        [switch] $Decrypt,

        [byte[]] $DecryptKey
    )

    $configDir = "$HOME/.config/nerdymishka/chocolatey"
    if([string]::IsNullOrWhiteSpace($Uri)) {
        $Uri = $Env:ChocolateyUpdateConfig
        if(!$Uri) {
            $Uri = $Env:CHOCOLATEY_UPDATE_CONFIG
        }
    }

    if(!$Uri) {
        if(Test-Path "$configDir/config.json") {
            $Uri = "$configDir/config.json"
        }
    }

    if(!$Uri) {
        Write-Warning "Uri for the configuration must be set";
        return;
    }

    if($Uri.StartsWith("./")) {
        $Uri = (Resolve-Path $Uri).Path
    }

    $test = [Uri]$Uri
    if(!$test.IsFile) {
        $content = Get-WebRequestContentAsString -Uri $Uri
    } else {
        $content = Get-Content $Uri -Raw
    }

    if($DecryptKey -or $Decrypt.ToBool()) {
        $canDecrypt = $null -ne (Get-Command Unprotect-String -ErrorAction SilentlyContinue)
        if(!$canDecrypt) {
            Write-Warning "Unprotect-String is required to decrypt data"
            return;
        }
        if(!$DecryptKey) {
            $DecryptKey = Get-ChocolateyDecryptKey
            if(!$DecryptKey) {
                Write-Warning "DecryptKey is required to decrypt data."
                return;
            }
        }

        $content = Unprotect-String -PrivateKey $DecryptKey -EncryptedValue $content
    }

    return $content | ConvertFrom-Json 
}