name: Deploy to Production

on:
  push:
    branches:
      - prod

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    container:
      image: docker:24-dind
      options: --privileged
    
    steps:
      - name: Install git
        run: apk add --no-cache git
      
      - name: Checkout code
        run: |
          git clone --depth 1 --branch prod https://${{ secrets.REGISTRY_USERNAME }}:${{ secrets.REGISTRY_TOKEN }}@git.local.evan.casa/evan/lediscord.git .
      
      - name: Login to Registry
        run: |
          echo "${{ secrets.REGISTRY_TOKEN }}" | docker login ${{ secrets.REGISTRY_URL }} -u ${{ secrets.REGISTRY_USERNAME }} --password-stdin
      
      - name: Build and push backend
        run: |
          docker build -t ${{ secrets.REGISTRY_URL }}/${{ secrets.REGISTRY_USERNAME }}/lediscord:prod-backend ./backend
          for i in 1 2 3 4 5; do
            docker push ${{ secrets.REGISTRY_URL }}/${{ secrets.REGISTRY_USERNAME }}/lediscord:prod-backend && break || sleep 10
          done
      
      - name: Build and push frontend
        run: |
          docker build -t ${{ secrets.REGISTRY_URL }}/${{ secrets.REGISTRY_USERNAME }}/lediscord:prod-frontend ./frontend
          for i in 1 2 3 4 5; do
            docker push ${{ secrets.REGISTRY_URL }}/${{ secrets.REGISTRY_USERNAME }}/lediscord:prod-frontend && break || sleep 10
          done
      
      - name: Done
        run: |
          echo "🚀 Images pushed! Run: nomad job run -force lediscord.nomad"