2024-07-27 04:15:43 +05:00
|
|
|
#!/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
|
2024-08-14 13:44:56 +05:00
|
|
|
echo "Please provide all arguments: CREATE_DB_NAME, CREATE_DB_PASSWORD"
|
2024-07-27 04:15:43 +05:00
|
|
|
exit 1
|
|
|
|
fi
|
|
|
|
|
2024-08-14 13:44:56 +05:00
|
|
|
trap 'echo -e "\033[31minit-db.sh: An error has occurred\033[0m"; exit 1' ERR
|
2024-07-27 04:15:43 +05:00
|
|
|
set -e
|
|
|
|
|
|
|
|
export DEBIAN_FRONTEND=noninteractive
|
|
|
|
|
2024-08-18 08:37:27 +05:00
|
|
|
PG_CONTAINER=postgres
|
2024-07-27 04:15:43 +05:00
|
|
|
CREATE_DB_NAME=$1
|
|
|
|
CREATE_DB_PASSWORD=$2
|
|
|
|
|
|
|
|
: "${POSTGRES_USER:?}"
|
|
|
|
: "${POSTGRES_DB:?}"
|
|
|
|
|
2024-08-18 08:37:27 +05:00
|
|
|
# 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
|
2024-07-27 04:15:43 +05:00
|
|
|
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
|
|
|
|
|
|
|
|
|
2024-08-14 13:44:56 +05:00
|
|
|
trap - ERR
|
2024-07-27 04:15:43 +05:00
|
|
|
echo -e "\033[32mDatabase $CREATE_DB_NAME created successfully\033[0m"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|