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

# Usage:
# SONATYPE_USER=<sonatype user> SONATYPE_PW=<sonatype pw> PGP_PW=<pgp pw> PGP_SECRET=<pgp secret> ./sbtPublish <publish cmd>

# Release command:
RELEASE_CMD="${1:?Missing publish command}"

# Make sure required environment variable are set
# Sonatype credentials are only used by sonaUpload. If run by itself, publishSigned
# only stages locally so runs that only sign and don't push (like when you run in
# a fork) don't need the Sonatype account creds.
if [[ "$RELEASE_CMD" == *sonaUpload* ]]; then
  : "${SONATYPE_USER:?not set}"
  : "${SONATYPE_PW:?not set}"
fi
: "${PGP_PW:?not set}"
: "${PGP_SECRET:?is not set}"

if [ ! "$NIGHTLYBUILD" = "yes" ] && [ ! "$RELEASEBUILD" = "yes" ]; then
    echo "Neither NIGHTLYBUILD nor RELEASEBUILD env var set to \"yes\""
    exit 1
fi

# Setup gpg (disabled, we use bouncycastle instead)
# export GPG_TTY="$(tty)"
# echo "$PGP_SECRET" | gpg --batch --import

# Setup bouncycastle instead of gpg to do signing, because gpg explodes when
# doing too many signing requests in parallel (https://github.com/sbt/sbt-pgp/issues/168)
sbtGpgDir="${HOME}/.sbt/gpg"
mkdir -p "$sbtGpgDir"
echo "$PGP_SECRET" > "$sbtGpgDir/secring.asc"

# run sbt with the supplied arg
SBT="$(cd "$(dirname "${BASH_SOURCE[0]}")" >& /dev/null && pwd)/sbt"
"$SBT" "$RELEASE_CMD"
