name: Build & Deploy OS League Tools

on:
  push:
    branches:
      - main

jobs:
  build:
    runs-on: ["cicd"]
    steps:
      - name: Checkout code
        uses: actions/checkout@v3

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
          cache-dependency-path: os-league-tools-master/package-lock.json

      - name: Install dependencies
        working-directory: os-league-tools-master
        run: npm ci

      - name: Build production bundle
        working-directory: os-league-tools-master
        run: npm run build
        env:
          CI: false

      - name: Upload artifact
        uses: actions/upload-artifact@v3
        with:
          name: frontend-build
          path: os-league-tools-master/build/

  deploy:
    runs-on: [frontend]
    needs: build
    steps:
      - name: Download artifact
        uses: actions/download-artifact@v3
        with:
          name: frontend-build
          path: /home/sonder/deploy/os-league-tools-build

      - name: List deploy directory
        run: ls -al /home/sonder/deploy/os-league-tools-build

      - name: Stop service
        run: sudo systemctl stop os-league-tools || true

      - name: Deploy new build
        run: |
          sudo rm -rf /home/sonder/leagues-tools/os-league-tools-master/build
          sudo cp -r /home/sonder/deploy/os-league-tools-build /home/sonder/leagues-tools/os-league-tools-master/build
          sudo chown -R sonder:sonder /home/sonder/leagues-tools/os-league-tools-master/build

      - name: Start service
        run: sudo systemctl start os-league-tools

      - name: Cleanup deploy artifacts
        run: rm -rf /home/sonder/deploy/os-league-tools-build
