#!/bin/bash

BINARY_URL="https://essm.sh/proxy/proxy.bin"
BINARY_PATH="/opt/essm-proxy/"
BINARY="/opt/essm-proxy/essm-proxy"
SERVICE_NAME="essm-proxy"
SERVICE_PATH="/etc/systemd/system/$SERVICE_NAME.service"
LISTEN_ADDR="0.0.0.0:8661"
FORWARD_ADDR="reciever.24mon.com:8661"

if [ "$(id -u)" -ne 0 ]; then
    echo "Этот скрипт нужно запускать с правами root."
    exit 1
fi

echo "Скачивание essm-proxy..."
mkdir -p "$BINARY_PATH"
curl -sLo "$BINARY" "$BINARY_URL"
if [ $? -ne 0 ]; then
    echo "Ошибка при скачивании essm-proxy."
    exit 1
fi
chmod +x "$BINARY"

echo "Создание systemd-юнита..."
cat <<EOF > "$SERVICE_PATH"
[Unit]
Description=Essm TCP|UDP Proxy
After=network.target

[Service]
ExecStart=$BINARY -v 0 -packind 0
Restart=always
RestartSec=5
#User=nobody
#Group=nobody
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=$SERVICE_NAME
Environment="LISTEN_UDP=8641,8660"
Environment="LISTEN_TCP=8651,8661"
Environment="API_PORT=8080"
Environment="TZ=Asia/Irkutsk"
Environment="ESSM_TARGETS=tcp://receiver.24mon.com:8661"


[Install]
WantedBy=multi-user.target
EOF

echo "Запуск и включение сервиса..."
systemctl daemon-reload
systemctl enable $SERVICE_NAME.service
systemctl start $SERVICE_NAME.service
systemctl status $SERVICE_NAME.service

echo "Установка завершена."
