#!/bin/bash
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
# This script is used to publish the official release after a successful
# vote of a release-candidate.

set -e
set -o nounset

# If GPG_TTY is unset, set it to the default tty. Otherwise git will not prompt
# for a passpharse for the GPG-key and silently fail when trying to create signed
# commits/tags.
export GPG_TTY=${GPG_TTY:-$(tty)}

aurora_git_web_url='https://gitbox.apache.org/repos/asf?p=aurora.git'
aurora_svn_dist_url='https://dist.apache.org/repos/dist/release/aurora'
aurora_svn_dev_dist_url='https://dist.apache.org/repos/dist/dev/aurora'

function print_help_and_exit {
cat <<EOF
Apache Aurora release tool.

Usage: $0 [-h] [-r #] [-p | publish]

  -h   Print this help message and exit
  -r   Release candidate number (default: 0)
  -p   Publish (default: dry-run (does not publish anything))
EOF
exit 0
}

publish=0
rc_tag_version=0
while getopts ":hl:r:p" opt; do
  case $opt in
    r)
      rc_tag_version=${OPTARG}
      ;;
    p)
      publish=1
      ;;
    h)
      print_help_and_exit
      ;;
    *  )
      echo "Unknown option: -$OPTARG"
      print_help_and_exit
      ;;
  esac
done

shift $(($OPTIND - 1))
if [[ "${1:-dry-run}" == "publish" ]]; then
  publish=1
fi

# Update local repository
git fetch --all -q
git fetch --tags -q

# Ensure that a signing key is available
if [[ -z "`git config user.signingkey`" ]]; then
  cat <<EOF
Error: No GPG signing key can be found within gitconfig.

To configure one, find your code signing key's ID with

   gpg --list-secret-keys

Then configure it as the signing key for this repository with

   git config --global user.signingkey YOUR_KEY_ID
EOF
  exit 1
fi

# Set the base dir for the script to be the top level of the repository
base_dir=$(git rev-parse --show-toplevel)
# Verify that this is a clean repository
if [[ -n "`git status --porcelain`" ]]; then
  echo "ERROR: Please run from a clean master."
  exit 1
elif [[ "`git rev-parse --abbrev-ref HEAD`" == "master" ]]; then
  echo "ERROR: This script must be run from the released branch."
  exit 1
fi

if [[ "$base_dir" != "$PWD" ]]; then
  echo "Warrning: This script must be run from the root of the repository ${base_dir}"
  cd $base_dir
fi

# Make sure that this is not on a snapshot release
current_version=$(cat .auroraversion | tr '[a-z]' '[A-Z]')
if [[ $current_version =~ .*-SNAPSHOT ]]; then
  echo "ERROR: .auroraversion can not be a 'SNAPSHOT', it is ${current_version}"
  exit 1
else
  major=`echo $current_version | cut -d. -f1`
  minor=`echo $current_version | cut -d. -f2`
  patch=`echo $current_version | cut -d. -f3 | cut -d- -f1`

  current_version="${major}.${minor}.${patch}"
fi

previous_version_tag="${current_version}-rc${rc_tag_version}"
current_version_tag="rel/${current_version}"

# Make sure the tag does not exist
if [[ $(git ls-remote --exit-code --tags origin refs/tags/${current_version} >/dev/null 2>&1) == 0 ]]; then
  echo "ERROR: ${current_version} tag exists."
  exit 1
fi

# All check are now complete, before we start alert if we are in dry-run
if [[ $publish == 0 ]]; then
  echo "Performing dry-run"
fi

dist_name="apache-aurora-${current_version}"
dist_dir=${base_dir}/dist

function print_reset_instructions {
cat <<EOF
To roll back your local repo you will need to run:

  rm -rf ${dist_dir}
EOF
}

# If anything goes wrong from here then print roll back instructions before exiting.
function print_rollback_instructions {
  echo "ERROR: Looks like something has failed while creating the release."
  print_reset_instructions
}
trap print_rollback_instructions EXIT

