#!/usr/bin/env bash
#
# Don't forget to update Cargo.toml with the right version before running
#

set -e

AUR_REPO=ssh://aur@aur.archlinux.org/sworkstyle.git

VERSION=$1

if [[ ! $VERSION =~ ^[0-9]*\.[0-9]*\.[0-9]*$ ]]; then
  echo "No version given"
  exit 1
fi

check_cargo() {
  echo "Cargo: validating"
  if ! test -f ~/.cargo/credentials; then
    echo "~/.cargo/credentials does not exist"
    exit 1
  fi
  cargo publish --dry-run
}

check_github() {
  echo "Github: validating"
  gh auth status
}

release_github() {
  echo "Github: creating release"
  gh release create $VERSION
}

release_cargo() {
  echo "Cargo: publishing"
  cargo publish
}

release_aur() {
  echo "AUR: creating temp"
  mkdir -p tmp
  cd tmp

  echo "AUR: cloning and modifiying pkgver"
  git clone $AUR_REPO .
  sed -i "s/pkgver=.*/pkgver=$VERSION/g" PKGBUILD
  makepkg --printsrcinfo > .SRCINFO
  git add .
  git commit -m "Upgraded to version $VERSION"
  git push

  echo "AUR: removing tmp"
  cd ..
  rm -rf tmp
}

check_cargo
check_github

git tag $VERSION
git push origin --tags

release_github
release_cargo
release_aur

echo "Release finished!"