name: Build MIPS Binary

on:
  push:
    branches: [ "main" ]

env:
  CARGO_TERM_COLOR: always

jobs:
  build:
    runs-on: mips-builder

    steps:
    - name: Checkout
      env:
        GIT_TOKEN: ${{ secrets.RELEASE_TOKEN }}
      run: |
        rm -rf .git
        git init .
        git remote add origin https://admin:$\{GIT_TOKEN\}@git.karatatar.com/admin/vibetorrent.git
        git fetch --depth=1 origin ${{ gitea.sha }}
        git checkout FETCH_HEAD

    - name: Build Frontend
      run: |
        cd frontend
        npm install
        npx @tailwindcss/cli -i input.css -o public/tailwind.css --minify --content './src/**/*.rs'
        # Trunk'ın optimizasyonunu kapalı (0) tutuyoruz çünkü Cargo.toml'daki opt-level='z' zaten o işi yapıyor.
        trunk build --release

    - name: Build Backend (MIPS)
      env:
        # -s ve -w ile binary içindeki gereksiz tüm yükleri siliyoruz.
        RUSTFLAGS: "-C target-feature=+crt-static -C link-self-contained=no -C link-arg=-msoft-float -C link-arg=-s -C link-arg=-w"
        CFLAGS_mips_unknown_linux_musl: "-msoft-float"
      run: |
        # Sadece gerekli özellikleri derliyoruz (Boyut tasarrufu için swagger kapalı)
        cargo zigbuild -p backend --target mips-unknown-linux-musl --release -Z build-std=std,panic_abort --no-default-features --features push-notifications

    - name: Create Release Assets
      run: |
        mv target/mips-unknown-linux-musl/release/backend target/mips-unknown-linux-musl/release/vibetorrent-mips

    - name: Generate Release Tag
      id: tag
      run: echo "release_tag=release-$(date +'%Y%m%d-%H%M')" >> "$GITHUB_OUTPUT"

    - name: Create Release
      env:
        RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
      run: |
        TAG="${{ steps.tag.outputs.release_tag }}"
        REPO="admin/vibetorrent"
        API_URL="${{ gitea.server_url }}/api/v1"

        RELEASE_RESPONSE=$(curl -s -X POST "${API_URL}/repos/${REPO}/releases" \
          -H "Authorization: token ${RELEASE_TOKEN}" \
          -H "Content-Type: application/json" \
          -d "{
            \"tag_name\": \"${TAG}\",
            \"name\": \"Release ${TAG}\",
            \"body\": \"Automated build from commit ${{ gitea.sha }}\",
            \"draft\": false,
            \"prerelease\": false
          }")

        RELEASE_ID=$(echo "$RELEASE_RESPONSE" | jq -r '.id')
        if [ "$RELEASE_ID" = "null" ] || [ -z "$RELEASE_ID" ]; then exit 1; fi

        curl -s -X POST "${API_URL}/repos/${REPO}/releases/${RELEASE_ID}/assets?name=vibetorrent-mips" \
          -H "Authorization: token ${RELEASE_TOKEN}" \
          -H "Content-Type: application/octet-stream" \
          --data-binary @target/mips-unknown-linux-musl/release/vibetorrent-mips