#!/bin/sh
set -e

# Create user and group if they don't exist
if ! getent group xxxig >/dev/null; then
    addgroup --system xxxig
fi

if ! getent passwd xxxig >/dev/null; then
    adduser --system --ingroup xxxig --no-create-home \
        --home /opt/xxxig --shell /usr/sbin/nologin \
        --gecos "XXXig Service" xxxig
fi

# Create log directory
mkdir -p /var/log/xxxig
chown xxxig:xxxig /var/log/xxxig
chmod 750 /var/log/xxxig

# Create config directory
mkdir -p /etc/xxxig

# Copy default configs if they don't exist
if [ ! -f /etc/xxxig/config.json ]; then
    cp /opt/xxxig/config.json /etc/xxxig/config.json
    chown xxxig:xxxig /etc/xxxig/config.json
    chmod 640 /etc/xxxig/config.json
fi

if [ ! -f /etc/xxxig/config_cc.json ]; then
    cp /opt/xxxig/config_cc.json /etc/xxxig/config_cc.json
    chown xxxig:xxxig /etc/xxxig/config_cc.json
    chmod 640 /etc/xxxig/config_cc.json
fi

# Set permissions
chown -R root:root /opt/xxxig
chmod -R 755 /opt/xxxig

# Reload systemd
if [ -d /run/systemd/system ]; then
    systemctl daemon-reload

    # 升级时重启正在运行的服务以加载新二进制；try-restart 不会启动未运行的服务，
    # 故首次安装仍保持"不自动启动"语义
    systemctl try-restart xxxig-daemon.service xxxig-server.service 2>/dev/null || true

    # Note: Services are NOT auto-enabled or auto-started
    # Users should manually enable the services they need:
    #   systemctl enable xxxig-server.service
    #   systemctl start xxxig-server.service
    # or
    #   systemctl enable xxxig-daemon.service
    #   systemctl start xxxig-daemon.service
fi

echo ""
echo "✅ XXXig installed successfully!"
echo ""
echo "📁 Important paths:"
echo "   Config files:   /etc/xxxig/config.json (daemon)"
echo "                   /etc/xxxig/config_cc.json (server)"
echo "   Log directory:  /var/log/xxxig"
echo "   Binaries:       /opt/xxxig/xxxigServer (control server)"
echo "                   /opt/xxxig/xxxigDaemon (mining daemon)"
echo "                   /opt/xxxig/xxxig (miner executable)"
echo "   Systemd services: xxxig-server.service (control server)"
echo "                     xxxig-daemon.service (mining daemon)"
echo ""
echo "💡 Tip: Your config files will NOT be overwritten during package upgrades."
echo ""

exit 0
