name: Update Vendor Hash

on:
  push:
    paths:
      - "go.mod"
      - "go.sum"
    branches:
      - master

jobs:
  update-vendor-hash:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Install Nix
        uses: cachix/install-nix-action@v31

      - name: Update vendorHash in flake.nix
        run: |
          set -euo pipefail

          # Try to build and capture the expected hash from error message
          echo "Attempting nix build to get new vendorHash..."
          if output=$(nix build .#dms-cli 2>&1); then
            echo "Build succeeded, no hash update needed"
            exit 0
          fi

          # Extract the expected hash from the error message
          new_hash=$(echo "$output" | grep -oP "got:\s+\K\S+" | head -n1)

          if [ -z "$new_hash" ]; then
            echo "Could not extract new vendorHash from build output"
            echo "Build output:"
            echo "$output"
            exit 1
          fi

          echo "New vendorHash: $new_hash"

          # Get current hash from flake.nix
          current_hash=$(grep -oP 'vendorHash = "\K[^"]+' flake.nix)
          echo "Current vendorHash: $current_hash"

          if [ "$current_hash" = "$new_hash" ]; then
            echo "vendorHash is already up to date"
            exit 0
          fi

          # Update the hash in flake.nix
          sed -i "s|vendorHash = \"$current_hash\"|vendorHash = \"$new_hash\"|" flake.nix

          # Verify the build works with the new hash
          echo "Verifying build with new vendorHash..."
          nix build .#dms-cli

          echo "vendorHash updated successfully!"

      - name: Commit and push vendorHash update
        run: |
          set -euo pipefail

          if ! git diff --quiet flake.nix; then
            git config user.name "github-actions[bot]"
            git config user.email "github-actions[bot]@users.noreply.github.com"

            git add flake.nix
            git commit -m "flake: update vendorHash for go.mod changes"

            for attempt in 1 2 3; do
              if git push; then
                echo "Successfully pushed vendorHash update"
                exit 0
              fi
              echo "Push attempt $attempt failed, pulling and retrying..."
              git pull --rebase
              sleep $((attempt*2))
            done

            echo "Failed to push after retries" >&2
            exit 1
          else
            echo "No changes to flake.nix"
          fi
