name: Deploy

on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v3

      - name: Setup SSH
        run: |
          mkdir -p ~/.ssh
          echo "${{ secrets.DEPLOY_SSH_KEY }}" > ~/.ssh/id_ed25519
          chmod 600 ~/.ssh/id_ed25519
          ssh-keyscan -H "${{ secrets.DEPLOY_HOST }}" >> ~/.ssh/known_hosts

      - name: Deploy via Deployer
        env:
          DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }}
          GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
        run: |
          # Créer le container sans le démarrer (évite le problème DinD avec les volumes)
          CONTAINER=$(docker create \
            -e DEPLOY_HOST \
            -e GITEA_TOKEN \
            -w /app \
            deployphp/deployer:v7 \
            -f /app/deploy.php deploy production -vvv)

          # Copier les sources et les clés SSH dans le container
          docker cp "$PWD/." "$CONTAINER:/app/"
          docker cp "$HOME/.ssh/." "$CONTAINER:/root/.ssh/"

          # Démarrer et attendre la fin
          docker start -a "$CONTAINER"
          EXIT_CODE=$?
          docker rm "$CONTAINER" || true
          exit $EXIT_CODE
