#!/bin/sh

set -e

PROJECT_VERSION="$1"

if [ -z "$1" ]; then
    echo "No version supplied"
    exit 1
fi

if ! command -v "make" &>/dev/null; then
    echo "please install make for running the build steps"
    exit 1
fi

if ! command -v "ruff" &>/dev/null; then
    echo "please install ruff for formatting"
    exit 1
fi

if [ "$(git tag -l "${PROJECT_VERSION}")" ]; then
    echo "Version: ${PROJECT_VERSION} already has a tag"
    exit 1
fi

# First check if there are changes
if [[ $(git diff) ]]; then
   echo "There are changes, commit them before releasing"
   exit 1
fi

# Format all Python files
make fmt
if [[ $(git diff) ]]; then
    git add -u
    git commit -m "Format: Run Ruff"
fi

# Update debian changelog
dch -v ${PROJECT_VERSION} --distribution unstable "New version"

# Update fedora spec
sed -i "s/^Version:.*/Version:        ${PROJECT_VERSION}/" rpm/SPECS/python-eduvpn-client.spec
# We set the author and email the same as debian's
sed -i "/^%changelog/a * $(LC_ALL=C date +'%a %b %d %Y') ${DEBFULL_NAME} <${DEBEMAIL}> - ${PROJECT_VERSION}-1\n- New version\n" rpm/SPECS/python-eduvpn-client.spec

# Replace version number
sed -i "s/version = .*/version = ${PROJECT_VERSION}/" setup.cfg
sed -i "s/__version__ = \".*\"/__version__ = \"${PROJECT_VERSION}\"/" eduvpn/__init__.py

git add -u
git commit -m "Version: Update to ${PROJECT_VERSION}"
