#!/bin/bash

# =============================================================================
# IDS - Fix PostgreSQL Authentication
# =============================================================================
# Risolve errore: "Ident authentication failed for user ids_user"
# Cambia autenticazione da 'ident' a 'scram-sha-256' (password-based)
# =============================================================================

set -e

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

echo -e "${BLUE}"
echo "╔═══════════════════════════════════════════════╗"
echo "║   PostgreSQL Authentication Fix               ║"
echo "╚═══════════════════════════════════════════════╝"
echo -e "${NC}"

# Trova pg_hba.conf
PG_HBA_CONF=$(sudo -u postgres psql -t -P format=unaligned -c 'SHOW hba_file;')

if [ -z "$PG_HBA_CONF" ]; then
    echo -e "${RED}❌ Impossibile trovare pg_hba.conf${NC}"
    exit 1
fi

echo -e "${BLUE}📂 File pg_hba.conf: ${PG_HBA_CONF}${NC}"
echo ""

# Backup originale
BACKUP_FILE="${PG_HBA_CONF}.backup_$(date +%Y%m%d_%H%M%S)"
echo -e "${YELLOW}💾 Backup configurazione...${NC}"
cp "$PG_HBA_CONF" "$BACKUP_FILE"
echo -e "${GREEN}✅ Backup salvato: ${BACKUP_FILE}${NC}"
echo ""

# Mostra configurazione attuale
echo -e "${BLUE}📋 Configurazione ATTUALE:${NC}"
grep -v "^#" "$PG_HBA_CONF" | grep -v "^$" | head -10
echo ""

# Modifica pg_hba.conf
echo -e "${YELLOW}🔧 Modifico pg_hba.conf...${NC}"

# Cambia tutte le occorrenze di 'ident' in 'scram-sha-256' per connessioni locali
sed -i.bak \
    -e 's/^\(local\s\+all\s\+all\s\+\)ident$/\1scram-sha-256/' \
    -e 's/^\(host\s\+all\s\+all\s\+127\.0\.0\.1\/32\s\+\)ident$/\1scram-sha-256/' \
    -e 's/^\(host\s\+all\s\+all\s\+::1\/128\s\+\)ident$/\1scram-sha-256/' \
    "$PG_HBA_CONF"

echo -e "${GREEN}✅ Configurazione modificata${NC}"
echo ""

# Mostra nuova configurazione
echo -e "${BLUE}📋 Configurazione NUOVA:${NC}"
grep -v "^#" "$PG_HBA_CONF" | grep -v "^$" | head -10
echo ""

# Reload PostgreSQL
echo -e "${YELLOW}🔄 Ricarico configurazione PostgreSQL...${NC}"
systemctl reload postgresql

echo -e "${GREEN}✅ PostgreSQL ricaricato${NC}"
echo ""

# Test connessione
echo -e "${BLUE}🧪 Test connessione con password...${NC}"

# Leggi password da .env se esiste
if [ -f "/opt/ids/.env" ]; then
    PGPASSWORD=$(grep "^PGPASSWORD=" /opt/ids/.env | cut -d'=' -f2)
    export PGPASSWORD
    
    if psql -h localhost -U ids_user -d ids_database -c "SELECT 1;" > /dev/null 2>&1; then
        echo -e "${GREEN}✅ Connessione RIUSCITA!${NC}"
        echo -e "${GREEN}   PostgreSQL ora accetta autenticazione con password${NC}"
    else
        echo -e "${RED}❌ Connessione FALLITA${NC}"
        echo -e "${YELLOW}   Verifica password in /opt/ids/.env${NC}"
        exit 1
    fi
else
    echo -e "${YELLOW}⚠️  File .env non trovato, salto test connessione${NC}"
fi

echo ""
echo -e "${GREEN}╔═══════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║   ✅ FIX COMPLETATO                           ║${NC}"
echo -e "${GREEN}╚═══════════════════════════════════════════════╝${NC}"
echo ""
echo "Modifiche effettuate:"
echo "  • Autenticazione cambiata: ident → scram-sha-256"
echo "  • Backup salvato: $BACKUP_FILE"
echo "  • PostgreSQL ricaricato"
echo ""
echo "Ora riavvia syslog_parser.py:"
echo "  pkill -f syslog_parser"
echo "  cd /opt/ids/python_ml"
echo "  sudo -u ids nohup python3.11 syslog_parser.py > /var/log/ids/syslog_parser.log 2>&1 &"
echo ""

exit 0
