#!/usr/bin/env bash

set -euo pipefail

if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
    echo "❌ Ошибка: скрипт должен быть запущен с правами root."
    echo "👉 Используй: sudo $0"
    exit 1
fi

source ./_config

#USER="${SUDO_USER}"
USER="root"

SOURCE_DIR="$(pwd)"
cd ..
WORKDIR="$(pwd)"
cd $SOURCE_DIR

source_file="$SOURCE_DIR/jrobo.service"
service_name="$SERVICE_NAME.service"
target_file="/etc/systemd/system/$service_name"

sed \
  -e "s|__WORKDIR__|$WORKDIR|" \
  -e "s|__CUR_USER__|$USER|" \
  -e "s|__DESCR__|$SERVICE_DESCR|" \
  -e "s|__JAVA_PATH__|$JAVA_PATH|" \
  -e "s|__CFG__|$CFG|" \
  -e "s|__XMS__|$XMS|" \
  -e "s|__XMX__|$XMX|" \
  "$source_file" > "$target_file"

chmod 644 "$target_file"

systemctl daemon-reexec
systemctl daemon-reload
systemctl enable $service_name

usermod -aG dialout ${USER}

echo Successfully installed $service_name!

