on:
  push:
    branches:
      - master  # Trigger this action on pushes to the `master` branch.

jobs:
  deploy:
    runs-on: ubuntu-latest

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

    - name: Build Docker Image
      run: |
        docker build -t registry.cball5.club/blog:latest .

    - name: Push Docker Image
      run: |
        docker push registry.cball5.club/blog:latest


    - name: Set up SSH agent
      uses: webfactory/ssh-agent@v0.5.4
      with:
        ssh-private-key: ${{ secrets.SSH_PRIVATE_KEY }}
    
    # Step 2: Test SSH Connection (optional but good for debugging)
    - name: Test SSH Connection
      run: |
        ssh -o StrictHostKeyChecking=no cball5@10.100.0.233 "echo SSH connection established."

    # Step 3: Execute commands on the remote server
    - name: Deploy
      run: |
        ssh -o StrictHostKeyChecking=no cball5@10.100.0.233 bash -c "
          cd /home/cball5/blog && \
          docker compose down && \
          git fetch origin && \
          git reset --hard origin/master && \
          sed -i 's/{{SECRET_PLACEHOLDER}}/${{ secrets.DOCKER_SECRET }}/g' /home/cball5/blog/docker-compose.yml
          docker compose pull && \
          docker compose up -d --force-recreate
        "
      env:
        DOCKER_SECRET: ${{ secrets.DOCKER_SECRET }

