name: Release

on:
  push:
    tags:
      - 'v*'

jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Install system dependencies
        run: |
          sudo apt-get update -q
          sudo apt-get install -y \
            libgtk-3-dev \
            libgstreamer1.0-dev \
            libgstreamer-plugins-base1.0-dev \
            libgstreamer-plugins-bad1.0-dev \
            gstreamer1.0-plugins-good \
            libpam0g-dev \
            ninja-build \
            meson \
            libglib2.0-dev

      - name: Install Rust stable
        uses: dtolnay/rust-toolchain@stable

      - name: Build release
        run: |
          meson setup builddir --buildtype=release
          meson compile -C builddir

      - name: Bundle artifacts
        run: |
          mkdir -p dist
          cp builddir/ahfail-module.so dist/
          cp builddir/libahfail_pam.so dist/
          cp builddir/ahfail-display dist/
          tar czf ahfail-linux-x86_64.tar.gz -C dist .

      - name: Create Gitea release and upload asset
        # Requires a GITEA_TOKEN secret with write:repository scope.
        # Create it in repo Settings → Secrets.
        env:
          GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
          GITEA_URL: https://gitea.weircon.dk
          REPO: agw/gtk-ahfail
          TAG: ${{ github.ref_name }}
        run: |
          set -euo pipefail
          RELEASE_ID=$(curl -f -X POST \
            "${GITEA_URL}/api/v1/repos/${REPO}/releases" \
            -H "Authorization: token ${GITEA_TOKEN}" \
            -H "Content-Type: application/json" \
            -d "{\"tag_name\":\"${TAG}\",\"name\":\"${TAG}\",\"draft\":false}" \
            | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])")

          [ -n "${RELEASE_ID}" ] || { echo "ERROR: empty RELEASE_ID from API"; exit 1; }

          curl -f -X POST \
            "${GITEA_URL}/api/v1/repos/${REPO}/releases/${RELEASE_ID}/assets" \
            -H "Authorization: token ${GITEA_TOKEN}" \
            -F "attachment=@ahfail-linux-x86_64.tar.gz"
