#!/usr/bin/env bash
# ==============================================================================
# SmartXChain Self-Configuring Node Installer for Linux (Debian / Ubuntu / RHEL)
# ==============================================================================
set -euo pipefail

NODE_USER="${SUDO_USER:-$USER}"
INSTALL_DIR="/opt/smartxchain"
SERVICE_NAME="smartxchain"
DEFAULT_NETWORK="${1:-mainnet}"

RED='\033[0;31m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
YELLOW='\033[1;33m'
NC='\033[0m'

log_info() { echo -e "${CYAN}[SmartXChain]${NC} $1"; }
log_success() { echo -e "${GREEN}[SmartXChain] ✓${NC} $1"; }
log_warn() { echo -e "${YELLOW}[SmartXChain] ⚠${NC} $1"; }
log_error() { echo -e "${RED}[SmartXChain] ✗${NC} $1"; }

if [ "$EUID" -ne 0 ]; then
  log_error "Please run installer with sudo or as root: sudo bash -c \"\$(curl -fsSL https://smartx.inetconnector.com/install.sh)\""
  exit 1
fi

echo -e "${CYAN}"
echo "  ███████╗███╗   ███╗ █████╗ ██████╗ ████████╗██╗  ██╗ ██████╗██╗  ██╗ █████╗ ██╗███╗   ██╗"
echo "  ██╔════╝████╗ ████║██╔══██╗██╔══██╗╚══██╔══╝╚██╗██╔╝██╔════╝██║  ██║██╔══██╗██║████╗  ██║"
echo "  ███████╗██╔████╔██║███████║██████╔╝   ██║    ╚███╔╝ ██║     ███████║███████║██║██╔██╗ ██║"
echo "  ╚════██║██║╚██╔╝██║██╔══██║██╔══██╗   ██║    ██╔██╗ ██║     ██╔══██║██╔══██║██║██║╚██╗██║"
echo "  ███████║██║ ╚═╝ ██║██║  ██║██║  ██║   ██║   ██╔╝ ██╗╚██████╗██║  ██║██║  ██║██║██║ ╚████║"
echo "  ╚══════╝╚═╝     ╚═╝╚═╝  ╚═╝╚═╝  ╚═╝   ╚═╝   ╚═╝  ╚═╝ ╚═════╝╚═╝  ╚═╝╚═╝  ╚═╝╚═╝╚═╝  ╚═══╝"
echo -e "${NC}"
log_info "Initializing SmartXChain Node automated setup for network: ${DEFAULT_NETWORK}..."

# 1. Package Dependencies
log_info "Updating system packages and installing prerequisites..."
if command -v apt-get >/dev/null 2>&1; then
    apt-get update -y -q
    apt-get install -y -q curl wget git jq ufw ca-certificates gnupg
elif command -v dnf >/dev/null 2>&1; then
    dnf install -y -q curl wget git jq ca-certificates
fi

# 2. .NET 9 Installation
if ! command -v dotnet >/dev/null 2>&1 || [ "$(dotnet --version | cut -d. -f1)" -lt 9 ]; then
    log_info "Installing Microsoft .NET 9 Runtime..."
    if command -v apt-get >/dev/null 2>&1; then
        wget -q https://packages.microsoft.com/config/debian/12/packages-microsoft-prod.deb -O /tmp/packages-microsoft-prod.deb || true
        dpkg -i /tmp/packages-microsoft-prod.deb || true
        apt-get update -y -q
        apt-get install -y -q dotnet-sdk-9.0 || apt-get install -y -q dotnet-runtime-9.0
    fi
fi

# 3. Node Directory & Repository
mkdir -p "$INSTALL_DIR"
if [ ! -d "$INSTALL_DIR/.git" ]; then
    log_info "Cloning SmartXChain repository into $INSTALL_DIR..."
    git clone https://github.com/SmartXChain/SmartXChain.git "$INSTALL_DIR" || {
        log_warn "Git clone skipped or failed, ensuring existing local install..."
    }
else
    log_info "Updating repository at $INSTALL_DIR..."
    git -C "$INSTALL_DIR" pull --rebase || true
fi

# 4. Build Node Daemon
log_info "Building SmartXChain headless Node daemon..."
cd "$INSTALL_DIR"
dotnet restore SmartXchain.sln
dotnet build SmartXChain.BlockExplorer.Web/SmartXChain.BlockExplorer.Web.csproj -c Release

# 5. Automated Firewall Configuration
log_info "Configuring network ports (5555 TCP/UDP for P2P, 5556 for Testnet, 8080 for API/Explorer)..."
if command -v ufw >/dev/null 2>&1 && ufw status | grep -q "Status: active"; then
    ufw allow 5555/tcp comment "SmartXChain P2P MainNet"
    ufw allow 5555/udp comment "SmartXChain P2P MainNet"
    ufw allow 5556/tcp comment "SmartXChain P2P TestNet"
    ufw allow 5556/udp comment "SmartXChain P2P TestNet"
    ufw allow 8080/tcp comment "SmartXChain Explorer API"
fi

# 6. Generate Systemd Services (Dual MainNet & TestNet Nodes)
log_info "Creating systemd daemon services for MainNet and TestNet..."

# MainNet Node & Explorer Service
cat <<EOF > /etc/systemd/system/${SERVICE_NAME}.service
[Unit]
Description=SmartXChain MainNet Node and Block Explorer Daemon
After=network.target network-online.target
Wants=network-online.target

[Service]
Type=simple
User=${NODE_USER}
WorkingDirectory=${INSTALL_DIR}/SmartXChain.BlockExplorer.Web
ExecStart=/usr/bin/dotnet run --project ${INSTALL_DIR}/SmartXChain.BlockExplorer.Web/SmartXChain.BlockExplorer.Web.csproj -c Release --no-build -- --Node:Network=mainnet
Restart=always
RestartSec=10
Environment=DOTNET_CLI_TELEMETRY_OPTOUT=1
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=ASPNETCORE_URLS=http://0.0.0.0:8080

[Install]
WantedBy=multi-user.target
EOF

# TestNet Node Service
cat <<EOF > /etc/systemd/system/${SERVICE_NAME}-testnet.service
[Unit]
Description=SmartXChain TestNet Reference Node and Consensus Daemon
After=network.target network-online.target
Wants=network-online.target

[Service]
Type=simple
User=${NODE_USER}
WorkingDirectory=${INSTALL_DIR}/SmartXChain.BlockExplorer.Web
ExecStart=/usr/bin/dotnet run --project ${INSTALL_DIR}/SmartXChain.BlockExplorer.Web/SmartXChain.BlockExplorer.Web.csproj -c Release --no-build -- --Node:Network=testnet
Restart=always
RestartSec=10
Environment=DOTNET_CLI_TELEMETRY_OPTOUT=1
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=ASPNETCORE_URLS=http://0.0.0.0:8081

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable ${SERVICE_NAME}
systemctl enable ${SERVICE_NAME}-testnet
systemctl restart ${SERVICE_NAME}
systemctl restart ${SERVICE_NAME}-testnet

log_success "SmartXChain Dual Node Services ('${SERVICE_NAME}' & '${SERVICE_NAME}-testnet') are active and running!"
log_info "MainNet Node Status: systemctl status ${SERVICE_NAME}"
log_info "TestNet Node Status: systemctl status ${SERVICE_NAME}-testnet"
log_info "View MainNet logs:   journalctl -u ${SERVICE_NAME} -f"
log_info "View TestNet logs:   journalctl -u ${SERVICE_NAME}-testnet -f"
echo "======================================================"
