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

# Установка/обновление systemd unit для локального update-agent.
# Скрипт предназначен для окружений, где update-agent запускается из исходников.

SERVICE_NAME="${SERVICE_NAME:-cascad360-update-agent}"
INSTALL_DIR="${INSTALL_DIR:-/opt/cascad360}"
SERVICE_USER="${SERVICE_USER:-cascad360}"
SERVICE_GROUP="${SERVICE_GROUP:-$SERVICE_USER}"
SOCKET_PATH="${SOCKET_PATH:-/run/cascad360-update-agent.sock}"
STATE_DIR="${STATE_DIR:-/var/lib/cascad360/update-agent}"
LOG_LEVEL="${LOG_LEVEL:-INFO}"
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"

if [[ "${EUID}" -ne 0 ]]; then
  echo "Ошибка: скрипт должен выполняться с правами root" >&2
  exit 1
fi

if ! command -v systemctl >/dev/null 2>&1 || [[ ! -d /run/systemd/system ]]; then
  echo "Ошибка: systemd не обнаружен в текущем окружении" >&2
  exit 1
fi

if [[ -x "${INSTALL_DIR}/venv/bin/python" ]]; then
  PYTHON_BIN="${INSTALL_DIR}/venv/bin/python"
else
  PYTHON_BIN="$(command -v python3)"
fi

AGENT_SCRIPT_PYC="${INSTALL_DIR}/scripts/cascad360_update_agent.pyc"
AGENT_SCRIPT_PY="${INSTALL_DIR}/scripts/cascad360_update_agent.py"
if [[ -f "${AGENT_SCRIPT_PYC}" ]]; then
  AGENT_SCRIPT="${AGENT_SCRIPT_PYC}"
elif [[ -f "${AGENT_SCRIPT_PY}" ]]; then
  # Fallback для dev/source окружений.
  AGENT_SCRIPT="${AGENT_SCRIPT_PY}"
else
  echo "Ошибка: не найден скрипт агента: ${AGENT_SCRIPT_PYC}" >&2
  exit 1
fi

install -d -m 0750 -o "${SERVICE_USER}" -g "${SERVICE_GROUP}" "${STATE_DIR}"

cat > "${SERVICE_FILE}" <<EOF
[Unit]
Description=Cascad360 Local Update Agent
After=network.target

[Service]
Type=simple
User=${SERVICE_USER}
Group=${SERVICE_GROUP}
WorkingDirectory=${INSTALL_DIR}
ExecStart=${PYTHON_BIN} ${AGENT_SCRIPT} --socket-path ${SOCKET_PATH} --state-dir ${STATE_DIR} --log-level ${LOG_LEVEL}
Restart=always
RestartSec=3
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ReadWritePaths=${STATE_DIR} /tmp /var/tmp /run

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable "${SERVICE_NAME}"
systemctl restart "${SERVICE_NAME}"

echo "Готово: ${SERVICE_FILE}"
echo "Проверка: systemctl status ${SERVICE_NAME} --no-pager"
