#!/bin/sh

check_user(){
    psql \
        --quiet \
        --tuples-only \
        --no-align \
        -c "SELECT 1 FROM pg_roles WHERE rolname='$1'" \
        postgres
}

sql=$(check_user _bloodhound)
if [ "${sql}" = "1" ]; then
    echo "User _bloodhound already exists in PostgreSQL"
else
    ## Create database user
    printf "\n Creating database user\n"
    createuser -DRS _bloodhound
fi

## Check if DB exists
if [ $(psql --quiet --tuples-only --no-align --list | awk -F '|' '/bloodhound/{print $1}') ]; then
    echo "Database bloodhound already exists in PostgreSQL"
else
    ## Create database
    printf "\n Creating database\n"
    createdb -O _bloodhound bloodhound
fi

## Set the password: the one of /etc/bhapi/bhapi.json, that bloodhound-setup
## passes in the BLOODHOUND_DB_PASSWORD environment variable ("bloodhound" if
## unset). It goes to psql through stdin, not visible in the process list
password=$(printf '%s' "${BLOODHOUND_DB_PASSWORD:-bloodhound}" | sed "s/'/''/g")
psql --quiet -v ON_ERROR_STOP=1 bloodhound <<EOF
ALTER USER _bloodhound WITH PASSWORD '${password}';
EOF

