name: Release

on:
  push:
    tags:
      - "v*"
  workflow_dispatch:
    inputs:
      tag:
        description: "Release tag (e.g., v0.1.0)"
        required: true

env:
  CARGO_TERM_COLOR: always

jobs:
  build-linux:
    name: Build Linux (${{ matrix.target }})
    runs-on: ubuntu-latest
    strategy:
      matrix:
        include:
          - target: x86_64-unknown-linux-gnu
            arch: amd64
          - target: aarch64-unknown-linux-gnu
            arch: arm64
    steps:
      - uses: actions/checkout@v4

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.target }}

      - name: Install cross-compilation tools
        if: matrix.target == 'aarch64-unknown-linux-gnu'
        run: |
          sudo apt-get update
          sudo apt-get install -y gcc-aarch64-linux-gnu

      - uses: Swatinem/rust-cache@v2
        with:
          key: ${{ matrix.target }}

      - name: Build binaries
        run: |
          if [ "${{ matrix.target }}" = "aarch64-unknown-linux-gnu" ]; then
            export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc
          fi
          cargo build --release --target ${{ matrix.target }} -p rstmdb -p rstmdb-cli

      - name: Prepare artifacts
        run: |
          mkdir -p dist
          cp target/${{ matrix.target }}/release/rstmdb dist/
          cp target/${{ matrix.target }}/release/rstmdb-cli dist/
          cp README.md LICENSE dist/ 2>/dev/null || true
          cd dist
          tar -czvf rstmdb-linux-${{ matrix.arch }}.tar.gz rstmdb rstmdb-cli README.md LICENSE 2>/dev/null || \
          tar -czvf rstmdb-linux-${{ matrix.arch }}.tar.gz rstmdb rstmdb-cli

      - name: Upload artifact
        uses: actions/upload-artifact@v4
        with:
          name: linux-${{ matrix.arch }}
          path: dist/rstmdb-linux-${{ matrix.arch }}.tar.gz

  build-deb:
    name: Build DEB Package (${{ matrix.arch }})
    runs-on: ubuntu-latest
    needs: build-linux
    strategy:
      matrix:
        include:
          - arch: amd64
            target: x86_64-unknown-linux-gnu
          - arch: arm64
            target: aarch64-unknown-linux-gnu
    steps:
      - uses: actions/checkout@v4

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.target }}

      - name: Install cross-compilation tools
        if: matrix.arch == 'arm64'
        run: |
          sudo apt-get update
          sudo apt-get install -y gcc-aarch64-linux-gnu

      - uses: Swatinem/rust-cache@v2
        with:
          key: ${{ matrix.target }}

      - name: Install cargo-deb
        run: cargo install cargo-deb

      - name: Get version
        id: version
        run: |
          if [ -n "${{ github.event.inputs.tag }}" ]; then
            VERSION="${{ github.event.inputs.tag }}"
          else
            VERSION="${GITHUB_REF#refs/tags/}"
          fi
          VERSION="${VERSION#v}"
          echo "version=$VERSION" >> $GITHUB_OUTPUT

      - name: Build binaries
        run: |
          if [ "${{ matrix.target }}" = "aarch64-unknown-linux-gnu" ]; then
            export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc
          fi
          cargo build --release --target ${{ matrix.target }} -p rstmdb -p rstmdb-cli

      - name: Build DEB package
        run: |
          cargo deb --no-build --target ${{ matrix.target }}

      - name: Rename package
        run: |
          mkdir -p dist
          cp target/${{ matrix.target }}/debian/*.deb dist/rstmdb_${{ steps.version.outputs.version }}_${{ matrix.arch }}.deb

      - name: Upload artifact
        uses: actions/upload-artifact@v4
        with:
          name: deb-${{ matrix.arch }}
          path: dist/*.deb

  build-rpm:
    name: Build RPM Package (${{ matrix.arch }})
    runs-on: ubuntu-latest
    needs: build-linux
    strategy:
      matrix:
        include:
          - arch: x86_64
            target: x86_64-unknown-linux-gnu
          - arch: aarch64
            target: aarch64-unknown-linux-gnu
    steps:
      - uses: actions/checkout@v4

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.target }}

      - name: Install cross-compilation tools
        if: matrix.arch == 'aarch64'
        run: |
          sudo apt-get update
          sudo apt-get install -y gcc-aarch64-linux-gnu

      - uses: Swatinem/rust-cache@v2
        with:
          key: ${{ matrix.target }}

      - name: Install cargo-generate-rpm
        run: cargo install cargo-generate-rpm

      - name: Get version
        id: version
        run: |
          if [ -n "${{ github.event.inputs.tag }}" ]; then
            VERSION="${{ github.event.inputs.tag }}"
          else
            VERSION="${GITHUB_REF#refs/tags/}"
          fi
          VERSION="${VERSION#v}"
          echo "version=$VERSION" >> $GITHUB_OUTPUT

      - name: Build binaries
        run: |
          if [ "${{ matrix.target }}" = "aarch64-unknown-linux-gnu" ]; then
            export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc
          fi
          cargo build --release --target ${{ matrix.target }} -p rstmdb -p rstmdb-cli

      - name: Strip binaries
        run: |
          if [ "${{ matrix.target }}" = "x86_64-unknown-linux-gnu" ]; then
            strip target/${{ matrix.target }}/release/rstmdb target/${{ matrix.target }}/release/rstmdb-cli
          fi

      - name: Build RPM package
        run: |
          cargo generate-rpm --target ${{ matrix.target }}

      - name: Rename package
        run: |
          mkdir -p dist
          cp target/${{ matrix.target }}/generate-rpm/*.rpm dist/rstmdb-${{ steps.version.outputs.version }}-1.${{ matrix.arch }}.rpm

      - name: Upload artifact
        uses: actions/upload-artifact@v4
        with:
          name: rpm-${{ matrix.arch }}
          path: dist/*.rpm

  build-macos:
    name: Build macOS (${{ matrix.target }})
    runs-on: macos-latest
    strategy:
      matrix:
        include:
          - target: x86_64-apple-darwin
            arch: x86_64
          - target: aarch64-apple-darwin
            arch: arm64
    steps:
      - uses: actions/checkout@v4

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.target }}

      - uses: Swatinem/rust-cache@v2
        with:
          key: ${{ matrix.target }}

      - name: Build binaries
        run: cargo build --release --target ${{ matrix.target }} -p rstmdb -p rstmdb-cli

      - name: Prepare artifacts
        run: |
          mkdir -p dist
          cp target/${{ matrix.target }}/release/rstmdb dist/
          cp target/${{ matrix.target }}/release/rstmdb-cli dist/
          cp README.md LICENSE dist/ 2>/dev/null || true
          cd dist
          zip rstmdb-macos-${{ matrix.arch }}.zip rstmdb rstmdb-cli README.md LICENSE 2>/dev/null || \
          zip rstmdb-macos-${{ matrix.arch }}.zip rstmdb rstmdb-cli

      - name: Upload artifact
        uses: actions/upload-artifact@v4
        with:
          name: macos-${{ matrix.arch }}
          path: dist/rstmdb-macos-${{ matrix.arch }}.zip

  build-windows:
    name: Build Windows (${{ matrix.target }})
    runs-on: windows-latest
    strategy:
      matrix:
        include:
          - target: x86_64-pc-windows-msvc
            arch: x86_64
          - target: aarch64-pc-windows-msvc
            arch: arm64
    steps:
      - uses: actions/checkout@v4

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.target }}

      - uses: Swatinem/rust-cache@v2
        with:
          key: ${{ matrix.target }}

      - name: Build binaries
        run: cargo build --release --target ${{ matrix.target }} -p rstmdb -p rstmdb-cli

      - name: Prepare artifacts
        shell: pwsh
        run: |
          New-Item -ItemType Directory -Force -Path dist
          Copy-Item "target/${{ matrix.target }}/release/rstmdb.exe" dist/
          Copy-Item "target/${{ matrix.target }}/release/rstmdb-cli.exe" dist/
          if (Test-Path README.md) { Copy-Item README.md dist/ }
          if (Test-Path LICENSE) { Copy-Item LICENSE dist/ }
          Compress-Archive -Path dist/* -DestinationPath "dist/rstmdb-windows-${{ matrix.arch }}.zip"

      - name: Upload artifact
        uses: actions/upload-artifact@v4
        with:
          name: windows-${{ matrix.arch }}
          path: dist/rstmdb-windows-${{ matrix.arch }}.zip

  docker:
    name: Docker Build & Push
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Get version
        id: version
        run: |
          if [ -n "${{ github.event.inputs.tag }}" ]; then
            VERSION="${{ github.event.inputs.tag }}"
          else
            VERSION="${GITHUB_REF#refs/tags/}"
          fi
          echo "tag=$VERSION" >> $GITHUB_OUTPUT
          echo "version=${VERSION#v}" >> $GITHUB_OUTPUT

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Login to Docker Hub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}

      - name: Docker metadata
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ secrets.DOCKERHUB_USERNAME }}/rstmdb
          tags: |
            type=raw,value=latest
            type=semver,pattern={{version}},value=${{ steps.version.outputs.tag }}
            type=semver,pattern={{major}}.{{minor}},value=${{ steps.version.outputs.tag }}
            type=semver,pattern={{major}},value=${{ steps.version.outputs.tag }}

      - name: Build and push Docker image
        uses: docker/build-push-action@v6
        with:
          context: .
          platforms: linux/amd64,linux/arm64
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

  release:
    name: Create Release
    runs-on: ubuntu-latest
    needs: [build-linux, build-deb, build-rpm, build-macos, build-windows]
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v4

      - name: Get version
        id: version
        run: |
          if [ -n "${{ github.event.inputs.tag }}" ]; then
            VERSION="${{ github.event.inputs.tag }}"
          else
            VERSION="${GITHUB_REF#refs/tags/}"
          fi
          echo "tag=$VERSION" >> $GITHUB_OUTPUT
          echo "version=${VERSION#v}" >> $GITHUB_OUTPUT

      - name: Download all artifacts
        uses: actions/download-artifact@v4
        with:
          path: artifacts

      - name: Prepare release assets
        run: |
          mkdir -p release
          find artifacts -type f \( -name "*.tar.gz" -o -name "*.zip" -o -name "*.deb" -o -name "*.rpm" \) -exec cp {} release/ \;
          ls -la release/

      - name: Generate checksums
        run: |
          cd release
          sha256sum * > SHA256SUMS.txt
          cat SHA256SUMS.txt

      - name: Create Release
        uses: softprops/action-gh-release@v2
        with:
          tag_name: ${{ steps.version.outputs.tag }}
          name: Release ${{ steps.version.outputs.tag }}
          draft: false
          prerelease: ${{ contains(steps.version.outputs.tag, '-') }}
          generate_release_notes: true
          files: |
            release/*
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
