#!/usr/bin/env bash

#
# blackbox_addadmin -- Add an admin to the system
#

# Example:
#    blackbox_addadmin tal@example.com
#

set -e
blackbox_home=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
source ${blackbox_home}/_blackbox_common.sh
source ${blackbox_home}/_stack_lib.sh

fail_if_not_in_repo

KEYNAME="$1"
: ${KEYNAME:?ERROR: First argument must be a keyname (email address)} ;

# The second argument, if present, is the directory to find the GPG keys to be imported.
if [[ "$2" == "" ]]; then
  GPGEXPORTOPTIONS=""
else
  GPGEXPORTOPTIONS=--homedir="${2}"
fi
# TODO(tlim): This could probably be done with GNUPGHOME
# but that affects all commands; we just want it to affect the key export.


# Add the email address to the BB_ADMINS file.  Remove any duplicates.
# The file must exist for sort to act as we expect.
touch "$BB_ADMINS"
sort  -fdu -o "$BB_ADMINS" <(echo "$1") "$BB_ADMINS"


# Add the user's key to the keychain.

# Extract it:
make_self_deleting_tempfile pubkeyfile
gpg $GPGEXPORTOPTIONS --export -a "$KEYNAME" >"$pubkeyfile"
if [[ $(wc -l < "$pubkeyfile") = 0 ]]; then
  fail_out "GPG key '$KEYNAME' not found.  Please create it with: gpg --gen-key"
  exit 1
fi

# Import it:
gpg --no-permission-warning --homedir="$KEYRINGDIR" --import "$pubkeyfile"
vcs_add "$KEYRINGDIR/pubring.gpg" "$KEYRINGDIR/trustdb.gpg" "$BB_ADMINS"

# Make a suggestion:
echo
echo
echo 'NEXT STEP: You need to manually check these in:'
echo '     ' $VCS_TYPE commit -m\'NEW ADMIN: $KEYNAME\' "$BLACKBOXDATA/pubring.gpg" "$BLACKBOXDATA/trustdb.gpg" "$BLACKBOXDATA/$BB_ADMINS_FILE"
