#!/bin/bash
# Setup script for PostgreSQL database for PunimTag

set -e

echo "🔧 Setting up PostgreSQL for PunimTag..."

# Check if PostgreSQL is installed
if ! command -v psql &> /dev/null; then
    echo "📦 Installing PostgreSQL..."
    sudo apt update
    sudo apt install -y postgresql postgresql-contrib
    echo "✅ PostgreSQL installed"
else
    echo "✅ PostgreSQL is already installed"
fi

# Start PostgreSQL service
echo "🚀 Starting PostgreSQL service..."
sudo systemctl start postgresql
sudo systemctl enable postgresql

# Create database and user
echo "📝 Creating database and user..."
sudo -u postgres psql << EOF
-- Create user if it doesn't exist
DO \$\$
BEGIN
    IF NOT EXISTS (SELECT FROM pg_user WHERE usename = 'punimtag') THEN
        CREATE USER punimtag WITH PASSWORD 'punimtag_password';
    END IF;
END
\$\$;

-- Create main database if it doesn't exist
SELECT 'CREATE DATABASE punimtag OWNER punimtag'
WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'punimtag')\gexec

-- Create auth database if it doesn't exist
SELECT 'CREATE DATABASE punimtag_auth OWNER punimtag'
WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'punimtag_auth')\gexec

-- Grant privileges
GRANT ALL PRIVILEGES ON DATABASE punimtag TO punimtag;
GRANT ALL PRIVILEGES ON DATABASE punimtag_auth TO punimtag;
\q
EOF

echo "✅ Database and user created"
echo ""
echo "📋 Database connection details:"
echo "   Host: localhost"
echo "   Port: 5432"
echo "   Main Database: punimtag"
echo "   Auth Database: punimtag_auth"
echo "   User: punimtag"
echo "   Password: punimtag_password"
echo ""
echo "✅ PostgreSQL setup complete!"
echo ""
echo "Next steps:"
echo "1. Install python-dotenv: pip install python-dotenv"
echo "2. The .env file is already configured with the connection string"
echo "3. Run your application - it will connect to PostgreSQL automatically"





