#!/usr/bin/env bash

set -o errexit
set -o nounset
set -o pipefail

if [ -z "$SOURCE_TARBALL_URL" ]
then
  echo "\$SOURCE_TARBALL_URL env not set"
  exit 1
fi

if [ -z "$OUTPUT_TARBALL" ]
then
  echo "\$OUTPUT_TARBALL env not set"
  exit 1
fi

PROJECT_NAME="3scale-operator"

echo "Download sources and extract ${SOURCE_TARBALL_URL}"
SOURCES_TARBALL=/tmp/${SOURCE_TARBALL_URL##*/}
curl -L ${SOURCE_TARBALL_URL} -o ${SOURCES_TARBALL}
NEW_TMP_DIR=`mktemp -d`
tar -C ${NEW_TMP_DIR} -xvf ${SOURCES_TARBALL}
mv ${NEW_TMP_DIR}/${PROJECT_NAME}{-*,}

# package licenses
# archive only files, dirs and symlinks
find ${NEW_TMP_DIR}/${PROJECT_NAME} -type f -name licenses.xml -printf "%P\n" \
    | tar -czf ${OUTPUT_TARBALL} --dereference --no-recursion -C ${NEW_TMP_DIR}/${PROJECT_NAME} -T -

rm -rf ${NEW_TMP_DIR}
