#!/usr/bin/env bash

set -ex

if [ -z "${BLOB_NAME}" ]; then
  echo "must specify \$BLOB_NAME" >&2
  exit 1
fi

if [ -z "${BLOB_DESTINATION}" ]; then
  echo "must specify \$BLOB_DESTINATION" >&2
  exit 1
fi

if [ -z "${BLOB_VERSION_FILE}" ] ; then
  echo "must specify \$BLOB_VERSION_FILE" >&2
  exit 1
fi

if [ -z "${BLOB_DOWNLOAD_FILENAME}" ] ; then
  BLOB_DOWNLOAD_FILENAME=*.tar.gz
fi

blob_dir=${PWD}/blob-dir
blob=${blob_dir}/${BLOB_DOWNLOAD_FILENAME}
blobsha=$(sha1sum ${blob} | cut -d' ' -f1)

blob_version=$(cat ${blob_dir}/${BLOB_VERSION_FILE})

git clone bosh-release bumped-bosh-release

set +x
echo "${BOSH_PRIVATE_CONFIG}" > bumped-bosh-release/config/private.yml
set -x

pushd bumped-bosh-release
  # Ensuring client-side cache matches director blobs
  bosh sync-blobs

  if "bosh -n blobs | grep ${blobsha}"; then
    echo "Blob already present."
    exit 0
  fi
  # work-around Go BOSH CLI trying to rename blobs downloaded into ~/.root/tmp
  # into release dir, which is invalid cross-device link
  export HOME=${PWD}

  git config --global user.name "CF BPM"
  git config --global user.email "cf-bpm+blob-bumper@pivotal.io"

  bosh -n add-blob ${blob} ${BLOB_DESTINATION}/${BLOB_NAME}
  bosh -n upload-blobs

  git add config/blobs.yml
  git commit -m "update ${BLOB_NAME} blob to ${blob_version}"
popd
