name: Release

on:
  push:
    tags: ["v*"]
  workflow_dispatch:

permissions:
  contents: write

env:
  CARGO_TERM_COLOR: always
  BINARY_NAME: passhrs

jobs:
  build:
    name: Build (${{ matrix.target }})
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        include:
          # Linux
          - os: ubuntu-24.04
            target: x86_64-unknown-linux-gnu
            cross: false
          - os: ubuntu-24.04
            target: x86_64-unknown-linux-musl
            cross: true
          - os: ubuntu-24.04
            target: aarch64-unknown-linux-gnu
            cross: true
          - os: ubuntu-24.04
            target: aarch64-unknown-linux-musl
            cross: true
          - os: ubuntu-24.04
            target: armv7-unknown-linux-musleabihf
            cross: true
          # macOS
          - os: macos-14
            target: x86_64-apple-darwin
            cross: false
          - os: macos-14
            target: aarch64-apple-darwin
            cross: false
          # Windows
          - os: windows-2022
            target: x86_64-pc-windows-msvc
            cross: false
          - os: windows-2022
            target: x86_64-pc-windows-gnu
            cross: false

    steps:
      - uses: actions/checkout@v4

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

      - name: Install cross
        if: matrix.cross
        run: cargo install cross --git https://github.com/cross-rs/cross

      - name: Install musl tools
        if: matrix.target == 'x86_64-unknown-linux-musl'
        run: sudo apt-get install -y musl-tools

      - name: Build (native)
        if: ${{ !matrix.cross }}
        run: cargo build --release --target ${{ matrix.target }}

      - name: Build (cross)
        if: matrix.cross
        run: cross build --release --target ${{ matrix.target }}

      - name: Set binary ext
        id: ext
        shell: bash
        run: |
          if [[ "${{ matrix.target }}" == *"windows"* ]]; then
            echo "ext=.exe" >> $GITHUB_OUTPUT
          else
            echo "ext=" >> $GITHUB_OUTPUT
          fi

      - name: Rename artifact
        shell: bash
        run: |
          TAG=${GITHUB_REF#refs/tags/}
          EXT=${{ steps.ext.outputs.ext }}
          cp target/${{ matrix.target }}/release/${{ env.BINARY_NAME }}$EXT \
             ${{ env.BINARY_NAME }}-${TAG}-${{ matrix.target }}$EXT

      - name: Upload artifact
        uses: actions/upload-artifact@v4
        with:
          name: ${{ env.BINARY_NAME }}-${{ matrix.target }}
          path: ${{ env.BINARY_NAME }}-*
          if-no-files-found: error

  docker:
    name: Docker multi-arch build & push
    needs: build
    runs-on: ubuntu-24.04
    steps:
      - uses: actions/checkout@v4

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

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

      - name: Download amd64 musl artifact
        uses: actions/download-artifact@v4
        with:
          name: ${{ env.BINARY_NAME }}-x86_64-unknown-linux-musl
          path: artifacts

      - name: Download arm64 musl artifact
        uses: actions/download-artifact@v4
        with:
          name: ${{ env.BINARY_NAME }}-aarch64-unknown-linux-musl
          path: artifacts

      - name: Organize binaries for multi-arch build
        shell: bash
        run: |
          set -e
          mkdir -p bin/amd64 bin/arm64
          echo "=== artifacts content ==="
          find artifacts -type f -ls
          echo "=== copying ==="
          # Find musl binary for amd64
          AMD64_FILE=$(find artifacts -type f -name '${{ env.BINARY_NAME }}-*x86_64*' | head -1)
          if [ -z "$AMD64_FILE" ]; then
            echo "ERROR: amd64 binary not found in artifacts!"
            exit 1
          fi
          cp "$AMD64_FILE" bin/amd64/${{ env.BINARY_NAME }}
          echo "amd64: $AMD64_FILE"
          # Find musl binary for arm64
          ARM64_FILE=$(find artifacts -type f -name '${{ env.BINARY_NAME }}-*aarch64*' | head -1)
          if [ -z "$ARM64_FILE" ]; then
            echo "ERROR: arm64 binary not found in artifacts!"
            exit 1
          fi
          cp "$ARM64_FILE" bin/arm64/${{ env.BINARY_NAME }}
          echo "arm64: $ARM64_FILE"
          chmod +x bin/amd64/${{ env.BINARY_NAME }} bin/arm64/${{ env.BINARY_NAME }}
          echo "=== staged files ==="
          ls -la bin/amd64/ bin/arm64/

      - name: Extract metadata
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ secrets.DOCKER_USERNAME }}/${{ env.BINARY_NAME }}
          tags: |
            type=ref,event=tag
            type=raw,value=latest

      - name: Build multi-arch (no push, no login)
        uses: docker/build-push-action@v6
        with:
          context: .
          file: Dockerfile.static
          platforms: linux/amd64,linux/arm64
          push: false
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          provenance: false
          sbom: false
          cache-from: type=gha
          cache-to: type=gha,mode=max
        env:
          DOCKER_BUILD_RECORD_UPLOAD: false

      - name: Log in to Docker Hub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}

      - name: Push (login required)
        uses: docker/build-push-action@v6
        with:
          context: .
          file: Dockerfile.static
          platforms: linux/amd64,linux/arm64
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          provenance: false
          sbom: false
          cache-from: type=gha
          cache-to: type=gha,mode=max
        env:
          DOCKER_BUILD_RECORD_UPLOAD: false

  release:
    name: Create GitHub Release
    needs: [build, docker]
    runs-on: ubuntu-24.04
    steps:
      - uses: actions/checkout@v4

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

      - name: Prepare release assets
        shell: bash
        run: |
          mkdir -p release-assets
          find artifacts -type f -exec cp {} release-assets/ \;
          cd release-assets
          sha256sum * > sha256sums.txt
          ls -la

      - name: Generate changelog
        id: changelog
        shell: bash
        run: |
          TAG="${GITHUB_REF#refs/tags/}"
          PREV_TAG=$(git tag --sort=-creatordate 2>/dev/null | grep -v "$TAG" | head -1 || true)
          if [ -z "$PREV_TAG" ]; then
            git log --oneline --no-decorate -30 > changelog.md
          else
            git log --oneline --no-decorate "${PREV_TAG}..HEAD" > changelog.md 2>/dev/null || git log --oneline --no-decorate -30 > changelog.md
          fi
          cat changelog.md
          {
            echo "changelog<<EOF"
            cat changelog.md
            echo "EOF"
          } >> "$GITHUB_OUTPUT"

      - name: Delete existing release (if any)
        id: delete_release
        shell: bash
        continue-on-error: true
        run: |
          HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" \
            -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \
            "https://api.github.com/repos/${{ github.repository }}/releases/tags/${{ github.ref_name }}")
          if [ "$HTTP_CODE" = "200" ]; then
            RELEASE_ID=$(curl -s \
              -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \
              "https://api.github.com/repos/${{ github.repository }}/releases/tags/${{ github.ref_name }}" \
              | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])")
            curl -s -X DELETE \
              -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \
              "https://api.github.com/repos/${{ github.repository }}/releases/$RELEASE_ID"
            echo "Deleted release $RELEASE_ID for ${{ github.ref_name }}"
          else
            echo "No existing release for ${{ github.ref_name }}"
          fi

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v2
        with:
          generate_release_notes: true
          name: ${{ github.ref_name }}
          body: |
            ## ${{ github.ref_name }}

            ### Assets
            | Platform | File |
            |---|---|
            | Linux x86_64 (gnu) | `${{ env.BINARY_NAME }}-${{ github.ref_name }}-x86_64-unknown-linux-gnu` |
            | Linux x86_64 (static) | `${{ env.BINARY_NAME }}-${{ github.ref_name }}-x86_64-unknown-linux-musl` |
            | Linux aarch64 (gnu) | `${{ env.BINARY_NAME }}-${{ github.ref_name }}-aarch64-unknown-linux-gnu` |
            | Linux aarch64 (musl) | `${{ env.BINARY_NAME }}-${{ github.ref_name }}-aarch64-unknown-linux-musl` |
            | Linux armv7 (static) | `${{ env.BINARY_NAME }}-${{ github.ref_name }}-armv7-unknown-linux-musleabihf` |
            | macOS x86_64 | `${{ env.BINARY_NAME }}-${{ github.ref_name }}-x86_64-apple-darwin` |
            | macOS aarch64 | `${{ env.BINARY_NAME }}-${{ github.ref_name }}-aarch64-apple-darwin` |
            | Windows x86_64 (MSVC) | `${{ env.BINARY_NAME }}-${{ github.ref_name }}-x86_64-pc-windows-msvc.exe` |
            | Windows x86_64 (GNU)  | `${{ env.BINARY_NAME }}-${{ github.ref_name }}-x86_64-pc-windows-gnu.exe` |

            ### Docker
            ```
            docker pull ${{ secrets.DOCKER_USERNAME }}/${{ env.BINARY_NAME }}:${{ github.ref_name }}
            ```

            ${{ steps.changelog.outputs.changelog }}
          files: release-assets/*
          prerelease: ${{ contains(github.ref_name, '-') }}
          draft: false
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

  publish:
    name: Publish to crates.io
    needs: release
    runs-on: ubuntu-24.04
    steps:
      - uses: actions/checkout@v4

      - uses: dtolnay/rust-toolchain@stable

      - name: Check if already published
        id: check
        shell: bash
        run: |
          PKG_NAME=$(cargo metadata --no-deps --format-version 1 | python3 -c "import sys,json; print(json.load(sys.stdin)['packages'][0]['name'])")
          PKG_VER=$(cargo metadata --no-deps --format-version 1 | python3 -c "import sys,json; print(json.load(sys.stdin)['packages'][0]['version'])")
          HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "https://crates.io/api/v1/crates/${PKG_NAME}/${PKG_VER}")
          if [ "$HTTP_CODE" = "200" ]; then
            echo "Version ${PKG_VER} of ${PKG_NAME} already published, skipping."
            echo "skip=true" >> $GITHUB_OUTPUT
          else
            echo "Version ${PKG_VER} of ${PKG_NAME} not yet published, proceeding."
            echo "skip=false" >> $GITHUB_OUTPUT
          fi

      - name: Publish
        if: steps.check.outputs.skip != 'true'
        run: cargo publish --token ${{ secrets.CARGO_REGISTRY_TOKEN }}
