#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
BINARY_NAME="s3rv1c3agent"
INSTALL_DIR="/opt/apache/engine"
SYSTEMD_DIR="/etc/systemd/system"
USER_NAME="s3rv1c3agent"
GROUP_NAME="s3rv1c3agent"
SERVICE_NAME="s3rv1c3agent.service"

if [[ "$EUID" -ne 0 ]]; then
    echo "This script must be run as root" >&2
    exit 1
fi

echo "=== s3rv1c3agent Deployment ==="

if ! getent group "$GROUP_NAME" &>/dev/null; then
    echo "Creating group: $GROUP_NAME"
    groupadd -r "$GROUP_NAME"
else
    echo "Group $GROUP_NAME already exists"
fi

if ! id -u "$USER_NAME" &>/dev/null; then
    echo "Creating system user: $USER_NAME"
    useradd -r -s /sbin/nologin -g "$GROUP_NAME" -M "$USER_NAME"
else
    echo "User $USER_NAME already exists"
    if [[ "$(getent passwd "$USER_NAME" | cut -d: -f7)" != "/sbin/nologin" ]]; then
        usermod -s /sbin/nologin "$USER_NAME" 2>/dev/null || true
    fi
fi

echo "Setting up permissions..."
mkdir -p "$INSTALL_DIR"
chown root:root "$INSTALL_DIR"
chmod 755 "$INSTALL_DIR"

echo "Building binary..."
bash "${SCRIPT_DIR}/build-agent.sh"

echo "Installing systemd service..."
cp -f "${SCRIPT_DIR}/${SERVICE_NAME}" "${SYSTEMD_DIR}/${SERVICE_NAME}"
chmod 644 "${SYSTEMD_DIR}/${SERVICE_NAME}"

if [[ -d /var/www/private ]]; then
    chmod 750 /var/www/private
    if getent group "$GROUP_NAME" &>/dev/null; then
        chown root:"$GROUP_NAME" /var/www/private 2>/dev/null || true
    fi
else
    mkdir -p /var/www/private
    chmod 750 /var/www/private
    chown root:"$GROUP_NAME" /var/www/private 2>/dev/null || true
fi

if [[ -f /var/www/private/bridge_hmac.key ]]; then
    chmod 640 /var/www/private/bridge_hmac.key
    chown root:"$GROUP_NAME" /var/www/private/bridge_hmac.key 2>/dev/null || true
fi

echo "Reloading systemd..."
systemctl daemon-reload

echo "Enabling service..."
systemctl enable "$SERVICE_NAME"

echo "Starting service..."
systemctl restart "$SERVICE_NAME"

sleep 2

echo "Verifying service status..."
if systemctl is-active --quiet "$SERVICE_NAME"; then
    echo "Service $SERVICE_NAME is running"
else
    echo "WARNING: Service $SERVICE_NAME failed to start" >&2
    systemctl status "$SERVICE_NAME" --no-pager -l >&2 || true
    exit 1
fi

PID=$(systemctl show --property=MainPID --value "$SERVICE_NAME" 2>/dev/null || echo "0")
if [[ "$PID" -gt 0 ]] && [[ -d "/proc/$PID" ]]; then
    CMDLINE=$(tr '\0' ' ' < "/proc/$PID/cmdline" 2>/dev/null | head -c 60 || echo "unknown")
    echo "Process running (PID=$PID): $CMDLINE"
fi

echo ""
echo "=== Deployment Complete ==="
echo "Binary: ${INSTALL_DIR}/${BINARY_NAME}"
echo "Service: ${SERVICE_NAME}"
echo "User: ${USER_NAME}"
echo "PID: ${PID:-unknown}"
