#!/usr/bin/env bash
set -e

## CLI PARSING

usage() {
    cat >&2 <<EOF
usage: tools/checkout-keystore

Temporarily decrypt the keystore file for signing an Android release.

By using this, a release manager can ensure that the secrets are only
accessible for short periods when they're explicitly thinking about a
release.

This primarily guards against accidents: no slip of the keyboard,
no sharp-edged tool with surprising behavior in an edge case, and
no outright buggy tool can cause a validly-signed release build
unless the release manager has decrypted the key.

Setup:

 * You'll need the \`sq\` command installed, the CLI for Sequoia PGP,
   which is a modern implementation of OpenPGP.

 * The decryption key is expected by default at a path
   ~/.config/sq/KEYNAME.key.pgp , where KEYNAME defaults to \$USER.

   KEYNAME can be set with \`git config zulip.keystoreKeyName\`.
   The directory ~/.config can be overridden by \$XDG_CONFIG_HOME.

 * See also setup instructions in docs/howto/release.md .

EOF
    exit 2
}

if (( ${#} )); then
    usage
fi


## EXECUTION

rootdir=$(git rev-parse --show-toplevel)
cleartext="${rootdir}"/android/release.keystore
cryptotext="${rootdir}"/android/release.keystore.pgp

key_name=$(git config zulip.keystoreKeyName || echo "${USER}")
sq_user_dir="${XDG_CONFIG_HOME:-${HOME}/.config}"/sq
recipient_key="${sq_user_dir}"/"${key_name}".key.pgp

# `sq decrypt` prints obnoxious, confusing output about the key file
# to stderr.  Filter that out (as a normal pipe-style filter, from
# stdin to stdout.)
filter_sq_stderr() {
    grep -vE '^(Compressed|Encrypted) '
}

sq decrypt --recipient-key "${recipient_key}" \
  -o "${cleartext}" "${cryptotext}" \
  2> >(filter_sq_stderr >&2)

wait_min=15
(
    sleep "$(( ${wait_min} * 60 ))"
    rm -f "${cleartext}"
) &

cat >&2 <<EOF

Wrote decrypted file: ${cleartext}

This file will be deleted in ${wait_min} minutes.
EOF
