name: Nightly Release

on:
  push:
    branches:
      - master
  workflow_dispatch:

permissions:
  contents: write

jobs:
  nightly:
    runs-on: macos-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Set up Go
        uses: actions/setup-go@v6
        with:
          go-version: "1.26.1"

      - name: Set up Zig
        uses: goto-bus-stop/setup-zig@v2

      - name: Set up libpcsclite for Linux cross-compilation
        run: |
          PCSC_DIR="$RUNNER_TEMP/pcsclite"
          mkdir -p "$PCSC_DIR/include" "$PCSC_DIR/lib/pkgconfig"

          # Download pcsc-lite headers from upstream
          for header in winscard.h pcsclite.h wintypes.h; do
            curl -fsSL "https://raw.githubusercontent.com/LudovicRousseau/PCSC/master/src/PCSC/$header" \
              -o "$PCSC_DIR/include/$header"
          done

          # Create pkg-config file (headers-only, no library needed for cross-compilation)
          cat > "$PCSC_DIR/lib/pkgconfig/libpcsclite.pc" << EOF
          Name: libpcsclite
          Description: PC/SC Lite
          Version: 1.9.0
          Cflags: -I$PCSC_DIR/include
          EOF

          echo "PKG_CONFIG_PATH=$PCSC_DIR/lib/pkgconfig" >> $GITHUB_ENV

      - name: Get macOS SDK path
        id: macos_sdk
        run: echo "path=$(xcrun --show-sdk-path)" >> $GITHUB_OUTPUT

      - name: Build with GoReleaser (snapshot)
        uses: goreleaser/goreleaser-action@v7
        with:
          version: latest
          args: release --snapshot --clean --config .goreleaser.nightly.yml
        env:
          SDK_PATH: ${{ steps.macos_sdk.outputs.path }}

      - name: Delete existing nightly release
        env:
          GH_TOKEN: ${{ secrets.HOMEBREW_TAP_GITHUB_TOKEN }}
        run: |
          gh release delete nightlyv0 --yes --cleanup-tag || true

      - name: Generate release notes
        id: notes
        env:
          GH_TOKEN: ${{ secrets.HOMEBREW_TAP_GITHUB_TOKEN }}
        run: |
          SHORT_SHA="$(git rev-parse --short HEAD)"
          LATEST_TAG="$(git describe --tags --abbrev=0 --exclude='nightlyv*' 2>/dev/null || echo '')"

          {
            echo 'BODY<<EOF'
            echo "> [!WARNING]"
            echo "> This is an automated nightly build from the latest \`master\` commit (\`$SHORT_SHA\`). It may be unstable — use stable releases for production."
            echo ""
            echo "### Install"
            echo ""
            echo "- **Homebrew:** \`brew install floatpane/matcha/matcha-nightly\`"
            echo "- **Snapcraft:** \`snap install matcha --beta\`"

            if [ -n "$LATEST_TAG" ]; then
              echo ""
              echo "### Changes since $LATEST_TAG"
              echo ""
              git log --pretty=format:"- %s (%h)" "$LATEST_TAG..HEAD"
              echo ""
            fi

            echo 'EOF'
          } >> "$GITHUB_OUTPUT"

      - name: Create nightly release
        env:
          GH_TOKEN: ${{ secrets.HOMEBREW_TAP_GITHUB_TOKEN }}
        run: |
          gh release create nightlyv0 dist/*.tar.gz dist/*.zip dist/checksums.txt \
            --title "Nightly Build ($(git rev-parse --short HEAD))" \
            --notes "${{ steps.notes.outputs.BODY }}" \
            --prerelease \
            --target master

      - name: Update Homebrew tap
        env:
          GH_TOKEN: ${{ secrets.HOMEBREW_TAP_GITHUB_TOKEN }}
        run: |
          VERSION="nightly-$(git rev-parse --short HEAD)"
          DARWIN_AMD64_SHA=$(shasum -a 256 dist/matcha_nightly_darwin_amd64.tar.gz | cut -d ' ' -f 1)
          DARWIN_ARM64_SHA=$(shasum -a 256 dist/matcha_nightly_darwin_arm64.tar.gz | cut -d ' ' -f 1)
          LINUX_AMD64_SHA=$(shasum -a 256 dist/matcha_nightly_linux_amd64.tar.gz | cut -d ' ' -f 1)
          LINUX_ARM64_SHA=$(shasum -a 256 dist/matcha_nightly_linux_arm64.tar.gz | cut -d ' ' -f 1)
          BASE_URL="https://github.com/floatpane/matcha/releases/download/nightlyv0"

          cat > /tmp/matcha-nightly.rb << EOF
          class MatchaNightly < Formula
            desc "A beautiful and functional email client for your terminal (nightly)"
            homepage "https://matcha.floatpane.com"
            version "$VERSION"

            on_macos do
              if Hardware::CPU.intel?
                url "$BASE_URL/matcha_nightly_darwin_amd64.tar.gz"
                sha256 "$DARWIN_AMD64_SHA"
              else
                url "$BASE_URL/matcha_nightly_darwin_arm64.tar.gz"
                sha256 "$DARWIN_ARM64_SHA"
              end
            end

            on_linux do
              if Hardware::CPU.intel?
                url "$BASE_URL/matcha_nightly_linux_amd64.tar.gz"
                sha256 "$LINUX_AMD64_SHA"
              else
                url "$BASE_URL/matcha_nightly_linux_arm64.tar.gz"
                sha256 "$LINUX_ARM64_SHA"
              end
            end

            def install
              bin.install "matcha"
            end

            test do
              system "#{bin}/matcha", "--version"
            end
          end
          EOF

          # Clone the tap repo and push the nightly formula
          git clone "https://x-access-token:${GH_TOKEN}@github.com/floatpane/homebrew-matcha.git" /tmp/homebrew-matcha
          cp /tmp/matcha-nightly.rb /tmp/homebrew-matcha/matcha-nightly.rb
          cd /tmp/homebrew-matcha
          git config user.name "goreleaserbot"
          git config user.email "bot@goreleaser.com"
          git add matcha-nightly.rb
          git diff --cached --quiet || (git commit -m "Update matcha-nightly to $VERSION" && git push)

  snapcraft:
    runs-on: ${{ matrix.runner }}
    needs: nightly
    strategy:
      matrix:
        include:
          - arch: amd64
            runner: ubuntu-latest
          - arch: arm64
            runner: ubuntu-24.04-arm
    steps:
      - name: Checkout
        uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Install Snapcraft and LXD
        run: |
          sudo snap install snapcraft --classic
          sudo snap install lxd
          sudo lxd init --auto
          sudo iptables -P FORWARD ACCEPT
          sudo usermod -aG lxd $USER

      - name: Build snap
        run: sg lxd -c 'snapcraft pack --use-lxd --build-for=${{ matrix.arch }}'

      - name: Upload snap
        env:
          SNAPCRAFT_STORE_CREDENTIALS: ${{ secrets.SNAPCRAFT_STORE_CREDENTIALS }}
        run: snapcraft upload --release=beta *.snap
