#!/bin/sh
set -e

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

if ! getent passwd p2pool >/dev/null; then
    adduser --system --ingroup p2pool --no-create-home \
        --home /var/lib/p2pool --shell /usr/sbin/nologin \
        --gecos "P2Pool Service" p2pool
fi

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

# Create data directory（非递归设权限，避免升级时遍历庞大数据目录）
mkdir -p /var/lib/p2pool/data-api
chown p2pool:p2pool /var/lib/p2pool /var/lib/p2pool/data-api
chmod 750 /var/lib/p2pool /var/lib/p2pool/data-api

# Create config directory
mkdir -p /etc/p2pool

# 兼容旧版本：配置文件曾位于 /var/lib/p2pool/params.conf，迁移到 /etc/p2pool/params.conf
if [ ! -f /etc/p2pool/params.conf ] && [ -f /var/lib/p2pool/params.conf ]; then
    echo "Migrating existing config from /var/lib/p2pool to /etc/p2pool..."
    cp /var/lib/p2pool/params.conf /etc/p2pool/params.conf
fi

# 首次安装：从包内默认配置生成（源：conf/params.conf.example）。升级不覆盖已有配置
if [ ! -f /etc/p2pool/params.conf ]; then
    cp /opt/p2pool/params.conf /etc/p2pool/params.conf
fi

chown p2pool:p2pool /etc/p2pool/params.conf
chmod 640 /etc/p2pool/params.conf

# Set permissions：/opt 目录与二进制 755，数据文件 644（对齐 xxxig / xxxig-proxy / mond）
chown -R root:root /opt/p2pool
find /opt/p2pool -type d -exec chmod 755 {} +
find /opt/p2pool -type f -exec chmod 644 {} +
chmod 755 /opt/p2pool/p2pool

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

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

    # Note: On fresh install, service is NOT auto-enabled or auto-started
    #   systemctl enable p2pool.service
    #   systemctl start p2pool.service
fi

echo ""
echo "✅ P2Pool installed successfully!"
echo ""
echo "📁 Important paths:"
echo "   Config file:      /etc/p2pool/params.conf"
echo "   Data directory:   /var/lib/p2pool/data-api"
echo "   Log directory:    /var/log/p2pool"
echo "   Binaries:         /opt/p2pool/p2pool"
echo "   Systemd services: p2pool.service"
echo ""
echo "💡 Tip: Your config files will NOT be overwritten during package upgrades."
echo "   Before starting, set your Monero wallet in /etc/p2pool/params.conf, then:"
echo "   sudo systemctl enable --now p2pool.service"
echo ""

exit 0
