name: Release new version

on:
  push:
    tags:
      - '[0-9]+.[0-9]+.[0-9]+'

jobs:
  release:
    name: Build and publish a release
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - name: Install Dependencies
        run: |
          head -v -n-0 /etc/apt/sources.list || :
          head -v -n-0 /etc/apt/sources.list.d/* || :
          # Workaround for https://github.com/orgs/community/discussions/120966
          sudo rm -f /etc/apt/sources.list.d/microsoft-prod.list
          # Workaround for apparmor breaking bwrap by disabling unpriv userns
          sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
          sudo systemctl reload apparmor
          # Dependencies
          sudo apt-get update
          sudo apt-get install -y libglib2.0-dev attr gettext bison  dbus gtk-doc-tools \
          libfuse3-dev ostree libostree-dev libarchive-dev libzstd-dev libcap-dev libattr1-dev libdw-dev libelf-dev python3-pyparsing \
          libjson-glib-dev shared-mime-info desktop-file-utils libpolkit-agent-1-dev libpolkit-gobject-1-dev \
          libseccomp-dev libcurl4-openssl-dev libsystemd-dev libxml2-utils libgpgme11-dev gobject-introspection \
          libgirepository1.0-dev libappstream-dev libdconf-dev clang socat meson libdbus-1-dev e2fslibs-dev bubblewrap xdg-dbus-proxy \
          meson ninja-build libyaml-dev libstemmer-dev gperf itstool libmalcontent-0-dev libxau-dev libgdk-pixbuf2.0-dev openssl
          # One of the tests wants this
          sudo mkdir /tmp/flatpak-com.example.App-OwnedByRoot

      - name: Checkout the repository
        uses: actions/checkout@v4

      - name: Build flatpak
        run: |
          meson setup _build
          meson dist -C _build

      - name: Extract release information
        run: |
          # Extract the release version
          releaseVersion=`meson introspect --projectinfo _build/ | jq -r .version`
          echo "releaseVersion=$releaseVersion" | tee -a $GITHUB_ENV
          echo $releaseVersion

          # Extract the changelog
          {
            echo "releaseChangelog<<EOF"
            perl -0777nE 'print $& if /(?<=\n\n).*?(?=\nChanges in)/sg' NEWS
            echo ""
            echo "EOF"
          } | tee -a $GITHUB_ENV
          echo $releaseChangelog

          # Check if version is a pre-release
          preRelease=$((`echo $releaseVersion | cut -d '.' -f2` % 2))
          {
            echo -n "preRelease="
            if [ $preRelease = 1 ] || [ $preRelease = "true" ]; then
              echo "true";
            else
              echo "false";
            fi
          } | tee -a $GITHUB_ENV
          echo $preRelease

      - name: Create release
        uses: ncipollo/release-action@v1.20.0
        with:
          tag: ${{ env.releaseVersion }}
          body: ${{ env.releaseChangelog }}
          prerelease: ${{ env.preRelease }}
          artifacts: _build/meson-dist/*
          immutableCreate: true