#!/bin/bash
#
# Download Go, verify its signature, and if that all succeeds, move the tarball
# to go.tar.gz in the current directory.

set -eu

if [ $# -eq 0 ]; then
  echo "usage: $0 <go version> [platform like linux-amd64]"
  exit 1
fi
VERSION="${1}"
PLATFORM="${2:-linux-amd64}"

export GNUPGHOME="$(mktemp -d)"

# From https://www.google.com/linuxrepositories/
#
# Key Details
#   Download: https://dl.google.com/linux/linux_signing_key.pub
#   Key ID: Google, Inc. Linux Package Signing Key <linux-packages-keymaster@google.com>
#   Fingerprint: 4CCA 1EAF 950C EE4A B839 76DC A040 830F 7FAC 5991
#   Google, Inc. (Linux Package Signing Authority) <linux-packages-keymaster@google.com>
#   Fingerprint: EB4C 1BFD 4F04 2F6D DDCC EC91 7721 F63B D38B 4796
gpg2 --import <<EOF
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1.4.2.2 (GNU/Linux)

mQGiBEXwb0YRBADQva2NLpYXxgjNkbuP0LnPoEXruGmvi3XMIxjEUFuGNCP4Rj/a
kv2E5VixBP1vcQFDRJ+p1puh8NU0XERlhpyZrVMzzS/RdWdyXf7E5S8oqNXsoD1z
fvmI+i9b2EhHAA19Kgw7ifV8vMa4tkwslEmcTiwiw8lyUl28Wh4Et8SxzwCggDcA
feGqtn3PP5YAdD0km4S4XeMEAJjlrqPoPv2Gf//tfznY2UyS9PUqFCPLHgFLe80u
QhI2U5jt6jUKN4fHauvR6z3seSAsh1YyzyZCKxJFEKXCCqnrFSoh4WSJsbFNc4PN
b0V0SqiTCkWADZyLT5wll8sWuQ5ylTf3z1ENoHf+G3um3/wk/+xmEHvj9HCTBEXP
78X0A/0Tqlhc2RBnEf+AqxWvM8sk8LzJI/XGjwBvKfXe+l3rnSR2kEAvGzj5Sg0X
4XmfTg4Jl8BNjWyvm2Wmjfet41LPmYJKsux3g0b8yzQxeOA4pQKKAU3Z4+rgzGmf
HdwCG5MNT2A5XxD/eDd+L4fRx0HbFkIQoAi1J3YWQSiTk15fw7RMR29vZ2xl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Y BLOCK-----
-----BEGIN PGP PUBLIC KEY BLOCK-----

[encoded data, 8385 characters]
eBqxcHwQ
=4zaS
-----END PGP PUBLIC KEY BLOCK-----
EOF


OUTPUT_DIR="$(mktemp -d)"
FILENAME="go${VERSION}.${PLATFORM}.tar.gz"
OUTPUT_FILE="${OUTPUT_DIR}/${FILENAME}"
curl -sSL "https://dl.google.com/go/${FILENAME}.asc" -o "${OUTPUT_FILE}.asc"
curl -sSL "https://dl.google.com/go/${FILENAME}" -o "${OUTPUT_FILE}"

gpg2 --verify --trust-model=always "${OUTPUT_FILE}.asc" "${OUTPUT_FILE}"

mv "${OUTPUT_FILE}" go.tar.gz

rm -r "${OUTPUT_DIR}"
rm -r "${GNUPGHOME}"
