#!/bin/bash

cd $(git rev-parse --show-toplevel)

./scripts/backquote_as_links.py

glow RELEASE_NOTES.md || exit "Can't find the release notes"

ver_line=$(grep version pyproject.toml | head -n 1)
echo $ver_line
echo -n "New version: "
read version
echo -n "Release name: "
read title

if [ -z "$title" ]; then
    title="$version"
fi

TOKEN=$(gopass show -o websites/api.github.com/fdev31)
URL=https://api.github.com/repos/hyprland-community/pyprland

tox run -e unit || exit -1

# Bump py project {{{
sed -i "s#$ver_line#version = \"$version\"#" pyproject.toml
git add pyproject.toml
V="$version" ./scripts/update_version
git add pyprland/version.py
git commit -m "Version $version"  --no-verify
git tag $version
git push

rm -fr dist
# Build sdist + pure Python wheel (opt out of the native client so the
# cross platform wheel stays pure python)
PYPRLAND_BUILD_NATIVE=0 uv build
# Build platform-specific wheel with statically compiled C client
PYPRLAND_BUILD_NATIVE=1 uv build --wheel
uv publish -u $PYPI_USERNAME -p $PYPI_PASSWORD
# }}}

# Make the release
#
rel_id=$(curl -s -X POST $URL/releases \
        -H "Accept: application/vnd.github+json" \
        -H "Authorization: Bearer ${TOKEN}" \
        -H "X-GitHub-Api-Version: 2022-11-28" \
        -d @- <<EOF | jq .id
{
  "tag_name": "${version}",
  "target_commitish": "main",
  "name": "${title}",
  "body": $(jq -Rs . < RELEASE_NOTES.md),
  "draft": false,
  "prerelease": false,
  "generate_release_notes": false
}
EOF
)

echo "RELEASE ID: $rel_id"

echo "Waiting 15s for pypi to update..."
for n in $(seq 15); do
    echo $n
    sleep 1
done

pushd scripts
./update_get-pypr.sh
git commit get-pypr ../pyprland/command.py -m "Update get-pypr script" --no-verify
git push
popd

pushd ../aurPkgs/pyprland/
echo $version | bumpAurPkg.sh
popd

echo "" >RELEASE_NOTES.md
exit 0
# Upload the standalone version

http -j POST "https://uploads.github.com/repos/hyprland-community/pyprland/releases/${rel_id}/assets?name=pypr" \
    "Accept: application/vnd.github+json" \
    "Authorization: Bearer ${TOKEN}" \
    "X-GitHub-Api-Version: 2022-11-28" \
    "Content-Type: application/octet-stream" < dist/pypr
