66 lines
1.5 KiB
Bash
66 lines
1.5 KiB
Bash
#!/bin/bash
|
|
|
|
if [ "$(id -u)" != "0" ]; then
|
|
echo -e "\033[31mThis script requires superuser rights\033[0m"
|
|
exit 0
|
|
fi
|
|
|
|
if [ -z "$1" ] || [ -z "$2" ]; then
|
|
echo "Please provide all arguments: CREATE_DB_NAME, CREATE_DB_PASSWORD"
|
|
exit 1
|
|
fi
|
|
|
|
trap 'echo -e "\033[31minit-db.sh: An error has occurred\033[0m"; exit 1' ERR
|
|
set -e
|
|
|
|
export DEBIAN_FRONTEND=noninteractive
|
|
|
|
PG_CONTAINER=postgres
|
|
CREATE_DB_NAME=$1
|
|
CREATE_DB_PASSWORD=$2
|
|
|
|
: "${POSTGRES_USER:?}"
|
|
: "${POSTGRES_DB:?}"
|
|
|
|
# Function to check container status:
|
|
check_container_state() {
|
|
state=$(sudo docker inspect -f '{{.State.Health.Status}}' "$PG_CONTAINER" 2>/dev/null)
|
|
|
|
if [ "$state" = "healthy" ]; then
|
|
return 0
|
|
fi
|
|
|
|
state=$(sudo docker inspect -f '{{.State.Status}}' "$PG_CONTAINER" 2>/dev/null)
|
|
|
|
if [ "$state" = "running" ]; then
|
|
return 0
|
|
fi
|
|
|
|
return 1
|
|
}
|
|
|
|
echo "Waiting for PostgreSQL container to start..."
|
|
while ! check_container_state; do
|
|
echo "Waiting for PostgreSQL container to be ready..."
|
|
sleep 5
|
|
done
|
|
|
|
echo "PostgreSQL container is ready. Init DB..."
|
|
|
|
sudo docker exec -i $PG_CONTAINER psql -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB" <<-EOSQL
|
|
CREATE USER "$CREATE_DB_NAME" WITH ENCRYPTED PASSWORD '$CREATE_DB_PASSWORD';
|
|
CREATE DATABASE "$CREATE_DB_NAME";
|
|
GRANT ALL PRIVILEGES ON DATABASE "$CREATE_DB_NAME" TO "$CREATE_DB_NAME";
|
|
ALTER DATABASE "$CREATE_DB_NAME" OWNER TO "$CREATE_DB_NAME";
|
|
EOSQL
|
|
|
|
|
|
trap - ERR
|
|
echo -e "\033[32mDatabase $CREATE_DB_NAME created successfully\033[0m"
|
|
|
|
|
|
|
|
|
|
|
|
|