name: Build & Deploy Backend

on:
  push:
    branches:
      - main

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

      - name: Set up JDK 17
        uses: actions/setup-java@v3
        with:
          distribution: 'temurin'
          java-version: '17'

      - name: Build with Gradle
        run: ./gradlew clean build -x test

      - name: Upload artifact
        uses: actions/upload-artifact@v3
        with:
          name: backend-jar
          path: build/libs/*.jar

  deploy:
    runs-on: [backend]
    needs: build
    steps:
      - name: Download artifact
        uses: actions/download-artifact@v3
        with:
          name: backend-jar
          path: /home/sonder/deploy

      - name: List deploy directory
        run: ls -al /home/sonder/deploy

      - name: Stop service
        run: sudo systemctl stop ld-sysinfo-server || true

      - name: Deploy new jar
        run: |
          sudo mkdir -p /opt/ld-sysinfo-server
          JAR=$(ls /home/sonder/deploy/*-SNAPSHOT.jar | grep -v plain)
          sudo cp "$JAR" /opt/ld-sysinfo-server/app.jar
          sudo chown sonder:sonder /opt/ld-sysinfo-server/app.jar
      - name: Start service
        run: sudo systemctl start ld-sysinfo-server
