name: CI

on:
  push:
    branches: [main]
    tags: ["v*"]
    paths-ignore:
      - 'peek-code/**'
      - 'README.md'
  pull_request:
    branches: [main]
    paths-ignore:
      - 'peek-code/**'
      - 'README.md'

permissions:
  contents: read

jobs:
  test:
    name: Test (${{ matrix.os }})
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: ubuntu-latest
          - os: macos-latest
          - os: windows-latest
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
      - uses: Swatinem/rust-cache@v2
      - run: cargo test --locked --release

  lint:
    name: Lint
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
        with:
          components: rustfmt, clippy
      - run: cargo fmt -- --check
      - run: cargo clippy --all-targets -- -D warnings

  msrv:
    name: MSRV (1.85)
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@master
        with:
          toolchain: "1.85"
      - run: cargo check --locked

  build:
    name: Build (${{ matrix.target }})
    runs-on: ${{ matrix.os }}
    permissions:
      contents: write
    strategy:
      fail-fast: false
      matrix:
        include:
          - target: x86_64-unknown-linux-gnu
            os: ubuntu-latest
            use-cross: true
          - target: aarch64-unknown-linux-gnu
            os: ubuntu-latest
            use-cross: true
          - target: x86_64-apple-darwin
            os: macos-latest
          - target: aarch64-apple-darwin
            os: macos-latest
          - target: x86_64-pc-windows-msvc
            os: windows-latest
    env:
      BUILD_CMD: ${{ matrix.use-cross && 'cross' || 'cargo' }}
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.target }}

      - name: Install cross
        if: matrix.use-cross
        run: |
          dir="$HOME/.local/bin/"
          mkdir -p "$dir"
          curl -LO "https://github.com/cross-rs/cross/releases/download/v0.2.5/cross-x86_64-unknown-linux-musl.tar.gz"
          tar -C "$dir" -xzf cross-x86_64-unknown-linux-musl.tar.gz
          echo "$dir" >> $GITHUB_PATH

      - run: ${{ env.BUILD_CMD }} build --locked --release --target ${{ matrix.target }}

      - name: Package
        shell: bash
        run: |
          EXE_suffix=""
          case ${{ matrix.target }} in
            *-pc-windows-*) EXE_suffix=".exe" ;;
          esac
          BIN="target/${{ matrix.target }}/release/peek${EXE_suffix}"

          PKG_NAME="peek-${{ github.ref_name }}-${{ matrix.target }}"
          case ${{ matrix.target }} in
            *-pc-windows-*)
              mkdir -p "$PKG_NAME"
              cp "$BIN" README.md LICENSE-MIT LICENSE-APACHE "$PKG_NAME/"
              7z a "$PKG_NAME.zip" "$PKG_NAME"
              echo "ASSET=$PKG_NAME.zip" >> $GITHUB_ENV
              ;;
            *)
              mkdir -p "$PKG_NAME"
              cp "$BIN" README.md LICENSE-MIT LICENSE-APACHE "$PKG_NAME/"
              tar czf "$PKG_NAME.tar.gz" "$PKG_NAME"
              shasum -a 256 "$PKG_NAME.tar.gz" > "$PKG_NAME.tar.gz.sha256"
              echo "ASSET=$PKG_NAME.tar.gz" >> $GITHUB_ENV
              echo "ASSET_SUM=$PKG_NAME.tar.gz.sha256" >> $GITHUB_ENV
              ;;
          esac

      - uses: actions/upload-artifact@v4
        if: startsWith(github.ref, 'refs/tags/v')
        with:
          name: ${{ matrix.target }}
          path: |
            ${{ env.ASSET }}
            ${{ env.ASSET_SUM }}

      - name: Check for release
        id: is-release
        shell: bash
        run: |
          unset IS_RELEASE
          if [[ $GITHUB_REF =~ ^refs/tags/v[0-9].* ]]; then IS_RELEASE='true' ; fi
          echo "IS_RELEASE=${IS_RELEASE}" >> $GITHUB_OUTPUT

      - name: Publish archives
        uses: softprops/action-gh-release@v2
        if: steps.is-release.outputs.IS_RELEASE
        with:
          files: |
            ${{ env.ASSET }}
            ${{ env.ASSET_SUM }}
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

  release:
    name: Publish to crates.io
    needs: build
    if: startsWith(github.ref, 'refs/tags/v')
    runs-on: ubuntu-latest
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@v4

      - name: Verify version match
        run: |
          VERSION="${{ github.ref_name }}"
          grep -q "version = \"${VERSION#v}\"" Cargo.toml || {
            echo "Tag version $VERSION does not match Cargo.toml" >&2
            exit 1
          }

      - uses: dtolnay/rust-toolchain@stable
      - name: Publish to crates.io
        continue-on-error: true
        run: cargo publish
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}

  update-homebrew:
    name: Update Homebrew Formula
    needs: build
    if: startsWith(github.ref, 'refs/tags/v')
    runs-on: ubuntu-latest
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@v4

      - name: Download checksums
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          VERSION="${{ github.ref_name }}"
          mkdir -p checksums
          for target in aarch64-apple-darwin x86_64-apple-darwin \
                        aarch64-unknown-linux-gnu x86_64-unknown-linux-gnu; do
            gh release download "$VERSION" \
              --pattern "peek-${VERSION}-${target}.tar.gz.sha256" \
              --dir checksums/ || true
          done

      - name: Extract checksums
        id: checksums
        run: |
          echo "arm64_mac=$(cut -d' ' -f1 checksums/peek-*aarch64-apple-darwin.tar.gz.sha256)" >> $GITHUB_OUTPUT
          echo "intel_mac=$(cut -d' ' -f1 checksums/peek-*x86_64-apple-darwin.tar.gz.sha256)" >> $GITHUB_OUTPUT
          echo "arm64_linux=$(cut -d' ' -f1 checksums/peek-*aarch64-unknown-linux-gnu.tar.gz.sha256)" >> $GITHUB_OUTPUT
          echo "intel_linux=$(cut -d' ' -f1 checksums/peek-*x86_64-unknown-linux-gnu.tar.gz.sha256)" >> $GITHUB_OUTPUT

      - name: Generate formula
        run: |
          VERSION_NUM="${VERSION#v}"
          bash scripts/update-homebrew-formula.sh \
            "$VERSION_NUM" \
            "${{ steps.checksums.outputs.arm64_mac }}" \
            "${{ steps.checksums.outputs.intel_mac }}" \
            "${{ steps.checksums.outputs.arm64_linux }}" \
            "${{ steps.checksums.outputs.intel_linux }}"
        env:
          VERSION: ${{ github.ref_name }}

      - name: Push to tap repository
        uses: dmnemec/copy_file_to_another_repo_action@main
        env:
          API_TOKEN_GITHUB: ${{ secrets.HOMEBREW_TAP_TOKEN }}
        with:
          source_file: 'Formula/peek-code.rb'
          destination_repo: 'owniai/homebrew-tap'
          destination_folder: 'Formula'
          user_email: 'noreply@owniai.com'
          user_name: 'owniai'
          commit_message: "bump peek to ${{ github.ref_name }}"
