#!/bin/bash
set -euE
set -o pipefail

PACKAGE=thin-provisioning-tools
REPO="https://github.com/jthornber/thin-provisioning-tools.git"

error() {
  echo "$@" >&2
  exit 1
}

if [[ $(git rev-parse --abbrev-ref HEAD) != master ]]; then
  error "Current branch is not master!"
fi
if [[ $(git remote get-url upstream) != ${REPO} ]]; then
  error "Need remote called 'upstream' pointing to ${REPO}!"
fi

version=$1
tag="v${version}"
tag_id=$(git ls-remote --quiet --tags --exit-code upstream ${tag} | awk '{ print $1 }')
commit_id=$(git log -1 --pretty=%H ${tag_id})
tar=../${PACKAGE}_${version}.orig.tar.xz

if [ -e ${tar} ]; then
  error "${tar} already exists!"
fi

git fetch upstream master
git tag upstream/${version} ${commit_id}

git archive --format=tar --prefix=${PACKAGE}-${version}/ ${commit_id} | xz > ${tar}
pristine-tar commit ${tar} ${commit_id}

git update-ref refs/heads/upstream ${commit_id}
git-dpm record-new-upstream ${tar} ${commit_id}

dch -v ${version}-1 "New upstream release."
git add debian/changelog
git commit --amend --message "Import ${version}"

git-dpm rebase-patched
