#!/bin/sh

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

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

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

psql -c "alter user _defectdojo with password 'defectdojo'" defectdojo
