name: Build, Push, and Deploy to Nomad

on:
  push:
    branches:
      - main

jobs:
  docker-nomad:
    runs-on: self-hosted
    steps:
      - name: Check out code
        uses: actions/checkout@v3

      - name: Log in to Container Registry
        run: echo ${{ secrets.password }} | docker login registry.i80.dk -u ${{ secrets.username }} --password-stdin

      - name: Build Docker Image
        run: |
          COMMIT_HASH=$(git rev-parse --short HEAD)
          docker build -t registry.i80.dk/gitea/[[PROJECT_NAME]]:latest -t registry.i80.dk/gitea/[[PROJECT_NAME]]:${COMMIT_HASH} .


      - name: Push Docker Image
        run: |
          COMMIT_HASH=$(git rev-parse --short HEAD)
          echo "registry.i80.dk/gitea/[[PROJECT_NAME]]:latest"
          echo "registry.i80.dk/gitea/[[PROJECT_NAME]]:${COMMIT_HASH}"
          docker push registry.i80.dk/gitea/[[PROJECT_NAME]]:${COMMIT_HASH}
          docker push registry.i80.dk/gitea/[[PROJECT_NAME]]:latest


      - name: Validate Nomad Job
        env:
          NOMAD_ADDR: https://nomad.i80.dk
        run: nomad job validate .gitea/workflows/nomad-job.hcl

#      - name: Stop old deployment
#        env:
#          NOMAD_ADDR: https://nomad.i80.dk
#        run: nomad job stop -purge -no-shutdown-delay [[PROJECT_NAME]]
#        continue-on-error: true


      - name: Apply Nomad Job
        env:
          NOMAD_ADDR: https://nomad.i80.dk
        run: nomad job run .gitea/workflows/nomad-job.hcl

      - name: Update Nginx Configuration
        run:  ssh runner@nomad sudo /opt/nginx_updater/venv/bin/python3 /opt/nginx_updater/nginx_updater.py [[PROJECT_NAME]]

      - name: Update Forwarder Configuration
        run:  ssh runner@nomad sudo /opt/nginx_updater/venv/bin/python3 /opt/nginx_updater/update_forwarder.py [[PROJECT_NAME]]


#      - name: Restart Nomad Job
#        env:
#          NOMAD_ADDR: https://nomad.i80.dk
#        run: |
#          nomad job stop [[PROJECT_NAME]]
#          sleep 5  # Optional: Wait to ensure the old allocation is stopped
#          nomad job run .gitea/workflows/nomad-job.hcl
