#!/bin/bash
# NEMO 2026 - Prerequisites Installation Script
# DEDA Connect S.r.l. - https://repo.connectlabs.it
# Uso: curl -sk https://repo.connectlabs.it/nemo-prereq.sh | sudo bash

# CHECK ROOT - prima di tutto
if [ "$EUID" -ne 0 ]; then
    echo ""
    echo "  NEMO 2026 - Prerequisites Setup"
    echo "  Errore: questo script richiede i privilegi di root."
    echo ""
    echo "  Rieseguire con:"
    echo "    curl -sk https://repo.connectlabs.it/nemo-prereq.sh | sudo bash"
    echo ""
    exit 1
fi

REPO_BASE="https://repo.connectlabs.it"
GPG_KEY="$REPO_BASE/RPM-GPG-KEY-ConnectLabs-NEMO"
NEMO_REPO="$REPO_BASE/nemo/el9/x86_64"
LOG="/var/log/nemo-prereq.log"
touch $LOG 2>/dev/null || LOG="/tmp/nemo-prereq.log"

RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m'
info()  { echo -e "${GREEN}[INFO]${NC}  $1" | tee -a $LOG; }
warn()  { echo -e "${YELLOW}[WARN]${NC}  $1" | tee -a $LOG; }
error() { echo -e "${RED}[ERROR]${NC} $1" | tee -a $LOG; exit 1; }

echo "================================================" | tee -a $LOG
echo " NEMO 2026 - Prerequisites Setup" | tee -a $LOG
echo " $(date)" | tee -a $LOG
echo "================================================" | tee -a $LOG

[ ! -f /etc/redhat-release ] && error "Sistema non supportato. Richiesto RHEL/Rocky Linux 9."
OS_VER=$(rpm -E %{rhel})
[ "$OS_VER" != "9" ] && error "Richiesto RHEL/Rocky Linux 9 (rilevato: RHEL $OS_VER)"
info "Sistema: $(cat /etc/redhat-release)"

info "Verifica connettivita' repo.connectlabs.it..."
curl -sf "$REPO_BASE/README.txt" > /dev/null || error "Impossibile raggiungere $REPO_BASE"

info "Aggiornamento sistema..."
dnf update -y -q 2>&1 | tail -2 | tee -a $LOG

info "Installazione dipendenze base..."
dnf install -y -q epel-release curl wget git tar unzip \
    net-tools bind-utils net-snmp net-snmp-utils 2>&1 | tail -2 | tee -a $LOG

# PHP 8.2 via Remi
info "Configurazione PHP 8.2 via Remi..."
dnf install -y -q https://rpms.remirepo.net/enterprise/remi-release-9.rpm 2>&1 | tail -1 | tee -a $LOG
dnf module reset php -y -q 2>/dev/null
dnf module enable php:remi-8.2 -y -q 2>/dev/null
info "Installazione PHP 8.2 e moduli..."
dnf install -y -q php php-fpm php-cli php-common php-mysqlnd php-pdo \
    php-mbstring php-xml php-json php-curl php-gd php-zip \
    php-snmp php-bcmath php-intl php-ldap php-soap php-opcache php-process \
    2>&1 | tail -2 | tee -a $LOG

# MariaDB 10.11 LTS
info "Configurazione MariaDB 10.11 LTS..."
cat > /etc/yum.repos.d/mariadb.repo << 'MDBEOF'
[mariadb]
name = MariaDB 10.11 LTS Repository
baseurl = https://rpm.mariadb.org/10.11/rhel/$releasever/$basearch
gpgkey = https://rpm.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck = 1
enabled = 0
MDBEOF
dnf install -y -q MariaDB-server MariaDB-client 2>&1 | tail -2 | tee -a $LOG

# ClickHouse
info "Installazione ClickHouse..."
curl -sf https://packages.clickhouse.com/rpm/clickhouse.repo \
    -o /etc/yum.repos.d/clickhouse.repo
dnf install -y -q clickhouse-server clickhouse-client 2>&1 | tail -2 | tee -a $LOG

