name: Deploy to Server

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest # Ensure your Gitea runner is configured with this label
    container:
      image: alpine:latest # Using Alpine to save CPU/Memory
    steps:
      - name: Install SSH and Networking Tools
        # 'apk add' is the Alpine equivalent of 'apt-get install'
        run: apk add --no-cache openssh-client iproute2 git

      - name: Configure SSH Key
        run: |
          mkdir -p ~/.ssh
          # Gitea uses ${{ secrets.SECRET_NAME }} syntax
          echo "${{ secrets.DEPLOY_SSH_KEY }}" > ~/.ssh/id_rsa
          chmod 600 ~/.ssh/id_rsa
          echo "StrictHostKeyChecking no" > ~/.ssh/config

      - name: Execute Remote Deployment
        run: |
          # 1. Dynamically find the Host machine's IP (Docker bridge gateway)
          HOST_IP=$(ip route | awk '/default/ { print $3 }')
          echo "==> Detected Host IP: $HOST_IP"

          # 2. SSH into the host machine to execute the deployment safely
          ssh adipu@$HOST_IP << 'EOF'
            # Exit immediately if any command fails
            set -e
            
            echo "==> Navigating to project directory..."
            cd ~/LabWise

            echo "==> Pulling latest code..."
            # Note: Changed 'onedev' to 'origin'. Update if your Gitea remote is named differently.
            git pull origin main

            echo "==> Running Build..."
            # If this build fails, 'set -e' aborts the script instantly.
            # Your existing containers will NOT be touched, keeping the site up.
            docker compose build

            echo "==> Build successful! Deploying new containers..."
            # This only runs if the build was 100% successful.
            docker compose up -d
            
            echo "==> Cleaning up old images to save disk space..."
            # Crucial for resource-constrained servers to prevent disk exhaustion over time
            docker image prune -f

            echo "==> Deployment Complete!"
          EOF