#!/bin/bash

#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.

# Usage:
#   ./verify_brooklyn_rc.sh <release>
#
# e.g. `verify_brooklyn_rc.sh 0.10.0-rc1`

set -ex

RELEASE=$1
RELEASE_GA=$(echo $RELEASE | perl -pe 's/(.*)-rc.*/$1/');

if [ "" == "$RELEASE" ]; then
    echo "No release specified as command line argument"
    exit 1
else
    echo "Validating release ${RELEASE} (GA version ${RELEASE_GA})"
fi

if [ -e /sbin/sha1 ]; then
    SHA1SUM="/sbin/sha1 -a 256"
elif [ -e /usr/bin/shasum ]; then
    SHA1SUM="/usr/bin/shasum -a 256"
else
    SHA1SUM="/usr/bin/sha1sum -a 256"
fi

curl https://dist.apache.org/repos/dist/release/brooklyn/KEYS | gpg --import

svn co https://dist.apache.org/repos/dist/dev/brooklyn/apache-brooklyn-$RELEASE

cd apache-brooklyn-$RELEASE

for tarball in `ls *.tar.gz`; do
    # Verify sha256sum
    ACTUAL=`$SHA1SUM ${tarball} | awk '{print $1}'`
    EXPECTED=`cat ${tarball}.sha256 | awk '{print $1}'`
    [ "$ACTUAL" == "${EXPECTED}" ]
    # verify signature
    gpg --verify ${tarball}.asc ${tarball};
    # Untar
    tar -xzf ${tarball};
done

echo "Build from sources ..."
srcdir=apache-brooklyn-${RELEASE_GA}-src
if [ ! -d "${srcdir}" ]; then
    echo "No src dir matching ${srcdir}"
    exit 1
fi
pushd ${srcdir};
#mvn clean install;
popd

echo "Testing vagrant ..."
vagrantdir=apache-brooklyn-${RELEASE_GA}-vagrant
if [ ! -d "${vagrantdir}" ]; then
    echo "No vagrant dir matching ${vagrantdir}"
    exit 1
fi
pushd ${vagrantdir};
vagrant up
curl http://localhost:8081/v1/server/healthy | grep true
vagrant destroy -f
popd

