#!/bin/bash

## Colour for bash prompt
GREEN="\033[01;32m"
YELLOW="\033[01;33m"
RESET="\033[00m"

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

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

## Check if DB exists
if [ $(psql --quiet --tuples-only --no-align --list | awk -F '|' '/gvmd/{print $1}') ]; then
    echo -e "${YELLOW}[i]${RESET} Database gvmd already exists in PostgreSQL"
    new_db=1
else
    ## Create database
    echo -e "\n${GREEN}[*]${RESET} Creating database"
    createdb -O _gvm gvmd
    new_db=0
fi

sql=$(check_user dba)
if [[ "${sql}" == "1" ]]; then
    echo -e "${YELLOW}[i]${RESET} Role DBA already exists in PostgreSQL"
else
    echo -e "\n${GREEN}[*]${RESET} Creating permissions"
    psql -c "create role dba with superuser noinherit" gvmd
fi

echo -e "\n${GREEN}[*]${RESET} Applying permissions"
psql -c"grant dba to _gvm" gvmd

if  [ $(psql --quiet --tuples-only --no-align -c "SELECT * FROM pg_extension" gvmd | grep uuid-ossp) ]; then
    echo -e "${YELLOW}[i]${RESET} Extension uuid-ossp already exists for gvmd database"
else
    echo -e "\n${GREEN}[*]${RESET} Creating extension uuid-ossp"
    psql -c"create extension \"uuid-ossp\"" gvmd
fi

if  [ $(psql --quiet --tuples-only --no-align -c "SELECT * FROM pg_extension" gvmd | grep pgcrypto) ]; then
    echo -e "${YELLOW}[i]${RESET} Extension pgcrypto already exists for gvmd database"
else
    echo -e "\n${GREEN}[*]${RESET} Creating extension pgcrypto"
    psql -c"create extension \"pgcrypto\"" gvmd
fi

if  [ $(psql --quiet --tuples-only --no-align -c "SELECT * FROM pg_extension" gvmd | grep pg-gvm) ]; then
    echo -e "${YELLOW}[i]${RESET} Extension pg-gvm already exists for gvmd database"
else
    if [ $new_db -eq 1 ]; then
	echo -e "${GREEN}[i]${RESET} Remove old parts from DB for new pg-gvm extension"
	/usr/share/gvm/clean-db-for-migration-22.4
    fi
    echo -e "\n${GREEN}[*]${RESET} Creating extension pg-gvm"
    psql -c"create extension \"pg-gvm\"" gvmd
fi
