#!/usr/bin/env bash
set -euo pipefail

if [ $# -ne 1 ]; then
    echo "Usage: $0 <version>"
    echo "  e.g. $0 0.2.0"
    exit 1
fi

VERSION="$1"

# Validate semver
if ! echo "$VERSION" | grep -qP '^\d+\.\d+\.\d+$'; then
    echo "error: version must be semver (e.g. 0.2.0)"
    exit 1
fi

# Must be on main
BRANCH=$(git rev-parse --abbrev-ref HEAD)
if [ "$BRANCH" != "main" ]; then
    echo "error: releases must be made from main (currently on $BRANCH)"
    exit 1
fi

# Working tree must be clean
if ! git diff --stat --exit-code; then
    echo "error: working tree has uncommitted changes"
    exit 1
fi
if ! git diff --cached --stat --exit-code; then
    echo "error: staged but uncommitted changes"
    exit 1
fi

# Tag must not already exist
if git tag -l "v$VERSION" | grep -q .; then
    echo "error: tag v$VERSION already exists"
    exit 1
fi

echo "==> Bumping version to $VERSION in Cargo.toml"
sed -i "s/^version = \".*\"/version = \"$VERSION\"/" Cargo.toml

echo "==> Running cargo test"
cargo test 2>&1 | tail -5

echo "==> Running cargo build --release"
cargo build --release 2>&1 | tail -3

echo "==> Committing release: v$VERSION"
git add Cargo.toml Cargo.lock
git commit -m "release: v$VERSION"

echo "==> Tagging v$VERSION"
git tag -a "v$VERSION" -m "release: v$VERSION"

echo "==> Building release site with abbaye"
if command -v abbaye &>/dev/null; then
    rm -rf public/
    abbaye build 2>&1 || echo "warning: abbaye build failed"
else
    echo "warning: abbaye not found, skipping site build"
fi

echo "==> Uploading to server"
read -r -p "Upload public/ to ololduck@vit.am:public_html/search_hub/? [y/N] " REPLY
if [[ "$REPLY" =~ ^[Yy]$ ]]; then
    rsync -avz --progress public/ ololduck@vit.am:public_html/search_hub/ 2>&1
fi
echo ""
echo "Release v$VERSION ready."
echo "To publish:  git push --tags origin main"
echo "To upload:   rsync -avz --progress public/ ololduck@vit.am:public_html/search_hub/"
echo "To undo:     git tag -d v$VERSION && git reset --soft HEAD~1"
