#!/bin/bash

# Log files
ERROR_LOG="error.log"
INSTALL_LOG="install.log"

# Colors for status messages
GREEN="\033[0;32m"
RED="\033[0;31m"
YELLOW="\033[0;33m"
NC="\033[0m" # No color

# Function to print messages with color
status_message() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

error_message() {
    echo -e "${RED}[ERROR]${NC} $1"
    echo "$(date '+%Y-%m-%d %H:%M:%S') [ERROR] $1" >> "$ERROR_LOG"
}

warning_message() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

# Variables for PostgreSQL user setup
DB_USERNAME="postG"
DB_PASSWORD="secretPost22!"

# Update package list
status_message "Updating package list..."
if sudo apt update; then
    status_message "Package list updated successfully."
else
    error_message "Failed to update package list."
    exit 1
fi

# Install PostgreSQL
status_message "Installing PostgreSQL..."
if sudo apt install -y postgresql postgresql-contrib; then
    status_message "PostgreSQL installed successfully."
else
    error_message "Failed to install PostgreSQL."
    exit 1
fi

# Enable and start PostgreSQL service
status_message "Enabling and starting PostgreSQL service..."
if sudo systemctl enable postgresql && sudo systemctl start postgresql; then
    status_message "PostgreSQL service started successfully."
else
    error_message "Failed to start PostgreSQL service."
    exit 1
fi

# Setting up PostgreSQL 
status_message "Setting up PostgreSQL user and password..."
sudo -u postgres psql -c "CREATE USER $DB_USERNAME WITH PASSWORD '$DB_PASSWORD';" 2>>"$ERROR_LOG"
if [ $? -eq 0 ]; then
    status_message "User '$DB_USERNAME' created successfully."
else
    error_message "Failed to create user '$DB_USERNAME'."
    exit 1
fi

# Granting privileges to the user
status_message "Granting privileges to the user '$DB_USERNAME'..."
sudo -u postgres psql -c "ALTER USER $DB_USERNAME WITH SUPERUSER;" 2>>"$ERROR_LOG"
if [ $? -eq 0 ]; then
    status_message "Privileges granted to user '$DB_USERNAME'."
else
    error_message "Failed to grant privileges to user '$DB_USERNAME'."
    exit 1
fi

# Log successful installation
echo "$(date '+%Y-%m-%d %H:%M:%S') postgres ok" >> "$INSTALL_LOG"
status_message "Installation and user setup complete. Log written to $INSTALL_LOG."
