name: deploy music
# music.famzheng.me — 听歌 + 练琴 曲目管理。host shell runner（fam 用户）。

on:
  push:
    branches: [master]
    paths:
      - 'apps/music/**'
      - 'crates/cube-core/**'
      - 'Cargo.toml'
      - 'Cargo.lock'
      - '.gitea/workflows/deploy-music.yml'
  workflow_dispatch:

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    env:
      APP: music
      NS: cube-music
      IMAGE: registry.famzheng.me/mochi/music
      CHORD_IMAGE: registry.famzheng.me/mochi/music-chord
    steps:
      - uses: actions/checkout@v4

      - name: Resolve image tag
        id: tag
        run: |
          echo "sha=$(git rev-parse --short=12 HEAD)" >> "$GITHUB_OUTPUT"

      - name: Build rust (musl static)
        run: |
          export PATH="$HOME/.cargo/bin:$PATH"
          cargo build --release --target x86_64-unknown-linux-musl -p "$APP"

      - name: Build frontend
        run: |
          cd "apps/$APP/frontend"
          npm ci
          npm run build

      - name: Build & push images
        env:
          REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
        run: |
          echo "$REGISTRY_TOKEN" | docker login registry.famzheng.me -u mochi --password-stdin
          # main app —— 必须 --no-cache，否则 docker layer cache 会把"COPY target/.../music"
          # 这一层套用历史 binary（之前几次 deploy 实测过：cargo 生成了新 binary 但
          # docker 看缓存 layer 命中直接复用旧 binary，新代码完全没进 image）
          docker build --no-cache -f "apps/$APP/Dockerfile" \
            -t "$IMAGE:${{ steps.tag.outputs.sha }}" .
          docker push "$IMAGE:${{ steps.tag.outputs.sha }}"
          # chord-fetcher sidecar：layer cache 这里有用（chromium apt 不变），保留
          docker build -f "apps/$APP/chord/Dockerfile" \
            -t "$CHORD_IMAGE:${{ steps.tag.outputs.sha }}" \
            "apps/$APP/chord"
          docker push "$CHORD_IMAGE:${{ steps.tag.outputs.sha }}"

      - name: Initialize K8s resources
        run: |
          kubectl apply -f apps/music/k8s/all.yaml

      - name: Roll out to k3s
        run: |
          kubectl -n "$NS" set image "deploy/$APP" \
            "$APP=$IMAGE:${{ steps.tag.outputs.sha }}" \
            "chord-fetcher=$CHORD_IMAGE:${{ steps.tag.outputs.sha }}"
          kubectl -n "$NS" rollout status "deploy/$APP" --timeout=300s
