name: "Update Flake Hash"

on:
  release:
    types: [published]

permissions:
  contents: write

jobs:
  update-flake:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Install Nix
        uses: DeterminateSystems/nix-installer-action@main

      - name: Get AppImage hash
        id: hash
        env:
          RELEASE_VERSION: ${{ github.event.release.tag_name }}
        run: |
          # Remove 'v' prefix from tag if present
          VERSION="${RELEASE_VERSION#v}"
          APPIMAGE_URL="https://github.com/${{ github.repository }}/releases/download/v${VERSION}/Handy_${VERSION}_amd64.AppImage"

          echo "Computing hash for: $APPIMAGE_URL"

          # Retry logic in case AppImage isn't immediately available
          for i in {1..30}; do
            HASH=$(nix-prefetch-url --name "Handy_${VERSION}_amd64.AppImage" "$APPIMAGE_URL" 2>&1 | grep "^sha256-" || true)
            if [ -n "$HASH" ]; then
              echo "hash=$HASH" >> "$GITHUB_OUTPUT"
              echo "Successfully computed hash: $HASH"
              exit 0
            fi
            echo "Attempt $i: AppImage not yet available, waiting..."
            sleep 5
          done

          echo "Failed to fetch AppImage after retries"
          exit 1

      - name: Update flake.nix
        env:
          HASH: ${{ steps.hash.outputs.hash }}
        run: |
          sed -i "s|hash = \"sha256-[^\"]*\"|hash = \"$HASH\"|" flake.nix

          # Verify the hash was actually updated
          if ! grep -q "hash = \"$HASH\"" flake.nix; then
            echo "ERROR: Failed to update hash in flake.nix"
            exit 1
          fi
          echo "Successfully updated flake.nix with hash: $HASH"

      - name: Commit and push
        env:
          VERSION: ${{ github.event.release.tag_name }}
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"

          # Only commit if flake.nix actually changed
          if git diff --quiet flake.nix; then
            echo "Hash already up-to-date, no commit needed"
          else
            git add flake.nix
            git commit -m "chore(nix): update AppImage hash for ${VERSION}"
            git push
            echo "Successfully pushed hash update"
          fi
