name: Build and Deploy classify service

on:
  push:
    branches:
      - main
    paths:
      - "scripts/classify_server.py"
      - "scripts/taxonomy.py"
      - "Dockerfile.classify"
      - "classify.nomad"
  workflow_dispatch:

env:
  SERVICE_NAME: classify

jobs:
  build-and-deploy:
    runs-on: debian-host

    env:
      PATH: /usr/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/sbin:/bin:/snap/bin
      DOCKER_HOST: unix:///var/run/docker.sock

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Log in to Docker Registry
        run: |
          echo "${{ secrets.HARBOR_ROBOT_TOKEN }}" | docker login registry.i80.dk -u "robot\$gitserver" --password-stdin

      - name: Build Docker image
        run: |
          SHA=$(git rev-parse --short HEAD)
          docker build -f Dockerfile.classify \
            -t registry.i80.dk/gitea/kreuzberg-classify:latest \
            -t registry.i80.dk/gitea/kreuzberg-classify:$SHA .

      - name: Push Docker image
        run: |
          SHA=$(git rev-parse --short HEAD)
          docker push registry.i80.dk/gitea/kreuzberg-classify:latest
          docker push registry.i80.dk/gitea/kreuzberg-classify:$SHA

      - name: Validate Nomad job
        run: nomad job validate classify.nomad
        env:
          NOMAD_ADDR: "https://nomad.i80.dk:4646"

      - name: Deploy to Nomad
        run: nomad job run classify.nomad
        env:
          NOMAD_ADDR: "https://nomad.i80.dk:4646"

      - name: Wait for healthy allocation
        run: |
          sleep 15
          nomad job status ${SERVICE_NAME}
          nomad job allocs ${SERVICE_NAME}
        env:
          NOMAD_ADDR: "https://nomad.i80.dk:4646"
