#!/bin/bash

# PostgreSQL Installation and Configuration Script for GNX-WEB
# This script installs PostgreSQL and configures it to use port 5433
# to avoid conflicts with Docker PostgreSQL instance on port 5432

set -e

echo "=========================================="
echo "PostgreSQL Installation Script"
echo "=========================================="

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    echo -e "${RED}Please run as root (use sudo)${NC}"
    exit 1
fi

# Update package list
echo -e "${GREEN}[1/7] Updating package list...${NC}"
apt-get update

# Install PostgreSQL
echo -e "${GREEN}[2/7] Installing PostgreSQL...${NC}"
apt-get install -y postgresql postgresql-contrib

# Get PostgreSQL version
PG_VERSION=$(psql --version | grep -oP '\d+' | head -1)
PG_MAJOR_VERSION=$(echo $PG_VERSION | cut -d. -f1)

echo -e "${GREEN}[3/7] PostgreSQL version: $PG_VERSION${NC}"

# Find postgresql.conf file
PG_CONF="/etc/postgresql/$PG_MAJOR_VERSION/main/postgresql.conf"

if [ ! -f "$PG_CONF" ]; then
    echo -e "${RED}Error: Could not find PostgreSQL configuration file${NC}"
    exit 1
fi

# Backup original configuration
echo -e "${GREEN}[4/7] Backing up PostgreSQL configuration...${NC}"
cp "$PG_CONF" "${PG_CONF}.backup.$(date +%Y%m%d_%H%M%S)"

# Configure PostgreSQL to use port 5433
echo -e "${GREEN}[5/7] Configuring PostgreSQL to use port 5433...${NC}"

# Check if port is already set
if grep -q "^port = " "$PG_CONF"; then
    # Replace existing port setting
    sed -i "s/^port = .*/port = 5433/" "$PG_CONF"
else
    # Add port setting
    echo "port = 5433" >> "$PG_CONF"
fi

# Restart PostgreSQL
echo -e "${GREEN}[6/7] Restarting PostgreSQL...${NC}"
systemctl restart postgresql

# Wait for PostgreSQL to start
sleep 2

# Verify PostgreSQL is running on port 5433
if netstat -tlnp 2>/dev/null | grep -q ":5433" || ss -tlnp 2>/dev/null | grep -q ":5433"; then
    echo -e "${GREEN}[7/7] PostgreSQL is running on port 5433${NC}"
else
    echo -e "${YELLOW}Warning: Could not verify PostgreSQL is running on port 5433${NC}"
fi

echo ""
echo -e "${GREEN}=========================================="
echo "PostgreSQL Installation Complete!"
echo "==========================================${NC}"
echo ""
echo "Next steps:"
echo "1. Create database and user:"
echo "   sudo -u postgres psql"
echo "   CREATE DATABASE gnx_db;"
echo "   CREATE USER gnx_user WITH PASSWORD 'your_password';"
echo "   GRANT ALL PRIVILEGES ON DATABASE gnx_db TO gnx_user;"
echo "   \\q"
echo ""
echo "2. Update your .env file with:"
echo "   DATABASE_URL=postgresql://gnx_user:your_password@localhost:5433/gnx_db"
echo ""

