// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.

package libkb

import "strings"

var apiCAOverrideForTest = ""

// GetBundledCAsFromHost returns in root CA in []byte for given host, or nil if
// no matching CA is found for host.
func GetBundledCAsFromHost(host string) (rootCA []byte, ok bool) {
	host = strings.TrimSpace(strings.ToLower(host))
	realAPICA := APICA
	if len(apiCAOverrideForTest) > 0 {
		realAPICA = apiCAOverrideForTest
	}
	switch {
	case (host == "api.keybase.io" || host == "api-0.core.keybaseapi.com" || host == "api-1.core.keybaseapi.com"):
		return []byte(realAPICA), true

	// Staging CA.
	case strings.HasSuffix(host, "dev.keybase.io"),
		strings.HasSuffix(host, "dev.keybaseapi.com"):
		return []byte(KBFSDevCA), true

	// Prod CA.
	case strings.HasSuffix(host, "kbfs.keybase.io"),
		strings.HasSuffix(host, "kbfs.keybaseapi.com"):
		return []byte(KBFSProdCA), true

	// We have services using both CAs on this domain, so need to bundle both.
	case strings.HasSuffix(host, "core.keybase.io"),
		strings.HasSuffix(host, "core.keybaseapi.com"):
		return []byte(realAPICA + KBFSProdCA), true

	default:
		return nil, false
	}
}

const APICA = `
-----BEGIN CERTIFICATE-----
MIIGIzCCBAugAwIBAgIJAPzhpcIBaOeNMA0GCSqGSIb3DQEBCwUAMIGMMQswCQYD
VQQGEwJVUzELMAkGA1UECBMCTlkxETAPBgNVBAcTCE5ldyBZb3JrMRQwEgYDVQQK
EwtLZXliYXNlIExMQzEXMBUGA1UECxMOQ2VydCBBdXRob3JpdHkxLjAsBgNVBAMM
JWtleWJhc2UuaW8vZW1haWxBZGRyZXNzPWNhQGtleWJhc2UuaW8wIBcNMjMxMjMx
MTkwMzE5WhgPNjAyMzEyMzExOTAzMTlaMIGMMQswCQYDVQQGEwJVUzELMAkGA1UE
CBMCTlkxETAPBgNVBAcTCE5ldyBZb3JrMRQwEgYDVQQKEwtLZXliYXNlIExMQzEX
MBUGA1UECxMOQ2VydCBBdXRob3JpdHkxLjAsBgNVBAMMJWtleW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Dk
skv6/B1fpes0ctZM/JV99FrKDqq7eWnAlsF0e6GdnWL5MNOW0UupPK8edcDjr9op
cULw/+/2Hp60r50L1WWIcYEjrVmGIMpybrX1eqNilpJSjgrhX0ZqtiHh03+DcxXw
kZHxDQZf1bn+WwMxy0nb6YNBwcBXZEePb4S5KKy4V0T10YEDv7oOMrF6wIy/MxtU
wXHjIp+cd+lZkMngsGYZQExt9dq2BVmAncUiXj4ZAGQjpgSjaEuFkKDxEnRU908n
s+ljmQv1mMwPJqVyR+VIcwmAzhDSK1bwRpKgPjhkB10fBbiqPVllPuU40lSWCGEA
JB1KvwsOTY92T/h43MIeXWD2q1yzLtNmXp434uTUiZZwu2rFUYJTwagGp+z7d8TO
Zdjxkm8d4rsrfgqIWXdOQejJwYm8+LpRiOcUNpA47JR5l+HQAMQ=
-----END CERTIFICATE-----
` /* ^ created on 9/26/2017; expires on 06/02/7014 */ + `
-----BEGIN CERTIFICATE-----
MIIDkDCCAnigAwIBAgIRAL1MQ3C37AuGO8gFqfhqb9EwDQYJKoZIhvcNAQELBQAw
UTESMBAGCgmSJomT8ixkARkWAmlvMRwwGgYKCZImiZPyLGQBGRYMa2Jmcy5rZXli
YXNlMR0wGwYDVQQDDBRLZXliYXNlIEtCRlMgQ0EgcHJvZDAeFw0xNTExMDgyMzM3
MDFaFw0xNzExMDcyMzM3MDFaMFExEjAQBgoJkiaJk/IsZAEZFgJpbzEcMBoGCgmS
JomT8ixkARkWDGtiZnMua2V5YmFzZTEdMBsGA1UEAwwUS2V5YmFzZSBLQkZTIENB
IHByb2QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCr9ttTzL093jPt
WstzWR19qvLprd778ALqShZYZughuXPULgOck4AQW27vlp1nY8+7sBnWgstzL6Gv
dTQU61e34yOeAFYyKoWPFHyeo/g1y+LANgLdLbeOatOlWyM2sb/f0K3SKpusp/9J
0ylpDyko97MAI28spwX1d7L/qlDV6ryce4GrzElp3J8j3TZ3cju5rEldn8B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