#!/bin/bash

# Check if PostgreSQL is installed already
if command -v psql > /dev/null; then
    echo "PostgreSQL is already installed."
    echo "Exiting script."
    exit 0
fi

# Set the timezone value for tzdata
export DEBIAN_FRONTEND=noninteractive
sudo ln -fs /usr/share/zoneinfo/America/New_York /etc/localtime
sudo dpkg-reconfigure --frontend noninteractive tzdata

# Update system
echo "####### UPDATING SYSTEM #######"
sudo apt update
sudo apt upgrade -y

echo ""

# Install PostgreSQL
echo "####### INSTALLING POSTGRESQL #######"
sudo apt install libpq-dev postgresql postgresql-contrib -y

echo ""

# Log into PostgreSQL console and change default user password
echo "####### CHANGING DEFAULT PASSWORD #######"
sudo -u postgres psql -c "ALTER USER postgres WITH PASSWORD 'Admin#321';"

echo ""

# Allow remote access by updating postgresql.conf
echo "####### ALLOWING REMOTE ACCESS #######"
sudo sed -i "s/#listen_addresses = 'localhost'/listen_addresses = '*'/g" /etc/postgresql/*/main/postgresql.conf

echo ""

# Update pg_hba.conf to allow remote connections
echo "####### ALLOWING REMOTE CONNECTIONS #######"
sudo sed -i "s/host    all             all             127.0.0.1\/32            md5/host    all             all             0.0.0.0\/0            md5/g" /etc/postgresql/*/main/pg_hba.conf

echo ""

# Allow port 5432 through the firewall
echo "####### ALLOWING 5432 PORT #######"
sudo ufw allow 5432/tcp

echo ""

# Allow SSH through the firewall
echo "####### ALLOWING SSH THROUGH FIREWALL #######"
sudo ufw allow ssh

echo ""

# Enable the firewall
echo "####### ENABLING FIREWALL #######"
sudo ufw --force enable

echo ""

# Restart PostgreSQL
echo "####### RESTARTING POSTGRESQL #######"
sudo systemctl restart postgresql

echo ""

# Reboot the system
echo "####### REBOOTING SYSTEM #######"
sudo reboot