# Gitea Actions CI/CD — Static Site (no tests, build + deploy only)
# Copy to: <repo>/.gitea/workflows/ci.yml
# Replace: nusqool-replica, /opt/websites/nusqool-replica, https://nusqool-staging.nusqool.com/

name: CI/CD

on:
  push:
    branches: [main]

env:
  REGISTRY: localhost:3000
  IMAGE: localhost:3000/jeffemmett/nusqool-replica

jobs:
  deploy:
    runs-on: ubuntu-latest
    container:
      image: docker:cli
    steps:
      - name: Setup tools
        run: apk add --no-cache git openssh-client curl

      - name: Checkout
        run: git clone --depth 1 --branch ${{ github.ref_name }} http://token:${{ github.token }}@server:3000/${{ github.repository }}.git .

      - name: Set image tag
        run: |
          SHORT_SHA=$(echo "${{ github.sha }}" | cut -c1-8)
          echo "IMAGE_TAG=${SHORT_SHA}" >> $GITHUB_ENV

      - name: Build and push image
        run: |
          docker build -t ${{ env.IMAGE }}:${{ env.IMAGE_TAG }} -t ${{ env.IMAGE }}:latest .
          echo "${{ secrets.REGISTRY_TOKEN }}" | docker login ${{ env.REGISTRY }} -u ${{ secrets.REGISTRY_USER }} --password-stdin
          docker push ${{ env.IMAGE }}:${{ env.IMAGE_TAG }}
          docker push ${{ env.IMAGE }}:latest

      - name: Deploy
        run: |
          mkdir -p ~/.ssh
          echo "${{ secrets.DEPLOY_SSH_KEY }}" | base64 -d > ~/.ssh/deploy_key
          chmod 600 ~/.ssh/deploy_key
          ssh -o StrictHostKeyChecking=no -i ~/.ssh/deploy_key root@${{ secrets.DEPLOY_HOST }} "
            cd /opt/websites/nusqool-replica
            cat .last-deployed-tag 2>/dev/null > .rollback-tag || true
            echo '${{ env.IMAGE_TAG }}' > .last-deployed-tag
            docker pull ${{ env.IMAGE }}:${{ env.IMAGE_TAG }}
            IMAGE_TAG=${{ env.IMAGE_TAG }} docker compose up -d --no-build
          "

      - name: Smoke test
        run: |
          sleep 15
          STATUS=$(ssh -o StrictHostKeyChecking=no -i ~/.ssh/deploy_key root@${{ secrets.DEPLOY_HOST }} \
            "cd /opt/websites/nusqool-replica && docker compose ps --format '{{{{.Status}}}}' 2>/dev/null | head -1 || echo 'unknown'")
          if echo "$STATUS" | grep -qi "up"; then
            echo "Smoke test passed (container status: $STATUS)"
          else
            echo "Smoke test failed (container status: $STATUS) — rolling back"
            ROLLBACK_TAG=$(ssh -o StrictHostKeyChecking=no -i ~/.ssh/deploy_key root@${{ secrets.DEPLOY_HOST }} "cat /opt/websites/nusqool-replica/.rollback-tag 2>/dev/null")
            if [ -n "$ROLLBACK_TAG" ]; then
              ssh -o StrictHostKeyChecking=no -i ~/.ssh/deploy_key root@${{ secrets.DEPLOY_HOST }} \
                "cd /opt/websites/nusqool-replica && IMAGE_TAG=$ROLLBACK_TAG docker compose up -d --no-build"
              echo "Rolled back to $ROLLBACK_TAG"
            fi
            exit 1
          fi
