name: Build & Release

on:
  push:
    tags:
      - 'v*'

jobs:
  build:
    runs-on: docker
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: '20'

      - name: Install pnpm
        run: npm install -g pnpm@10

      - name: Install dependencies
        run: pnpm install

      - name: Set version from tag
        run: |
          VERSION="${{ github.ref_name }}"
          VERSION="${VERSION#v}"
          node -e "const fs=require('fs'),p=JSON.parse(fs.readFileSync('package.json')); p.version='$VERSION'; fs.writeFileSync('package.json', JSON.stringify(p, null, 2)+'\n')"

      - name: Install Linux build deps
        run: apt-get update && apt-get install -y --fix-missing python3 make g++ libgtk-3-dev libnss3-dev libxss1 libasound2-dev libgbm-dev dpkg fakeroot zip

      - name: Build Linux (deb + zip)
        run: pnpm make
        env:
          PLATFORM: linux

      - name: Build Windows (zip)
        run: pnpm make --platform win32 --arch x64
        env:
          PLATFORM: win32

      - name: Create release and upload artifacts
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          TAG="${{ github.ref_name }}"
          API="${{ github.server_url }}/api/v1/repos/${{ github.repository }}"

          RELEASE_ID=$(curl -sf -X POST \
            -H "Authorization: token $GITHUB_TOKEN" \
            -H "Content-Type: application/json" \
            "$API/releases" \
            -d "{\"tag_name\":\"$TAG\",\"name\":\"Sanctum $TAG\"}" \
            | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])")

          find out/make -name "*.deb" -o -name "*.zip" | while read file; do
            curl -sf -X POST \
              -H "Authorization: token $GITHUB_TOKEN" \
              -H "Content-Type: application/octet-stream" \
              "$API/releases/$RELEASE_ID/assets?name=$(basename "$file")" \
              --data-binary @"$file"
          done
