#!/bin/bash
# Setup automatico server AlmaLinux 9 per VigilanzaTurni
# Esegui: sudo bash deploy/setup-server.sh

set -e

# Colori output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

log_info() { echo -e "${GREEN}[INFO]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# Verifica root
if [ "$EUID" -ne 0 ]; then 
    log_error "Esegui come root: sudo bash $0"
    exit 1
fi

log_info "🚀 Setup server AlmaLinux 9 per VigilanzaTurni"
log_info "Dominio: vt.alfacom.it"

# =================== SYSTEM UPDATE ===================
log_info "Aggiornamento sistema..."
dnf update -y

# =================== NODE.JS ===================
log_info "Installazione Node.js 20..."
dnf module reset nodejs -y
dnf module enable nodejs:20 -y
dnf install nodejs -y
node --version
npm --version

# =================== PM2 ===================
log_info "Installazione PM2..."
npm install -g pm2
pm2 startup systemd -u root --hp /root
systemctl enable pm2-root

# =================== POSTGRESQL ===================
log_info "Installazione PostgreSQL 15..."
<<<<<<< HEAD
dnf install -y postgresql15-server postgresql15

# Inizializza database
postgresql-setup --initdb
systemctl enable postgresql
systemctl start postgresql
=======
dnf install -y postgresql15-server postgresql15-contrib
postgresql-15-setup --initdb
systemctl enable postgresql-15
systemctl start postgresql-15
>>>>>>> 94bec4cfd683fe846be466cbfba0a57786d95c2a

# Genera password sicura PostgreSQL (o usa variabile ambiente)
if [ -z "$DB_PASSWORD" ]; then
    DB_PASSWORD=$(openssl rand -base64 32 | tr -d "=+/" | cut -c1-25)
    log_warn "Password PostgreSQL generata automaticamente"
else
    log_info "Uso password PostgreSQL da variabile DB_PASSWORD"
fi

# Creazione database e utente
log_info "Configurazione database..."
sudo -u postgres psql << EOF
CREATE DATABASE vigilanza_turni;
CREATE USER vigilanza_user WITH ENCRYPTED PASSWORD '${DB_PASSWORD}';
GRANT ALL PRIVILEGES ON DATABASE vigilanza_turni TO vigilanza_user;
\c vigilanza_turni
GRANT ALL ON SCHEMA public TO vigilanza_user;
EOF

# Salva password in file sicuro
echo "PGPASSWORD=${DB_PASSWORD}" > /root/.vigilanza_db_password
chmod 600 /root/.vigilanza_db_password
log_info "✅ Database configurato - Password salvata in /root/.vigilanza_db_password"

# Configurazione PostgreSQL per connessioni locali
log_info "Configurazione autenticazione PostgreSQL..."
PG_HBA="/var/lib/pgsql/data/pg_hba.conf"
if ! grep -q "vigilanza_user" $PG_HBA; then
    echo "local   vigilanza_turni    vigilanza_user                    md5" >> $PG_HBA
    echo "host    vigilanza_turni    vigilanza_user    127.0.0.1/32    md5" >> $PG_HBA
    systemctl restart postgresql
fi

# =================== NGINX ===================
log_info "Installazione Nginx..."
dnf install -y nginx
systemctl enable nginx
systemctl start nginx

# =================== GIT ===================
log_info "Installazione Git..."
dnf install -y git

# =================== DIRECTORY APPLICAZIONE ===================
log_info "Creazione directory applicazione..."
mkdir -p /var/www/vigilanza-turni
mkdir -p /var/backups/vigilanza-turni
chmod 755 /var/www/vigilanza-turni
chmod 700 /var/backups/vigilanza-turni

# =================== FIREWALL ===================
log_info "Configurazione firewall..."
systemctl enable firewalld
systemctl start firewalld
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload

# =================== SSL CERTIFICATE (Let's Encrypt) ===================
log_info "Installazione Certbot per SSL..."
dnf install -y certbot python3-certbot-nginx

log_info ""
log_info "================================================"
log_info "Setup completato con successo!"
log_info "================================================"
log_info ""
log_warn "PROSSIMI PASSI:"
echo "1. Copia deploy/nginx.conf → /etc/nginx/conf.d/vigilanza-turni.conf"
echo "2. Clone repository: cd /var/www/vigilanza-turni && git clone <repo-url> ."
echo "3. Crea file .env con DATABASE_URL (password già configurata)"
echo "4. Ottieni certificato SSL: sudo certbot --nginx -d vt.alfacom.it"
echo "5. Esegui primo deploy: bash deploy/deploy.sh"
echo ""
log_warn "⚠️  IMPORTANTE - Password PostgreSQL:"
echo "Salvata in: /root/.vigilanza_db_password"
echo ""
log_info "DATABASE_URL per .env:"
echo "postgresql://vigilanza_user:PASSWORD_DA_FILE@localhost:5432/vigilanza_turni"
echo ""
echo "Recupera password con:"
echo "  cat /root/.vigilanza_db_password"
