name: Build and Release to Staging

on:
  push:
    branches:
      - main
  workflow_dispatch:

env:
  REGISTRY_HOST: git.ivanch.me
  REGISTRY_USERNAME: ivanch
  IMAGE_NAME: ${{ env.REGISTRY_HOST }}/ivanch/vision-start
  IMAGE_TAG: staging

jobs:
  build:
    name: Build Vision Start
    runs-on: ubuntu-amd64
    steps:
      - name: Check out repository code
        uses: actions/checkout@v4

      - name: Setup required tools
        run: sudo apt-get install zip jq curl -y

      - name: Install JS dependencies
        run: npm install

      - name: Run build
        run: |
          bash scripts/prepare_release.sh
          npm run build

      - name: Prepare release
        run: |
          mv dist vision-start/
          mv extension vision-start/
          mv manifest.json vision-start/

      - name: Create zip archive
        run: |
          cd vision-start
          zip -r ../vision-start-${{ gitea.ref_name }}.zip *

      - name: Upload artifact
        uses: actions/upload-artifact@v3
        with:
          name: release-zip
          path: vision-start-${{ gitea.ref_name }}.zip

  build_vision_start:
    name: Build Vision Start Image
    runs-on: ubuntu-amd64
    needs: build
    steps:
      - name: Check out repository
        uses: actions/checkout@v2

      - name: Log in to Container Registry
        run: |
          echo "${{ secrets.REGISTRY_PASSWORD }}" \
            | docker login "${{ env.REGISTRY_HOST }}" \
                -u "${{ env.REGISTRY_USERNAME }}" \
                --password-stdin

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

      - name: Build and Push Multi-Arch Image
        uses: docker/build-push-action@v6
        with:
          push: true
          context: .
          platforms: linux/amd64,linux/arm64
          tags: |
            ${{ env.IMAGE_NAME }}:${{ env.IMAGE_TAG }}

  deploy_vision_start:
    name: Deploy Vision Start (staging)
    runs-on: ubuntu-amd64
    needs: build_vision_start
    steps:
      - name: Recreate Container
        uses: appleboy/ssh-action@v0.1.7
        with:
          host: ${{ secrets.HOST }}
          username: ${{ secrets.USERNAME }}
          key: ${{ secrets.KEY }}
          port: ${{ secrets.PORT }}
          script: |
            cd ${{ secrets.STAGING_DIR }}
            docker compose pull
            docker compose up -d --force-recreate
