#!/bin/bash
# Filename: ubuntu-php-postgres.sh
# Perform PHP and Postgres installation and best practices config for dev environment.
# Run this script only once!
#
# To run to run use one of the below commands:
# wget -O - -q https://go.poorna.net/go/ubuntu-php-postgres.sh | bash
# curl -s      https://go.poorna.net/go/ubuntu-php-postgres.sh | bash

# Check that we are running this as root
if [ "$(id -u)" -ne 0 ]; then
  echo 'ERROR: This script must be run as root.'
  exit 1
fi

# Ensure that we are running on an ubuntu host
. /etc/os-release
if [ "$ID" != "ubuntu" ]; then
  echo 'ERROR: This script is intended to run only on an Ubuntu host.'
  exit 1
fi

set -eoux pipefail

echo 'Install packages'
apt update; apt -y upgrade; apt clean

echo 'Install PHP Packages'
apt -y install \
  composer \
  git \
  php-bcmath \
  php-cli \
  php-curl \
  php-gd \
  php-intl \
  php-json \
  php-ldap \
  php-mbstring \
  php-memcached \
  php-mysql \
  php-pgsql \
  php-soap \
  php-tidy \
  php-uploadprogress \
  php-xml \
  php-xmlrpc \
  php-yaml \
  php-zip

echo 'Install ImageMagick CLI tools'
apt -y install --no-install-recommends imagemagick

echo 'Install PostgreSQL latest'
apt -y install postgresql-16

echo 'Clean up apt setup files'
apt autoremove; apt clean

echo 'Setting postgresql config to listen connection from 0.0.0.0/0'
mkdir /etc/postgresql/16/main/conf.d
cat > /etc/postgresql/16/main/conf.d/zz-base.conf <<EOT
listen_addresses = '*'
EOT
cat >> /etc/postgresql/16/main/pg_hba.conf <<EOT

# Custom config to allow from any IP to connect to all databases using password auth
# TYPE  DATABASE        USER            ADDRESS                 METHOD
host    all             all             0.0.0.0/0               md5
host    all             all             ::/0                    md5
EOT

echo 'Restarting postgresql with new config'
systemctl restart postgresql

echo 'SUCCESS: PHP and PostgreSQL packages installed successfully'
