name: Publish Release Assets

on:
  release:
    types: [published]

permissions:
  contents: write

jobs:
  publish:
    name: Publish Release Assets
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Setup Bun
        uses: oven-sh/setup-bun@v1
        with:
          bun-version: 'latest'

      - name: Cache Bun dependencies
        uses: actions/cache@v3
        with:
          path: |
            ~/.bun
          key: ${{ runner.os }}-bun-cache-${{ hashFiles('**/bun.lockb') }}
          restore-keys: |
            ${{ runner.os }}-bun-cache-

      - name: Install deps
        run: bun install --cache

      - name: Build
        run: bun run build

      - name: Run publish script
        run: |
          chmod +x scripts/publish.sh
          ./scripts/publish.sh

      - name: Upload tar.gz file to release
        uses: softprops/action-gh-release@v2
        with:
          files: |
            out/ppanel-admin-web.tar.gz
            out/ppanel-user-web.tar.gz
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Log in to Docker Hub
        uses: docker/login-action@v2
        with:
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}

      - name: Install jq
        run: sudo apt-get install -y jq

      - name: Extract version from package.json
        id: version
        run: echo "PPANEL_VERSION=$(jq -r '.version' package.json)" >> $GITHUB_ENV

      - name: Build and push Docker image for ppanel-admin-web
        uses: docker/build-push-action@v6
        with:
          context: .
          file: ./docker/ppanel-admin-web/Dockerfile
          platforms: linux/amd64,linux/arm64
          push: true
          tags: |
            ${{ secrets.DOCKER_USERNAME }}/ppanel-admin-web:latest
            ${{ secrets.DOCKER_USERNAME }}/ppanel-admin-web:${{ env.PPANEL_VERSION }}

      - name: Build and push Docker image for ppanel-user-web
        uses: docker/build-push-action@v6
        with:
          context: .
          file: ./docker/ppanel-user-web/Dockerfile
          platforms: linux/amd64,linux/arm64
          push: true
          tags: |
            ${{ secrets.DOCKER_USERNAME }}/ppanel-user-web:latest
            ${{ secrets.DOCKER_USERNAME }}/ppanel-user-web:${{ env.PPANEL_VERSION }}
