name: Build and Deploy Production

on:
  push:
    tags:
      - "v*"

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    container:
      image: catthehacker/ubuntu:act-latest
    env:
      DOCKER_REGISTRY: git.comprofix.com
      IMAGE_NAME: mmckinnon/comprofix.com
    steps:
      - uses: actions/checkout@v4

      - uses: docker/setup-buildx-action@v3

      - uses: docker/login-action@v3
        with:
          registry: ${{ env.DOCKER_REGISTRY }}
          username: ${{ secrets.REGISTRY_USERNAME }}
          password: ${{ secrets.REGISTRY_TOKEN }}

      - name: Build and push Docker image
        uses: docker/build-push-action@v6
        with:
          context: .
          file: ./Dockerfile
          push: true
          tags: ${{ env.DOCKER_REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.ref_name }}
          build-args: |
            HUGO_BASEURL=https://comprofix.com/

  deploy:
    runs-on: ubuntu-latest
    needs: build-and-push
    env:
      DEPLOY_USER: administrator
      DEPLOY_HOST: docker.comprofix.xyz
      DEPLOY_PATH: /opt/comprofix
    steps:
      - uses: actions/checkout@v4

      - name: Deploy to production server
        run: |
          mkdir -p ~/.ssh
          eval $(ssh-agent -s)
          ssh-add <(echo "${{ secrets.SSH_PRIVATE_KEY }}")

          echo "Uploading docker-compose.yml and .env.production..."
          scp docker-compose.yml $DEPLOY_USER@$DEPLOY_HOST:$DEPLOY_PATH
          scp .env.production $DEPLOY_USER@$DEPLOY_HOST:$DEPLOY_PATH/.env

          echo "Deploying production container..."
          ssh -o StrictHostKeyChecking=no $DEPLOY_USER@$DEPLOY_HOST "
            cd $DEPLOY_PATH
            docker compose --env-file .env up -d
          "
