name: CI/CD Pipeline

on:
  push:
    branches:
      - main
  workflow_dispatch:

env:
  DOCKER_REPO: {{ dockerhub_username|default('user') }}/{{ project_name|lower }}
  BACKEND_TAG_LATEST: backend-latest

jobs:
  dockerhub:
    name: Build, Tag and Push on Docker Hub
    runs-on: ubuntu-latest

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

      - name: Log in to Docker Hub
        env:
          DOCKERHUB_USERNAME: {% raw %}${{ secrets.DOCKERHUB_USERNAME }}{% endraw %}
          DOCKERHUB_TOKEN: {% raw %}${{ secrets.DOCKERHUB_TOKEN }}{% endraw %}
        run: |
          echo "$DOCKERHUB_TOKEN" | docker login -u "$DOCKERHUB_USERNAME" --password-stdin

      - name: Build backend image
        run: |
          docker build --no-cache -t $DOCKER_REPO:$BACKEND_TAG_LATEST backend/

      - name: Push backend image
        run: docker push $DOCKER_REPO:$BACKEND_TAG_LATEST
        
  deploy:
    name: Deploy to EC2
    runs-on: ubuntu-latest
    needs: dockerhub

    steps:
      - name: SSH to EC2 and deploy
        uses: appleboy/ssh-action@v1.0.0
        with:
          host: {% raw %}${{ secrets.EC2_HOST }}{% endraw %}
          username: {% raw %}${{ secrets.EC2_USER }}{% endraw %}
          key: {% raw %}${{ secrets.EC2_SSH_PRIVATE_KEY }}{% endraw %}
          script: |
            set -e
            cd /home/ubuntu/{{ project_name }}
            # Clean up old unused images and containers to free up space
            docker system prune -af
            docker compose -f docker-compose.prod.yml down
            docker compose -f docker-compose.prod.yml pull
            docker compose -f docker-compose.prod.yml up -d --force-recreate --remove-orphans
