name: ci-cd-vm
on:
  push:
    branches: [main]

# Everything lives on the same Ubuntu VM (Gitea, the registry, the build, and the
# runtime share one Docker daemon), so a single job on the `ubuntu` runner does
# test -> build -> push -> deploy. No cross-machine pull is needed; deploy reuses
# the images just built in the local Docker.
jobs:
  ci-cd:
    runs-on: ubuntu
    defaults:
      run:
        shell: bash
    env:
      REGISTRY: git.golife.love/chrischen
      DEPLOY_DIR: /home/chris/docker/rolac
    steps:
      - uses: actions/checkout@v4

      - name: Test API
        run: dotnet test API/ROLAC.API.Tests/ROLAC.API.Tests.csproj -c Release

      - name: Registry login
        run: echo "${{ secrets.REGISTRY_TOKEN }}" | docker login git.golife.love -u "${{ secrets.REGISTRY_USER }}" --password-stdin

      - name: Build images
        run: |
          docker build -t "$REGISTRY/rolac-api:latest" -t "$REGISTRY/rolac-api:${{ github.sha }}" ./API
          docker build \
            --build-arg KENDO_UI_LICENSE="${{ secrets.KENDO_UI_LICENSE }}" \
            -t "$REGISTRY/rolac-app:latest" -t "$REGISTRY/rolac-app:${{ github.sha }}" ./APP

      - name: Push images
        run: |
          docker push --all-tags "$REGISTRY/rolac-api"
          docker push --all-tags "$REGISTRY/rolac-app"

      - name: Sync compose + nginx to deploy dir
        run: |
          mkdir -p "$DEPLOY_DIR/nginx/conf.d" "$DEPLOY_DIR/data/api-storage"
          cp deploy/vm/docker-compose.yml      "$DEPLOY_DIR/docker-compose.yml"
          cp deploy/vm/nginx/conf.d/rolac.conf "$DEPLOY_DIR/nginx/conf.d/rolac.conf"

      - name: Deploy
        run: |
          cd "$DEPLOY_DIR"
          export TAG=${{ github.sha }}
          docker compose up -d
          sleep 5
          curl -fsS http://localhost:8080/api/health

      # Always runs (success or failure) so the team gets a build result in Rocket.Chat.
      - name: Notify Rocket.Chat
        if: always()
        env:
          JOB_STATUS: ${{ job.status }}
          REPO: ${{ github.repository }}
          REF: ${{ github.ref_name }}
          SHA: ${{ github.sha }}
          ACTOR: ${{ github.actor }}
          COMMIT_URL: ${{ github.server_url }}/${{ github.repository }}/commit/${{ github.sha }}
          WEBHOOK: ${{ secrets.ROCKETCHAT_WEBHOOK }}
        run: |
          if [ "$JOB_STATUS" = "success" ]; then
            STATUS_TEXT="✅ Build succeeded"
            COLOR="#2ecc71"
          else
            STATUS_TEXT="❌ Build failed"
            COLOR="#e74c3c"
          fi
          SHORT_SHA="${SHA:0:7}"
          curl -fsS -X POST -H 'Content-Type: application/json' --data @- "$WEBHOOK" <<JSON
          {
            "attachments": [
              {
                "title": "$REPO — $STATUS_TEXT",
                "title_link": "$COMMIT_URL",
                "color": "$COLOR",
                "text": "Branch *$REF* · commit $SHORT_SHA · by $ACTOR"
              }
            ]
          }
          JSON
