-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinit.sh
42 lines (33 loc) · 1.73 KB
/
init.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#!/bin/bash
set -e
# Define PostgreSQL version
PG_VERSION=11
# Paths
POSTGRES_BIN_DIR="/usr/lib/postgresql/${PG_VERSION}/bin"
# Initialize PostgreSQL data directory if it doesn't exist
if [ ! -d "/var/lib/postgresql/data" ]; then
echo "Initializing PostgreSQL data directory..."
mkdir -p /var/lib/postgresql/data
chown -R postgres:postgres /var/lib/postgresql
su postgres -c "${POSTGRES_BIN_DIR}/initdb -D /var/lib/postgresql/data"
fi
# Update pg_hba.conf to allow password authentication
PG_HBA=/var/lib/postgresql/data/pg_hba.conf
if [ -f "$PG_HBA" ]; then
echo "Configuring PostgreSQL to use md5 authentication..."
sed -i "s/^\(local\s\+all\s\+all\s\+\)peer/\1md5/" $PG_HBA
fi
# Start PostgreSQL to perform setup
echo "Starting PostgreSQL..."
su postgres -c "${POSTGRES_BIN_DIR}/pg_ctl -D /var/lib/postgresql/data -w start"
# Create PostgreSQL user with SUPERUSER privilege if it doesn't exist
echo "Creating PostgreSQL user with SUPERUSER privilege if it doesn't exist..."
su postgres -c "psql -tc \"SELECT 1 FROM pg_roles WHERE rolname = '$db_username'\" | grep -q 1 || psql -c \"CREATE USER $db_username WITH PASSWORD '$db_password' SUPERUSER;\""
# Create database if it doesn't exist
echo "Creating PostgreSQL database if it doesn't exist..."
su postgres -c "psql -tc \"SELECT 1 FROM pg_database WHERE datname = '$password_vault_db'\" | grep -q 1 || psql -c \"CREATE DATABASE $password_vault_db OWNER $db_username;\""
# Grant all privileges on the database to the user
su postgres -c "psql -c \"GRANT ALL PRIVILEGES ON DATABASE $password_vault_db TO $db_username;\""
# Stop PostgreSQL (Supervisor will manage it)
echo "Stopping PostgreSQL..."
su postgres -c "${POSTGRES_BIN_DIR}/pg_ctl -D /var/lib/postgresql/data -m fast -w stop"