#!/bin/bash

set -e

function print_done { printf "\e[1;32m☑  %s\e[m\n" "$1"; }
function print_todo { printf "\e[1;32m☐  %s\e[m\n" "$1"; }
function changelog_jessie_low { dch --force-distribution --distribution jessie --urgency low --newversion "$1" 2>/dev/null; }
function changelog_get_version { echo "$(dpkg-parsechangelog | grep Version: | cut -d' ' -f2-)"; }
function changelog_get_mtime { echo "$(stat -c%y debian/changelog)"; }

NORIS_MAILGREP_WEB_CURRENT_VERSION="$(changelog_get_version)"

read -p "Enter next debian version number (current: $NORIS_MAILGREP_WEB_CURRENT_VERSION): " NORIS_MAILGREP_WEB_NEXT_VERSION

CHANGELOG_MTIME_BEFORE=$(changelog_get_mtime)
changelog_jessie_low "$NORIS_MAILGREP_WEB_NEXT_VERSION"
CHANGELOG_MTIME_AFTER=$(changelog_get_mtime)

if [ "$CHANGELOG_MTIME_BEFORE" == "$CHANGELOG_MTIME_AFTER" ]; then
    echo "You didn't edit the changelog. Exiting…"
    exit 0
fi

git add debian/changelog
print_done "Created debian/changelog"

git commit -m "Release $NORIS_MAILGREP_WEB_NEXT_VERSION" --quiet
print_done "Git: Commit debian/changelog"

git tag -a "$NORIS_MAILGREP_WEB_NEXT_VERSION" -m "Release $NORIS_MAILGREP_WEB_NEXT_VERSION"
print_done "Git: Tag $NORIS_MAILGREP_WEB_NEXT_VERSION"

read -p "Do you want to build a debian package now (y/n)? " NORIS_MAILGREP_WEB_BUILD_DEB
if [[ $NORIS_MAILGREP_WEB_BUILD_DEB =~ ^[Yy]$ ]] ; then
    debuild

    CHANGES_FILE="../noris-mailgrep-web_${NORIS_MAILGREP_WEB_NEXT_VERSION}_amd64.changes"
    print_todo "Upload the package ($CHANGES_FILE) to the debarchiver"
    print_todo "Run ansible / Wait for CD to deploy."
fi
