name: Build and Release

on:
  push:
    tags:
      - 'v*'
  workflow_dispatch:

env:
  # Domain for small API calls (goes through Cloudflare - fine for <100MB)
  FORGEJO_API: https://git.sanhost.net/api/v1
  # Direct upload URL (bypasses Cloudflare for large files) - set in repo secrets
  FORGEJO_UPLOAD: ${{ secrets.FORGEJO_UPLOAD_URL }}

jobs:
  create-release:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Create Draft Release
        run: |
          curl -s -X POST "${FORGEJO_API}/repos/${GITHUB_REPOSITORY}/releases" \
            -H "Authorization: token ${{ secrets.RELEASE_TOKEN }}" \
            -H "Content-Type: application/json" \
            -d "{\"tag_name\":\"${{ github.ref_name }}\",\"name\":\"${{ github.ref_name }}\",\"body\":\"Release ${{ github.ref_name }}\",\"draft\":true,\"prerelease\":false}" \
            -o release.json
          cat release.json
          echo "RELEASE_ID=$(cat release.json | python3 -c 'import sys,json; print(json.load(sys.stdin)["id"])')" >> $GITHUB_ENV

  build-windows:
    needs: [create-release]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Install Wine for cross-compilation
        run: |
          sudo dpkg --add-architecture i386
          sudo mkdir -pm755 /etc/apt/keyrings
          sudo wget -O /etc/apt/keyrings/winehq-archive.key https://dl.winehq.org/wine-builds/winehq.key
          sudo wget -NP /etc/apt/sources.list.d/ https://dl.winehq.org/wine-builds/ubuntu/dists/$(lsb_release -cs)/winehq-$(lsb_release -cs).sources
          sudo apt-get update
          sudo apt-get install -y --install-recommends winehq-stable
      - uses: actions/setup-node@v4
        with:
          node-version: '22'
      - run: npm ci

      - name: Build Windows Packages
        run: npx electron-builder --win --publish never --config.npmRebuild=false

      - name: Upload to Release
        run: |
          RELEASE_ID=$(curl -s "${FORGEJO_API}/repos/${GITHUB_REPOSITORY}/releases/tags/${{ github.ref_name }}" \
            -H "Authorization: token ${{ secrets.RELEASE_TOKEN }}" | python3 -c 'import sys,json; print(json.load(sys.stdin)["id"])')
          echo "Release ID: ${RELEASE_ID}"
          echo "Upload URL: ${FORGEJO_UPLOAD}/repos/${GITHUB_REPOSITORY}/releases/${RELEASE_ID}/assets"
          for file in dist/*.exe dist/*.exe.blockmap dist/latest.yml; do
            [ -f "$file" ] || continue
            echo "Uploading $file ($(stat -c%s "$file" 2>/dev/null || stat -f%z "$file") bytes)..."
            HTTP_CODE=$(curl -w '%{http_code}' --max-time 600 -X POST "${FORGEJO_UPLOAD}/repos/${GITHUB_REPOSITORY}/releases/${RELEASE_ID}/assets?name=$(basename $file)" \
              -H "Authorization: token ${{ secrets.RELEASE_TOKEN }}" \
              -F "attachment=@${file}" -o /tmp/upload_response.txt 2>/tmp/upload_err.txt)
            if [ "$HTTP_CODE" = "201" ]; then
              echo "OK — uploaded $(basename $file)"
            else
              echo "FAILED (HTTP $HTTP_CODE): $(cat /tmp/upload_response.txt)"
              echo "Curl stderr: $(cat /tmp/upload_err.txt)"
            fi
          done

  build-macos:
    needs: [create-release]
    runs-on: macos-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '22'
      - run: npm ci

      - name: Build macOS Packages
        env:
          CSC_LINK: ${{ secrets.CSC_LINK }}
          CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
          APPLE_ID: ${{ secrets.APPLE_ID }}
          APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
          APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
        run: npx electron-builder --mac --publish never

      - name: Upload to Release
        run: |
          RELEASE_ID=$(curl -s "${FORGEJO_API}/repos/${GITHUB_REPOSITORY}/releases/tags/${{ github.ref_name }}" \
            -H "Authorization: token ${{ secrets.RELEASE_TOKEN }}" | python3 -c 'import sys,json; print(json.load(sys.stdin)["id"])')
          echo "Release ID: ${RELEASE_ID}"
          for file in dist/*.dmg dist/*.zip dist/*.blockmap dist/latest-mac.yml; do
            [ -f "$file" ] || continue
            echo "Uploading $file..."
            HTTP_CODE=$(curl -w '%{http_code}' --max-time 600 -X POST "${FORGEJO_UPLOAD}/repos/${GITHUB_REPOSITORY}/releases/${RELEASE_ID}/assets?name=$(basename $file)" \
              -H "Authorization: token ${{ secrets.RELEASE_TOKEN }}" \
              -F "attachment=@${file}" -o /tmp/upload_response.txt 2>/tmp/upload_err.txt)
            if [ "$HTTP_CODE" = "201" ]; then
              echo "OK — uploaded $(basename $file)"
            else
              echo "FAILED (HTTP $HTTP_CODE): $(cat /tmp/upload_response.txt)"
              echo "Curl stderr: $(cat /tmp/upload_err.txt)"
            fi
          done

  build-linux:
    runs-on: ubuntu-latest
    needs: [create-release]
    steps:
      - uses: actions/checkout@v4
      - name: Install build dependencies
        run: |
          sudo apt-get update
          sudo apt-get install -y libarchive-tools rpm

      - uses: actions/setup-node@v4
        with:
          node-version: '22'
      - run: npm ci

      - name: Build Linux Packages
        run: npx electron-builder --linux AppImage deb rpm pacman --publish never

      - name: Upload to Release
        run: |
          RELEASE_ID=$(curl -s "${FORGEJO_API}/repos/${GITHUB_REPOSITORY}/releases/tags/${{ github.ref_name }}" \
            -H "Authorization: token ${{ secrets.RELEASE_TOKEN }}" | python3 -c 'import sys,json; print(json.load(sys.stdin)["id"])')
          echo "Release ID: ${RELEASE_ID}"
          for file in dist/*.AppImage dist/*.AppImage.blockmap dist/*.deb dist/*.rpm dist/*.pacman dist/latest-linux.yml; do
            [ -f "$file" ] || continue
            echo "Uploading $file ($(stat -c%s "$file" 2>/dev/null || stat -f%z "$file") bytes)..."
            HTTP_CODE=$(curl -w '%{http_code}' --max-time 600 -X POST "${FORGEJO_UPLOAD}/repos/${GITHUB_REPOSITORY}/releases/${RELEASE_ID}/assets?name=$(basename $file)" \
              -H "Authorization: token ${{ secrets.RELEASE_TOKEN }}" \
              -F "attachment=@${file}" -o /tmp/upload_response.txt 2>/tmp/upload_err.txt)
            if [ "$HTTP_CODE" = "201" ]; then
              echo "OK — uploaded $(basename $file)"
            else
              echo "FAILED (HTTP $HTTP_CODE): $(cat /tmp/upload_response.txt)"
              echo "Curl stderr: $(cat /tmp/upload_err.txt)"
            fi
          done
