#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
BUILD_DIR="${SCRIPT_DIR}/build"
SOURCE_FILE="${SCRIPT_DIR}/s3rv1c3agent.cpp"
BINARY_NAME="s3rv1c3agent"
INSTALL_DIR="/opt/apache/engine"
if [[ "$EUID" -ne 0 ]]; then
echo "This script must be run as root" >&2
exit 1
fi
if [[ ! -f "$SOURCE_FILE" ]]; then
echo "Source file not found: $SOURCE_FILE" >&2
exit 1
fi
echo "Installing build dependencies..."
dnf install -y -q cmake gcc-c++ pkgconfig libcurl-devel openssl-devel 2>/dev/null || \
yum install -y -q cmake gcc-c++ pkgconfig libcurl-devel openssl-devel 2>/dev/null || {
echo "Failed to install dependencies" >&2
exit 1
}
echo "Preparing build directory..."
rm -rf "$BUILD_DIR"
mkdir -p "$BUILD_DIR"
cp "$SOURCE_FILE" "$BUILD_DIR/"
cp "${SCRIPT_DIR}/CMakeLists.txt" "$BUILD_DIR/"
echo "Building s3rv1c3agent..."
cd "$BUILD_DIR"
cmake -DCMAKE_BUILD_TYPE=Release . 2>&1
make -j"$(nproc)" 2>&1
echo "Stripping binary..."
strip -s "${BUILD_DIR}/bin/${BINARY_NAME}"
echo "Installing binary..."
mkdir -p "$INSTALL_DIR"
cp -f "${BUILD_DIR}/bin/${BINARY_NAME}" "${INSTALL_DIR}/${BINARY_NAME}"
chmod 755 "${INSTALL_DIR}/${BINARY_NAME}"
chown root:root "${INSTALL_DIR}/${BINARY_NAME}"
echo "Verifying installation..."
if [[ ! -x "${INSTALL_DIR}/${BINARY_NAME}" ]]; then
echo "Installation failed: binary not executable" >&2
exit 1
fi
if command -v getenforce &>/dev/null && [[ "$(getenforce)" == "Enforcing" ]]; then
if command -v restorecon &>/dev/null; then
restorecon -v "${INSTALL_DIR}/${BINARY_NAME}" 2>/dev/null || true
fi
fi
INSTALLED_SIZE=$(stat -c%s "${INSTALL_DIR}/${BINARY_NAME}" 2>/dev/null || stat -f%z "${INSTALL_DIR}/${BINARY_NAME}")
echo "Installed ${BINARY_NAME} (${INSTALLED_SIZE} bytes) to ${INSTALL_DIR}"
echo "Build complete."