#!/bin/sh
set -e

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

if ! getent passwd mond >/dev/null; then
    adduser --system --ingroup mond --no-create-home \
        --home /var/lib/mond --shell /usr/sbin/nologin \
        --gecos "Mond Cryptocurrency Daemon" mond
fi

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

# Create data directory
mkdir -p /var/lib/mond/data
chown -R mond:mond /var/lib/mond
chmod -R 750 /var/lib/mond

# Create configuration file if it doesn't exist
if [ ! -f /var/lib/mond/params.conf ]; then
    cat > /var/lib/mond/params.conf << 'CONF'
# Mond Configuration File
# This file is automatically created during installation
# Edit this file to customize your Mond daemon settings
# After modifying, restart the service: sudo systemctl restart mond.service

# DATA STORAGE
# ============================================================================
# data-dir: 区块链数据存储目录
data-dir=/var/lib/mond/data

# BLOCKCHAIN PRUNING
# ============================================================================
# prune-blockchain: 启用区块链修剪模式
prune-blockchain=1

# sync-pruned-blocks: 同步已修剪的区块（默认启用）
sync-pruned-blocks=1

# NETWORK PEER SETTINGS
# ============================================================================
# out-peers: 主动连接的对等节点数量（出站连接）
out-peers=32

# in-peers: 接受连接的对等节点数量（入站连接）
in-peers=64

# limit-rate-up: 上传速率限制（kB/s）
limit-rate-up=1048576

# limit-rate-down: 下载速率限制（kB/s）
limit-rate-down=1048576

# PRIORITY NODES
# ============================================================================
# add-priority-node: 优先连接的可信节点
add-priority-node=p2pmd.xmrvsbeast.com:18080
add-priority-node=nodes.hashvault.pro:18080

# SECURITY AND NETWORK INTEGRITY
# ============================================================================
# enforce-dns-checkpointing: 强制执行 DNS 检查点验证
enforce-dns-checkpointing=1

# enable-dns-blocklist: 启用 DNS 黑名单
enable-dns-blocklist=1

# ZMQ NOTIFICATION SYSTEM
# ============================================================================
# zmq-pub: ZeroMQ 发布接口，用于实时广播区块链事件
zmq-pub=tcp://127.0.0.1:18083

# P2P AND RPC NETWORK BINDING
# ============================================================================
# p2p-bind-ip: P2P 网络监听地址（默认启用，绑定所有网络接口）
p2p-bind-ip=0.0.0.0

# p2p-bind-port: P2P 网络监听端口
p2p-bind-port=18080

# rpc-bind-ip: RPC 接口监听地址
#rpc-bind-ip=0.0.0.0

# rpc-bind-port: RPC 接口监听端口
#rpc-bind-port=18081

# confirm-external-bind: 确认外部网络绑定
#confirm-external-bind=1

# RPC AUTHENTICATION
# ============================================================================
# rpc-login: RPC 访问认证凭据
#rpc-login=user:password

# RPC SSL/TLS ENCRYPTION
# ============================================================================
# rpc-ssl: 启用 RPC 连接的 SSL/TLS 加密（语义更清晰的启用方式）
#rpc-ssl=enabled

# rpc-ssl-certificate: SSL 证书文件路径
#rpc-ssl-certificate=/path/to/your/certificate.pem

# rpc-ssl-private-key: SSL 私钥文件路径
#rpc-ssl-private-key=/path/to/your/private_key.pem

# LOGGING SETTINGS
# ============================================================================
# log-level: 日志详细程度（调整为详细日志级别）
log-level=1

# log-file: 日志文件保存路径
log-file=/var/log/mond/mond.log
CONF
    chown mond:mond /var/lib/mond/params.conf
    chmod 640 /var/lib/mond/params.conf
fi

# Set permissions on binary
chown root:root /opt/mond/mond
chmod 755 /opt/mond/mond

# Reload systemd and handle service restart on upgrade
if [ -d /run/systemd/system ]; then
    systemctl daemon-reload

    # On upgrade: restart service if it was enabled
    if [ "$1" = "configure" ] && [ -n "$2" ]; then
        # $2 is the previously installed version (only set on upgrade)
        if systemctl is-enabled --quiet mond.service 2>/dev/null; then
            echo "Restarting mond service after upgrade..."
            systemctl start mond.service || true
        fi
    fi
    # Note: On fresh install, service is NOT auto-enabled or auto-started
    # Users should manually enable the service:
    #   systemctl enable mond.service
    #   systemctl start mond.service
fi

echo ""
echo "✅ Mond installed successfully!"
echo ""
echo "📋 Configuration and startup:"
echo ""
echo "1. Review and configure settings (optional):"
echo "   sudo nano /var/lib/mond/params.conf"
echo ""
echo "   Adjust network settings, peer connections, and other options as needed."
echo ""
echo "2. Start Mond:"
echo "   sudo systemctl enable mond.service"
echo "   sudo systemctl start mond.service"
echo ""
echo "3. Check status:"
echo "   sudo systemctl status mond.service"
echo "   sudo journalctl -u mond -f"
echo ""
echo "📁 Important paths:"
echo "   Config file:    /var/lib/mond/params.conf"
echo "   Data directory: /var/lib/mond/data"
echo "   Log directory:  /var/log/mond"
echo "   Binary:         /opt/mond/mond"
echo ""
echo "💡 Tip: Your params.conf will NOT be overwritten during package upgrades."
echo ""
echo "For help:"
echo "   /opt/mond/mond --help"
echo ""

exit 0