# RabbitMQ via repo ufficiale cloudsmith
info "Configurazione repo RabbitMQ..."
curl -sf https://packagecloud.io/rabbitmq/rabbitmq-server/gpgkey | \
    gpg --dearmor > /usr/share/keyrings/rabbitmq.gpg 2>/dev/null

cat > /etc/yum.repos.d/rabbitmq.repo << 'EOF'
[rabbitmq-erlang]
name=rabbitmq-erlang
baseurl=https://packagecloud.io/rabbitmq/erlang/el/8/$basearch
gpgcheck=0
enabled=1

[rabbitmq-server]
name=rabbitmq-server
baseurl=https://packagecloud.io/rabbitmq/rabbitmq-server/el/8/$basearch
gpgcheck=0
enabled=1
EOF

info "Installazione Erlang + RabbitMQ..."
dnf install -y -q erlang rabbitmq-server 2>&1 | tail -2 | tee -a $LOG || \
    warn "RabbitMQ: installazione da repo alternativo fallita, riprova manualmente"

# nginx + httpd su porta 8080 (nginx fa da reverse proxy)
info "Installazione nginx e httpd..."
dnf install -y -q nginx httpd mod_ssl 2>&1 | tail -2 | tee -a $LOG

# Configura httpd su porta 8080 per evitare conflitto con nginx
sed -i 's/^Listen 80$/Listen 127.0.0.1:8080/' /etc/httpd/conf/httpd.conf 2>/dev/null
sed -i 's/^Listen 443/#Listen 443/' /etc/httpd/conf.d/ssl.conf 2>/dev/null

# fail2ban
info "Installazione fail2ban..."
dnf install -y -q fail2ban fail2ban-firewalld 2>&1 | tail -2 | tee -a $LOG

# Composer
info "Installazione Composer..."
command -v composer &>/dev/null || \
    curl -sf https://getcomposer.org/installer | \
    php -- --install-dir=/usr/local/bin --filename=composer 2>&1 | tail -1 | tee -a $LOG

# GPG key e repo NEMO
info "Importazione chiave GPG ConnectLabs..."
rpm --import "$GPG_KEY" 2>/dev/null || warn "GPG key non importata"

info "Configurazione repository NEMO..."
cat > /etc/yum.repos.d/nemo.repo << EOF
[nemo]
name = NEMO Network Monitoring - DEDA Connect
baseurl = $NEMO_REPO
enabled = 0
gpgcheck = 1
gpgkey = $GPG_KEY
EOF

# PHP capabilities per ICMP
info "Configurazione capabilities PHP per ICMP..."
setcap cap_net_bind_service,cap_net_raw=ep $(which php)
info "Capabilities: $(getcap $(which php))"

# Utente nemo
info "Creazione utente nemo..."
id nemo &>/dev/null || useradd -r -s /sbin/nologin -d /var/nemo -m nemo
mkdir -p /var/log/nemo /etc/nemo
chown nemo:nemo /var/log/nemo

# Avvio servizi
info "Avvio servizi..."
for svc in mariadb clickhouse-server rabbitmq-server php-fpm nginx httpd fail2ban; do
    systemctl enable --now $svc 2>/dev/null && \
        info "  $svc: OK" || warn "  $svc: non avviato"
done

# Firewall
info "Configurazione firewall..."
firewall-cmd --permanent --add-service=http  &>/dev/null
firewall-cmd --permanent --add-service=https &>/dev/null
firewall-cmd --permanent --add-rich-rule='rule service name="ssh" limit value="3/m" accept' &>/dev/null
firewall-cmd --reload &>/dev/null

# SELinux
info "SELinux enforcing..."
setenforce 1 2>/dev/null || warn "SELinux non disponibile"
sed -i 's/^SELINUX=.*/SELINUX=enforcing/' /etc/selinux/config 2>/dev/null

echo "" | tee -a $LOG
echo "================================================" | tee -a $LOG
info "Prerequisites completati! Log: $LOG"
info ""
info "Prossimo passo - installare NEMO:"
info "  dnf install -y nemo-setup nemo-www nemo-daemon"
info "  /usr/share/nemo/setup/nemo-setup.sh"
echo "================================================" | tee -a $LOG