if [[ $publish == 1 ]]; then
  # Create release branch and tag and push them to the origin
  echo "Creating ${current_version_tag} staging branch"
  git checkout -b "stage_${current_version_tag}"

  # Increment the version and create a branch
  echo ${current_version} > .auroraversion
  git add .auroraversion
  git commit -m "Updating .auroraversion to release version ${current_version}."
  git tag -s "${current_version_tag}" \
    -m "Apache Aurora ${current_version} release" HEAD
  git push origin "${current_version_tag}"
fi

rc_dir=${dist_dir}/rc
release_dir=${dist_dir}/${current_version}
mkdir -p ${rc_dir}
cd ${dist_dir}

# Checkout the release candidate
svn co ${aurora_svn_dev_dist_url}/${previous_version_tag} ${rc_dir} >/dev/null 2>&1

if [[ $publish == 1 ]]; then
  echo "Publishing the release"
  # Make the release dist directory and check it out
  svn mkdir ${aurora_svn_dist_url}/${current_version} -m "aurora-${current_version} release"
  svn co --depth=empty ${aurora_svn_dist_url}/${current_version} ${release_dir}
else
  mkdir ${release_dir}
fi

cd ${release_dir}

# Rename the .auroraversion from -RC[:digit:] to release current_version and repackage the release
tar -xzf ${rc_dir}/apache-aurora-*.tar.gz
mv apache-aurora-* ${dist_name}
echo ${current_version} > ${dist_name}/.auroraversion
tar -czf ${dist_name}.tar.gz ${dist_name}
rm -rf ${dist_name}

# Sign the tarball.
echo "Signing the distribution"
gpg --armor --output ${dist_name}.tar.gz.asc --detach-sig ${dist_name}.tar.gz

# Create the checksums
echo "Creating checksum"
shasum -a 512 ${dist_name}.tar.gz > ${dist_name}.tar.gz.sha512

if [[ $publish == 1 ]]; then
  # Commit the release
  svn add ${dist_name}*
  svn ci -m "aurora-${current_version} release"
fi

cd ${base_dir}

echo
echo "Done creating the release. The following draft email has been created"
echo "to send to the dev@aurora.apache.org mailing list."
echo

# Create the email template for the release to be sent to the mailing lists.
MESSAGE=$(cat <<__EOF__
To: dev@aurora.apache.org
Subject: [RESULT][VOTE] Release Apache Aurora ${current_version} RC${rc_tag_version}

All,
The vote to accept Apache Aurora ${current_version} RC${rc_tag_version}
as the official Apache Aurora ${current_version} release has passed.


+1 (Binding)
------------------------------


+1 (Non-binding)
------------------------------


There were no 0 or -1 votes. Thank you to all who helped make this release.


Aurora ${current_version} includes the following:
---
The CHANGELOG for the release is available at:
${aurora_git_web_url}&f=CHANGELOG&hb=${current_version_tag}

The tag used to create the release with is ${current_version_tag}:
${aurora_git_web_url}&a=shortlog&h=refs/tags/${current_version_tag}

The release is available at:
${aurora_svn_dist_url}/${current_version}/${dist_name}.tar.gz

The SHA-512 checksum of the release can be found at:
${aurora_svn_dist_url}/${current_version}/${dist_name}.tar.gz.sha512

The signature of the release can be found at:
${aurora_svn_dist_url}/${current_version}/${dist_name}.tar.gz.asc

The GPG key used to sign the release are available at:
${aurora_svn_dist_url}/KEYS

__EOF__
)
echo "--------------------------------------------------------------------------------"
echo
echo "${MESSAGE}"
echo
echo "--------------------------------------------------------------------------------"
echo

# Print reset instructions if this was a dry-run
if [[ $publish == 0 ]]; then
  echo
  echo "This is a dry run, nothing has been published."
  echo
  print_reset_instructions
fi

# Unset error message handler and exit
trap '' EXIT
exit 0
