#!/bin/bash

VERSION=$(grep Bundle-Version "$WORKSPACE"/core/plugins/org.eclipse.hawk.core/META-INF/MANIFEST.MF | \
              cut --delim=: -f2 | \
              sed -re 's/ *([0-9]+)[.]([0-9]+)[.].*/\1.\2.0/')
DIST_DIR="/home/data/httpd/download.eclipse.org/hawk/$VERSION"
CLIENT_DIR="$DIST_DIR/client"
SERVER_DIR="$DIST_DIR/server"
SSH_USER=genie.hawk@projects-storage.eclipse.org

echo "Creating downloads for Hawk Server ${VERSION} at ${DIST_DIR}"

# Use rsync with delete rather than a straight up 'rm', in case SSH fails intermittently
ssh "$SSH_USER" mkdir -p "$CLIENT_DIR"
rsync -rvhz "$WORKSPACE/server/releng/org.eclipse.hawk.service.client.updatesite/target/repository/" "$SSH_USER":"${CLIENT_DIR}/" --delete
ssh "$SSH_USER" mkdir -p "$SERVER_DIR"
rsync -rvhz "$WORKSPACE/server/releng/org.eclipse.hawk.service.server.updatesite/target/repository/" "$SSH_USER":"${SERVER_DIR}/" --delete

# Delete the old client+server zipped update site
ssh "$SSH_USER" rm -f "${DIST_DIR}"/org.eclipse.hawk.service.updatesite-*.zip

# Copy the update site (version-based)
scp "$WORKSPACE"/server/releng/org.eclipse.hawk.service.client.updatesite/target/org.eclipse.hawk.service.client.updatesite-*.zip "$SSH_USER":"${DIST_DIR}/"
scp "$WORKSPACE"/server/releng/org.eclipse.hawk.service.server.updatesite/target/org.eclipse.hawk.service.server.updatesite-*.zip "$SSH_USER":"${DIST_DIR}/"

# Refresh the server/CLI products (timestamped, so we need to remove old ones)
ssh "$SSH_USER" rm -f "${DIST_DIR}/"hawk-server-nogpl_*.zip
ssh "$SSH_USER" rm -f "${DIST_DIR}/"hawk-cli_*.zip
scp "$WORKSPACE"/server/releng/org.eclipse.hawk.service.server.product/target/products/hawk-server-nogpl_*.zip "$SSH_USER":"${DIST_DIR}/"
scp "$WORKSPACE"/server/releng/org.eclipse.hawk.service.cli.product/target/products/hawk-cli_*.zip "$SSH_USER":"${DIST_DIR}/"

# Upload Thrift stub sources as well
pushd "$WORKSPACE"/server/plugins/org.eclipse.hawk.service.api
HAWK_THRIFT_JS="hawk-thrift-js-$VERSION.tar.gz"
HAWK_THRIFT_CPP="hawk-thrift-cpp-$VERSION.tar.gz"
HAWK_THRIFT_PY="hawk-thrift-py-$VERSION.tar.gz"
tar czf "$HAWK_THRIFT_JS" src-gen-js
tar czf "$HAWK_THRIFT_CPP" src-gen-cpp
tar czf "$HAWK_THRIFT_PY" src-gen-py
scp "$HAWK_THRIFT_JS" "$SSH_USER":"$DIST_DIR/"
scp "$HAWK_THRIFT_CPP" "$SSH_USER":"$DIST_DIR/"
scp "$HAWK_THRIFT_PY" "$SSH_USER":"$DIST_DIR/"
popd
