name: GBCI

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

env:
  CARGO_BUILD_JOBS: 1
  CARGO_INCREMENTAL: 0
  CARGO_NET_RETRY: 10

jobs:
  build:
    runs-on: gbo

    steps:
      - name: Disable SSL verification
        run: git config --global http.sslVerify false

      - uses: actions/checkout@v4

      - name: Clone botlib dependency
        run: git clone --depth 1 https://github.com/GeneralBots/botlib.git ../botlib

      - name: Cache Cargo registry
        uses: actions/cache@v4
        with:
          path: |
            ~/.cargo/registry
            ~/.cargo/git
            target
          key: ${{ runner.os }}-cargo-debug-${{ hashFiles('**/Cargo.lock') }}
          restore-keys: |
            ${{ runner.os }}-cargo-debug-

      - name: Install system dependencies
        run: |
          sudo apt-get update
          sudo apt-get install -y libpq-dev libssl-dev liblzma-dev pkg-config

      - name: Install Rust
        run: |
          curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable --profile minimal
          echo "$HOME/.cargo/bin" >> $GITHUB_PATH

      - name: Setup environment
        run: sudo cp /opt/gbo/bin/system/.env . 2>/dev/null || true

      - name: Build debug
        run: |
          cargo build --locked -j 1 2>&1 | tee /tmp/build.log
          ls -lh target/debug/botserver

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

      - name: Deploy
        run: |
          sudo mkdir -p /opt/gbo/releases/botserver/linux
          sudo cp target/debug/botserver /opt/gbo/releases/botserver/linux/botserver-x86_64
          sudo chmod 755 /opt/gbo/releases/botserver/linux/botserver-x86_64

          lxc exec bot:pragmatismo-system -- systemctl stop system || true
          sudo cp target/debug/botserver /opt/gbo/bin/system/botserver
          sudo chmod +x /opt/gbo/bin/system/botserver
          lxc exec bot:pragmatismo-system -- systemctl start system || true
