name: BotServer CI/CD

on:
  push:
    branches: ["main"]
  pull_request:
    branches: ["main"]

env:
  CARGO_BUILD_JOBS: 8
  CARGO_NET_RETRY: 10
  RUSTC_WRAPPER: sccache
  WORKSPACE: /opt/gbo/data/botserver
  CARGO_TARGET_DIR: /opt/gbo/data/botserver/target
  PATH: /home/gbuser/.cargo/bin:/home/gbuser/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

jobs:
  build:
    runs-on: gbo

    steps:
      - name: Setup Git
        run: |
          git config --global http.sslVerify false
          git config --global --add safe.directory "*"

      - name: Setup Workspace
        run: |
          mkdir -p $WORKSPACE
          cd $WORKSPACE
          # Update or clone botlib (preserve git history for sccache fingerprints)
          if [ -d botlib/.git ]; then
            git -C botlib pull origin main
          else
            git clone --branch main https://alm.pragmatismo.com.br/GeneralBots/botlib.git botlib
          fi
          # Update or clone botserver (preserve git history for sccache fingerprints)
          if [ -d botserver/.git ]; then
            git -C botserver pull origin main
          else
            git clone --branch main https://alm.pragmatismo.com.br/GeneralBots/BotServer.git botserver
          fi
          # Get workspace Cargo.toml from gb and strip unused members
          if [ -d /opt/gbo/data/gb-ws/.git ]; then
            git -C /opt/gbo/data/gb-ws pull origin main
          else
            git clone --branch main https://alm.pragmatismo.com.br/GeneralBots/gb.git /opt/gbo/data/gb-ws
          fi
          cp /opt/gbo/data/gb-ws/Cargo.toml Cargo.toml
          for m in botapp botdevice bottest botui botbook botmodels botplugin bottemplates; do
            grep -v "\"$m\"" Cargo.toml > /tmp/c.toml && mv /tmp/c.toml Cargo.toml
          done
          # Ensure target dir exists
          mkdir -p target

      - name: Install system dependencies
        run: |
          PKGS="libpq-dev libssl-dev liblzma-dev pkg-config"
          MISSING=""
          for pkg in $PKGS; do
            dpkg -s "$pkg" >/dev/null 2>&1 || MISSING="$MISSING $pkg"
          done
          if [ -n "$MISSING" ]; then
            sudo apt-get update -qq -o Acquire::Retries=3 -o Acquire::http::Timeout=30
            sudo apt-get install -y --no-install-recommends $MISSING
          else
            echo "All system dependencies already installed"
          fi

      - name: Build BotServer
        working-directory: /opt/gbo/data/botserver
        run: |
          export SCCACHE_IDLE_TIMEOUT=300
          export SCCACHE_CACHE_SIZE=10G
          sccache --stop-server 2>/dev/null || true
          sleep 1
          sccache --start-server
          cargo build -p botserver -j 8 2>&1 | tee /tmp/build.log
          echo "=== sccache stats ==="
          sccache --show-stats
          echo "=== Binary info ==="
          ls -lh target/debug/botserver
          stat -c '%y' target/debug/botserver

      - name: Save build log
        if: always()
        run: cp /tmp/build.log /tmp/botserver-$(date +%Y%m%d-%H%M%S).log || true

      - name: Deploy via ssh tar gzip
        run: |
          set -e
          SSH_ARGS="-i /home/gbuser/.ssh/id_ed25519 -o StrictHostKeyChecking=no -o ConnectTimeout=5 -o ServerAliveInterval=5 -o ServerAliveCountMax=2 -o BatchMode=yes"
          echo "=== Deploy started ==="
          echo "Step 1: Checking binary..."
          ls -lh /opt/gbo/data/botserver/target/debug/botserver
          echo "Step 2: Backing up old binary..."
          ssh $SSH_ARGS system "cp /opt/gbo/bin/botserver /tmp/botserver.bak"
          echo "Step 3: Stopping botserver service..."
          ssh $SSH_ARGS system "sudo systemctl stop botserver || true"
          echo "Step 4: Transferring new binary..."
          tar cf - -C /opt/gbo/data/botserver/target/debug botserver | gzip -1 | ssh $SSH_ARGS system "gzip -d | tar xf - -C /opt/gbo/bin && chmod +x /opt/gbo/bin/botserver && chown gbuser:gbuser /opt/gbo/bin/botserver && echo 'Transfer complete'"
          echo "Step 5: Starting botserver service..."
          ssh $SSH_ARGS system "sudo systemctl start botserver && echo 'Botserver started'"
          echo "=== Deploy completed ==="

      - name: Verify botserver started
        run: |
          sleep 30
          SSH_ARGS="-i /home/gbuser/.ssh/id_ed25519 -o StrictHostKeyChecking=no -o ConnectTimeout=5 -o ServerAliveInterval=5 -o ServerAliveCountMax=2 -o BatchMode=yes"
          ssh $SSH_ARGS system "pgrep -f botserver >/dev/null && echo 'OK: botserver is running' || echo 'WARNING: botserver may still be starting'"

      - name: Save deploy log
        if: always()
        run: cp /tmp/deploy.log /tmp/deploy-$(date +%Y%m%d-%H%M%S).log || true
