#!/bin/sh
set -e

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

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

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

# Create config directory
mkdir -p /etc/xxxigcc

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

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

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

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

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

echo ""
echo "✅ XXXigCC installed successfully!"
echo ""
echo "📋 Configuration and startup:"
echo ""
echo "1. Review and configure settings (optional):"
echo "   For mining client:"
echo "     sudo nano /etc/xxxigcc/config.json"
echo "   For control server:"
echo "     sudo nano /etc/xxxigcc/config_cc.json"
echo ""
echo "   Adjust pool settings, wallet address, CC server, and other options as needed."
echo ""
echo "2. Start services:"
echo ""
echo "   For mining client (daemon):"
echo "     sudo systemctl enable xxxigcc-daemon.service"
echo "     sudo systemctl start xxxigcc-daemon.service"
echo ""
echo "   For control server (optional, Web UI on port 3344):"
echo "     sudo systemctl enable xxxigcc-server.service"
echo "     sudo systemctl start xxxigcc-server.service"
echo ""
echo "3. Check status:"
echo "   sudo systemctl status xxxigcc-daemon"
echo "   sudo journalctl -u xxxigcc-daemon -f"
echo ""
echo "📁 Important paths:"
echo "   Config files:   /etc/xxxigcc/config.json (daemon)"
echo "                   /etc/xxxigcc/config_cc.json (server)"
echo "   Log directory:  /var/log/xxxigcc"
echo "   Binaries:       /opt/xxxigcc/xxxigServer (control server)"
echo "                   /opt/xxxigcc/xxxigDaemon (mining daemon)"
echo "                   /opt/xxxigcc/xxxigMiner (miner executable)"
echo ""
echo "💡 Tip: Your config files will NOT be overwritten during package upgrades."
echo ""
echo "For help:"
echo "   /opt/xxxigcc/xxxigDaemon --help"
echo "   /opt/xxxigcc/xxxigServer --help"
echo ""

exit 0
