name: Release Packages

on:
  push:
    branches:
      - master
    paths:
      - 'Cargo.toml'
  release:
    types: [created]
  workflow_dispatch:

env:
  CARGO_TERM_COLOR: always

jobs:
  check-version:
    name: Check Version and Create Release
    runs-on: ubuntu-latest
    permissions:
      contents: write
    outputs:
      version: ${{ steps.version.outputs.VERSION }}
      should_release: ${{ steps.check.outputs.SHOULD_RELEASE }}
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Get version from Cargo.toml
        id: version
        run: |
          VERSION=$(grep '^version' Cargo.toml | head -1 | cut -d'"' -f2)
          echo "VERSION=$VERSION" >> $GITHUB_OUTPUT
          echo "Version: $VERSION"

      - name: Check if tag exists
        id: check
        run: |
          if git rev-parse "v${{ steps.version.outputs.VERSION }}" >/dev/null 2>&1; then
            echo "SHOULD_RELEASE=false" >> $GITHUB_OUTPUT
            echo "Tag v${{ steps.version.outputs.VERSION }} already exists"
          else
            echo "SHOULD_RELEASE=true" >> $GITHUB_OUTPUT
            echo "Tag v${{ steps.version.outputs.VERSION }} does not exist, will create release"
          fi

      - name: Create Git Tag
        if: steps.check.outputs.SHOULD_RELEASE == 'true'
        run: |
          echo "Creating tag v${{ steps.version.outputs.VERSION }}"
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git tag -a "v${{ steps.version.outputs.VERSION }}" -m "Release v${{ steps.version.outputs.VERSION }}"
          echo "Pushing tag to remote..."
          git push https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }} "v${{ steps.version.outputs.VERSION }}"
          echo "Tag created and pushed successfully"

      - name: Create GitHub Release
        if: steps.check.outputs.SHOULD_RELEASE == 'true'
        uses: softprops/action-gh-release@v1
        with:
          tag_name: v${{ steps.version.outputs.VERSION }}
          name: Release v${{ steps.version.outputs.VERSION }}
          draft: false
          prerelease: false
          generate_release_notes: true
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

  test:
    name: Run Tests
    runs-on: ubuntu-latest
    needs: check-version
    if: needs.check-version.outputs.should_release == 'true' || github.event_name == 'release'
    steps:
      - uses: actions/checkout@v4

      - name: Install Rust
        uses: actions-rs/toolchain@v1
        with:
          toolchain: stable
          profile: minimal
          override: true

      - name: Run tests
        run: cargo test --verbose

  publish-crate:
    name: Publish to crates.io
    runs-on: ubuntu-latest
    needs: [check-version, test]
    if: needs.check-version.outputs.should_release == 'true'
    steps:
      - uses: actions/checkout@v4

      - name: Install Rust
        uses: actions-rs/toolchain@v1
        with:
          toolchain: stable
          profile: minimal
          override: true

      - name: Publish to crates.io
        run: cargo publish --token ${{ secrets.CARGO_REGISTRY_TOKEN }}
        continue-on-error: true

  build-deb:
    name: Build Debian Package
    runs-on: ubuntu-latest
    permissions:
      contents: write
    needs: [check-version, test]
    if: needs.check-version.outputs.should_release == 'true' || github.event_name == 'release'
    steps:
      - uses: actions/checkout@v4

      - name: Install Rust
        uses: actions-rs/toolchain@v1
        with:
          toolchain: stable
          profile: minimal
          override: true

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

      - name: Build release binary
        run: cargo build --release --verbose

      - name: Build .deb package
        run: cargo deb

      - name: Upload .deb package
        uses: actions/upload-artifact@v4
        with:
          name: sticks-deb
          path: target/debian/*.deb

      - name: Upload to release
        uses: softprops/action-gh-release@v1
        with:
          tag_name: v${{ needs.check-version.outputs.version }}
          files: target/debian/*.deb
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

  build-arch:
    name: Build Arch Linux Package
    runs-on: ubuntu-latest
    permissions:
      contents: write
    needs: [check-version, test]
    if: needs.check-version.outputs.should_release == 'true' || github.event_name == 'release'
    steps:
      - uses: actions/checkout@v4
        with:
          submodules: true

      - name: Update PKGBUILD version
        run: |
          cd sticks-aur
          sed -i "s/pkgver=.*/pkgver=${{ needs.check-version.outputs.version }}/" PKGBUILD
          cat PKGBUILD | grep pkgver

      - name: Commit and push PKGBUILD changes
        run: |
          cd sticks-aur
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add PKGBUILD
          if ! git diff --cached --quiet; then
            git commit -m "chore: update PKGBUILD to v${{ needs.check-version.outputs.version }}"
            # Use PAT for authentication to sticks-aur repository
            git push "https://x-access-token:${{ secrets.STICKS_PAT }}@github.com/mAmineChniti/sticks-aur.git" HEAD:master
            echo "PKGBUILD updated and pushed to sticks-aur repository"
          else
            echo "No changes to PKGBUILD"
          fi

      - name: Build Arch package in container
        run: |
          docker run --rm -v "$PWD:/workspace" -w /workspace archlinux:latest bash -c "
            set -e
            pacman -Syu --noconfirm base-devel rust cargo git
            useradd -m builder
            chown -R builder:builder /workspace
            echo 'Building package...'
            su - builder -c 'cd /workspace/sticks-aur && makepkg --noconfirm -s'
            echo 'Build completed successfully'
          " || { echo "Error: makepkg failed inside container"; exit 1; }

      - name: Find and verify package file
        id: package
        run: |
          # Find the release package (exclude debug)
          PKGFILE=$(find sticks-aur -name "sticks-*-x86_64.pkg.tar.zst" -not -name "*-debug-*" -type f | head -1)
          if [ -z "$PKGFILE" ]; then
            echo "Error: No release package found"
            exit 1
          fi
          echo "PKGFILE=$PKGFILE" >> $GITHUB_OUTPUT
          echo "PKGNAME=$(basename $PKGFILE)" >> $GITHUB_OUTPUT
          echo "Found package: $PKGFILE"
          ls -lh "$PKGFILE"

      - name: Upload Arch package artifact
        uses: actions/upload-artifact@v4
        with:
          name: sticks-arch-package
          path: ${{ steps.package.outputs.PKGFILE }}

      - name: Upload Arch package to release
        uses: softprops/action-gh-release@v1
        with:
          tag_name: v${{ needs.check-version.outputs.version }}
          files: ${{ steps.package.outputs.PKGFILE }}
          fail_on_unmatched_files: true
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

  build-binary:
    name: Build Generic Linux Binary
    runs-on: ubuntu-latest
    permissions:
      contents: write
    needs: [check-version, test]
    if: needs.check-version.outputs.should_release == 'true' || github.event_name == 'release'

    steps:
      - uses: actions/checkout@v4

      - name: Install Rust
        uses: actions-rs/toolchain@v1
        with:
          toolchain: stable
          target: x86_64-unknown-linux-gnu
          profile: minimal
          override: true

      - name: Build
        uses: actions-rs/cargo@v1
        with:
          command: build
          args: --release --target x86_64-unknown-linux-gnu

      - name: Strip binary
        run: strip target/x86_64-unknown-linux-gnu/release/sticks

      - name: Rename binary
        run: |
          cp target/x86_64-unknown-linux-gnu/release/sticks sticks-linux-x86_64
          chmod +x sticks-linux-x86_64

      - name: Upload binary
        uses: actions/upload-artifact@v4
        with:
          name: sticks-linux-x86_64
          path: sticks-linux-x86_64

      - name: Upload to release
        uses: softprops/action-gh-release@v1
        with:
          tag_name: v${{ needs.check-version.outputs.version }}
          files: sticks-linux-x86_64
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
