name: CD

on:
  push:
    tags:
      - "v*"

jobs:
  metadata:
    runs-on: ubuntu-24.04
    steps:
      - uses: actions/checkout@v5
      - uses: dtolnay/rust-toolchain@stable
      - id: cargo
        run: cargo metadata --no-deps --format-version 1 | jq -r '"version=" + .packages[0].version' >> $GITHUB_OUTPUT
    outputs:
      version: ${{ steps.cargo.outputs.version }}

  build:
    name: ${{ matrix.job.target }}
    runs-on: ${{ matrix.job.os }}
    needs: metadata
    permissions:
      contents: write
    strategy:
      fail-fast: false
      matrix:
        job:
          - { target: x86_64-unknown-linux-gnu, os: ubuntu-24.04 }
          - { target: aarch64-unknown-linux-gnu, os: ubuntu-24.04-arm }
    steps:
      - uses: actions/checkout@v5
      - uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.job.target }}
      - name: Install Deps
        run: |
          sudo apt-get install -y libwayland-dev
      - name: Cache
        uses: actions/cache@v4
        with:
          path: |
            ~/.cargo/bin/
            ~/.cargo/registry/index/
            ~/.cargo/registry/cache/
            ~/.cargo/git/db/
            target/
          key: ${{ matrix.job.target }}-${{ hashFiles('**/Cargo.lock') }}
          restore-keys: ${{ matrix.job.target }}-
      - name: Build
        run: cargo build --locked --release --target=${{ matrix.job.target }}
      - name: Create Tarball
        id: package
        run: |
          PKG_NAME=chameleos-v${{ needs.metadata.outputs.version }}-${{ matrix.job.target }}
          TARBALL=${PKG_NAME}.tar.gz

          echo "pkg_name=$PKG_NAME" >> $GITHUB_OUTPUT
          echo "tarball=$TARBALL" >> $GITHUB_OUTPUT

          mkdir "$PKG_NAME"

          cp "README.md" "LICENSE" "$PKG_NAME"
          cp target/${{ matrix.job.target }}/release/chameleos "$PKG_NAME"
          cp target/${{ matrix.job.target }}/release/chamel "$PKG_NAME"

          tar czf "$TARBALL" --directory="$PKG_NAME" .
      - name: Upload Artifact
        uses: actions/upload-artifact@v4
        with:
          name: ${{ steps.package.outputs.pkg_name }}
          path: ${{ steps.package.outputs.pkg_name }}
      - name: Create Release
        uses: softprops/action-gh-release@v2
        with:
          draft: true
          files: ${{ steps.package.outputs.tarball }}
