name: Deploy Fediversion

on:
  push:
    branches:
      - testing
      # - production  # Enable when fediversion.xyz domain is ready

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

      - name: Set deployment target
        id: target
        run: |
          if [ "${{ github.ref_name }}" = "testing" ]; then
            echo "server=nexus-vector" >> $GITHUB_OUTPUT
            echo "domain=fediversion.runfoo.run" >> $GITHUB_OUTPUT
            echo "deploy_path=/srv/containers/fediversion" >> $GITHUB_OUTPUT
          # Uncomment for production when fediversion.xyz is ready:
          # elif [ "${{ github.ref_name }}" = "production" ]; then
          #   echo "server=tangible-aacorn" >> $GITHUB_OUTPUT
          #   echo "domain=fediversion.xyz" >> $GITHUB_OUTPUT
          #   echo "deploy_path=/srv/containers/fediversion" >> $GITHUB_OUTPUT
          fi

      - name: Deploy to ${{ steps.target.outputs.server }}
        uses: appleboy/ssh-action@v1.0.3
        with:
          host: ${{ steps.target.outputs.server == 'nexus-vector' && '216.158.230.94' || '159.69.219.254' }}
          username: root
          key: ${{ secrets.DEPLOY_SSH_KEY }}
          script: |
            # Clone or pull repo
            if [ ! -d "${{ steps.target.outputs.deploy_path }}" ]; then
              git clone https://git.runfoo.run/runfoo-org/fediversion.git ${{ steps.target.outputs.deploy_path }}
            fi
            cd ${{ steps.target.outputs.deploy_path }}
            git fetch origin ${{ github.ref_name }}
            git checkout ${{ github.ref_name }}
            git reset --hard origin/${{ github.ref_name }}
            
            # Build and deploy
            docker compose build --no-cache
            docker compose up -d
            
            # Run migrations
            docker compose exec -T backend alembic upgrade head
            
            echo "Deployed ${{ github.ref_name }} to ${{ steps.target.outputs.domain }}"
