name: Update Homebrew Cask

on:
  workflow_run:
    workflows: ["Release"]
    types:
      - completed
    branches:
      - master
  workflow_dispatch:
    inputs:
      version:
        description: "Version to update (e.g., 0.6.0 or v0.6.0)"
        required: true
        type: string

jobs:
  update-homebrew:
    runs-on: ubuntu-latest
    # Only run if:
    # - Manual dispatch, OR
    # - Release workflow succeeded and was triggered by a tag
    if: ${{ github.event_name == 'workflow_dispatch' || (github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'push') }}
    steps:
      - name: Extract version from tag
        id: version
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
            # Manual trigger - use the input version
            TAG="${{ inputs.version }}"
            echo "Using manually provided version: $TAG"
          else
            # Automated trigger - get the tag from the Release workflow
            TAG=$(gh api /repos/${{ github.repository }}/actions/runs/${{ github.event.workflow_run.id }} --jq '.head_branch')
            echo "Extracted tag from workflow run: $TAG"
          fi

          # Remove 'v' prefix from tag if present
          VERSION="${TAG#v}"
          echo "version=$VERSION" >> $GITHUB_OUTPUT
          echo "Final version: $VERSION"

      - name: Wait for release assets
        run: |
          echo "Waiting 15 seconds for release assets to be uploaded..."
          sleep 15

      - name: Fetch release assets and calculate SHA256
        id: assets
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          VERSION="${{ steps.version.outputs.version }}"
          REPO="amir20/dtop"

          # Function to get SHA256 for an asset
          get_sha256() {
            local asset_name=$1
            local download_url=$(gh release view "v${VERSION}" --repo "$REPO" --json assets --jq ".assets[] | select(.name == \"$asset_name\") | .url")

            if [ -z "$download_url" ]; then
              echo "Error: Asset $asset_name not found in release v${VERSION}" >&2
              return 1
            fi

            echo "Downloading $asset_name..." >&2
            curl -sL -H "Authorization: token $GH_TOKEN" -H "Accept: application/octet-stream" "$download_url" | sha256sum | cut -d' ' -f1
          }

          # Calculate SHA256 for each platform
          echo "Calculating SHA256 checksums for all platforms..."

          MACOS_X86_SHA=$(get_sha256 "dtop-x86_64-apple-darwin.tar.gz")
          MACOS_ARM_SHA=$(get_sha256 "dtop-aarch64-apple-darwin.tar.gz")
          LINUX_X86_SHA=$(get_sha256 "dtop-x86_64-unknown-linux-gnu.tar.gz")
          LINUX_ARM_SHA=$(get_sha256 "dtop-aarch64-unknown-linux-gnu.tar.gz")

          # Output to GitHub outputs
          echo "macos_x86_sha=$MACOS_X86_SHA" >> $GITHUB_OUTPUT
          echo "macos_arm_sha=$MACOS_ARM_SHA" >> $GITHUB_OUTPUT
          echo "linux_x86_sha=$LINUX_X86_SHA" >> $GITHUB_OUTPUT
          echo "linux_arm_sha=$LINUX_ARM_SHA" >> $GITHUB_OUTPUT

          echo "SHA256 checksums calculated successfully"

      - name: Checkout homebrew-dtop repository
        uses: actions/checkout@v4
        with:
          repository: amir20/homebrew-dtop
          token: ${{ secrets.HOMEBREW_TAP_GITHUB_TOKEN }}
          path: homebrew-dtop

      - name: Update Homebrew Cask
        run: |
          VERSION="${{ steps.version.outputs.version }}"
          CASK_FILE="homebrew-dtop/Casks/dtop.rb"

          cat > "$CASK_FILE" << 'EOF'
          # typed: false
          # frozen_string_literal: true

          # This file was generated by cargo-dist.
          # Do not modify this file manually.

          cask "dtop" do
            version "VERSION_PLACEHOLDER"

            on_intel do
              on_macos do
                url "https://github.com/amir20/dtop/releases/download/vVERSION_PLACEHOLDER/dtop-x86_64-apple-darwin.tar.gz"
                sha256 "MACOS_X86_SHA_PLACEHOLDER"
              end
              on_linux do
                url "https://github.com/amir20/dtop/releases/download/vVERSION_PLACEHOLDER/dtop-x86_64-unknown-linux-gnu.tar.gz"
                sha256 "LINUX_X86_SHA_PLACEHOLDER"
              end
            end

            on_arm do
              on_macos do
                url "https://github.com/amir20/dtop/releases/download/vVERSION_PLACEHOLDER/dtop-aarch64-apple-darwin.tar.gz"
                sha256 "MACOS_ARM_SHA_PLACEHOLDER"
              end
              on_linux do
                url "https://github.com/amir20/dtop/releases/download/vVERSION_PLACEHOLDER/dtop-aarch64-unknown-linux-gnu.tar.gz"
                sha256 "LINUX_ARM_SHA_PLACEHOLDER"
              end
            end

            name "dtop"
            desc "A terminal-based Docker container monitoring tool"
            homepage "https://github.com/amir20/dtop"

            on_intel do
              on_macos do
                binary "dtop-x86_64-apple-darwin/dtop"

                postflight do
                  system_command "/usr/bin/xattr",
                                args: ["-d", "com.apple.quarantine", "#{staged_path}/dtop-x86_64-apple-darwin/dtop"],
                                must_succeed: false
                end
              end
              on_linux do
                binary "dtop-x86_64-unknown-linux-gnu/dtop"
              end
            end

            on_arm do
              on_macos do
                binary "dtop-aarch64-apple-darwin/dtop"

                postflight do
                  system_command "/usr/bin/xattr",
                                args: ["-d", "com.apple.quarantine", "#{staged_path}/dtop-aarch64-apple-darwin/dtop"],
                                must_succeed: false
                end
              end
              on_linux do
                binary "dtop-aarch64-unknown-linux-gnu/dtop"
              end
            end
          end
          EOF

          # Replace placeholders
          sed -i "s/VERSION_PLACEHOLDER/$VERSION/g" "$CASK_FILE"
          sed -i "s/MACOS_X86_SHA_PLACEHOLDER/${{ steps.assets.outputs.macos_x86_sha }}/g" "$CASK_FILE"
          sed -i "s/MACOS_ARM_SHA_PLACEHOLDER/${{ steps.assets.outputs.macos_arm_sha }}/g" "$CASK_FILE"
          sed -i "s/LINUX_X86_SHA_PLACEHOLDER/${{ steps.assets.outputs.linux_x86_sha }}/g" "$CASK_FILE"
          sed -i "s/LINUX_ARM_SHA_PLACEHOLDER/${{ steps.assets.outputs.linux_arm_sha }}/g" "$CASK_FILE"

          echo "Updated Homebrew Cask to version $VERSION"
          cat "$CASK_FILE"

      - name: Commit and push changes
        working-directory: homebrew-dtop
        run: |
          VERSION="${{ steps.version.outputs.version }}"

          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"

          git add Casks/dtop.rb
          git commit -m "Update dtop to version $VERSION"
          git push

          echo "Successfully updated Homebrew tap to version $VERSION"
