#!/bin/bash
set -eo pipefail

# This file should mostly mirror changes in universe's update-local-secrets

turtle="$(git rev-parse --show-toplevel)"

if [ -n "$1" ] && [ "$1" != '--keyfile-only' ] ; then
  echo "unrecognized option $1"
  exit 1
fi

if [[ $OSTYPE =~ darwin.* ]] && [ "$(fdesetup isactive)" != true ]; then
  cat << EOM
You must have FileVault's full-disk encryption active before downloading secret credentials to your computer. Read this guide to learn how to enable FileVault: https://support.apple.com/en-us/HT204837.

Thank you for helping keep Expo secure.
EOM
  exit 2
fi


gscp_with_headers() {
  url=$1
  dest=$2
  # to have obvious behavior for everyone who runs this, we want to trace the cp
  # but ONLY the cp, because otherwise all sorts of weird subshell shit prints
  gsutil stat "$url" | sed -e 's/^/# /g' > "$dest"
  gsutil cat "$url" >> "$dest"
}

set -x

mkdir -p "$HOME/.expo-internal"

if [ $# = 0 ]; then
  gscp_with_headers gs://expo-secrets/turtle-dev-env-secrets "$turtle/.secrets"
  gscp_with_headers gs://expo-secrets/turtle-dev-env-secrets-prod "$turtle/.secrets.prod"
fi

gsutil cat gs://expo-secrets/turtle-git-crypt-key > "$HOME/.expo-internal/turtle-git-crypt-key"
