#!/bin/bash

set -eu

###########
# Helpers #
###########
show_help() {
  cat << EOF
Usage: [-c] [-p] [-b] [-u] VERSION

Prepare, build and upload a new release

   -c  clean the current directory
   -p  prepare the release
   -b  build artefacts (pypi and debian)
   -u  upload the release
EOF
}


########################
# Command line parsing #
########################
FULL=1
CLEAN=0
PREPARE=0
BUILD=0
UPLOAD=0


while getopts "bcpuh" opt; do
  case $opt in
    c)
      CLEAN=1
      FULL=0
      ;;
    p)
      PREPARE=1
      FULL=0
      ;;
    b)
      BUILD=1
      FULL=0
      ;;
    u)
      UPLOAD=1
      FULL=0
      ;;
    h)
      show_help
      exit 0
      ;;
    ?)
      show_help >&2
      exit 1
  esac
done
shift "$((OPTIND-1))"

if [ "$FULL" = "1" ]
then
  BUILD=1
  CLEAN=1
  PREPARE=1
  UPLOAD=1
fi

TAG="$*"

if [ "$PREPARE" = "1" -a "$TAG" = "" ]
then
  echo "Missing version" >&2
  show_help >&2
  exit 1
fi

# clean
if [ "$CLEAN" = "1" ]
then
  echo "Cleaning..."
  rm -rf build-area dist lavacli.egg-info
  echo "done"
  echo
fi

# Prepare the release
if [ "$PREPARE" = "1" ]
then
  echo "Preparing..."
  echo "* debian/changelog"
  read
  gbp dch --new-version="$TAG-1" --release --commit --commit-msg="Prepare for release v$TAG"
  echo "* lavacli/__about__.py version"
  read
  edit lavacli/__about__.py
  git commit --amend lavacli/__about__.py --message="Prepare for release v$TAG"
  echo "* git tag"
  read
  git tag --annotate --sign "v$TAG"
  echo "done"
  echo
fi

# Build the release artefacts
if [ "$BUILD" = "1" ]
then
  echo "Building..."
  python3 setup.py sdist
  gbp buildpackage -us -uc
  echo "done"
  echo
fi

if [ "$UPLOAD" = "1" ]
then
  echo "Uploading..."
  # Push the release
  echo "* git push --tags origin master"
  read
  git push --tags origin master
  # Uploading to pypi.org
  echo "* twine upload dist"
  read
  twine upload dist/*
  echo "done"
  echo
fi
