name: OpenBSD Build
permissions:
  contents: read

on:
  workflow_dispatch:
    inputs:
      openbsd_version:
        description: 'OpenBSD version to use'
        required: false
        default: '7.8'
        type: choice
        options:
          - '7.8'
          - '7.7'
          - '7.6'
      lua_version:
        description: 'Lua version to use'
        required: false
        default: 'luajit'
        type: choice
        options:
          - 'luajit'
          - 'lua51'
          - 'lua53'

jobs:
  openbsd-build:
    runs-on: ubuntu-latest
    name: Build on OpenBSD ${{ inputs.openbsd_version }} with ${{ inputs.lua_version }}

    steps:
      - name: Check out source code
        uses: actions/checkout@v4

      - name: Build on OpenBSD
        uses: vmactions/openbsd-vm@v1
        with:
          release: ${{ inputs.openbsd_version }}
          usesh: true
          prepare: |
            # Set package repository path
            export PKG_PATH=https://cdn.openbsd.org/pub/OpenBSD/$(uname -r)/packages/$(uname -m)/

            # Install base build dependencies
            pkg_add cmake ninja pkgconf \
              pcre2 sqlite3 openssl ragel icu4c \
              libsodium glib2 libunwind \
              perl libarchive zstd xxhash \
              file gettext-tools

            # Install Lua version based on user selection
            case "${{ inputs.lua_version }}" in
              luajit)
                pkg_add luajit
                ;;
              lua51)
                pkg_add lua%5.1
                ;;
              lua53)
                pkg_add lua%5.3
                ;;
            esac

          run: |
            set -e

            echo "==> Building Rspamd on OpenBSD $(uname -r) with ${{ inputs.lua_version }}"

            # Determine Lua CMake flags
            case "${{ inputs.lua_version }}" in
              luajit)
                LUA_FLAGS="-DENABLE_LUAJIT=ON"
                ;;
              *)
                LUA_FLAGS="-DENABLE_LUAJIT=OFF"
                ;;
            esac

            # Create build directory
            mkdir -p build
            cd build

            # Run CMake
            echo "==> Running CMake configuration"
            cmake -G Ninja \
              -DCMAKE_BUILD_TYPE=Release \
              -DCMAKE_INSTALL_PREFIX=/usr/local \
              -DENABLE_HYPERSCAN=OFF \
              $LUA_FLAGS \
              -DSYSTEM_ZSTD=ON \
              -DSYSTEM_XXHASH=ON \
              -DENABLE_JEMALLOC=OFF \
              ..

            # Build
            echo "==> Building Rspamd"
            ninja

            # Run tests
            echo "==> Running C++ unit tests"
            ./test/rspamd-test-cxx || echo "C++ tests failed"

            echo "==> Running Lua unit tests"
            ./test/rspamd-test -p /rspamd/lua || echo "Lua tests failed"

            echo "==> Build completed successfully!"
