# -*- mode: shell-script -*-

include pretty

export DB_NAME="$SERVICE_NAME"                          ## general type of database (ie: postgres/mysql...)
export DB_DATADIR=/var/lib/postgresql/data

export DATA_DIR=$SERVICE_DATASTORE$DB_DATADIR
export LOCAL_DB_PASSFILE="$DATA_DIR/pgpass"

export CLIENT_DB_PASSFILE="/root/.pgpass"
export PG_HBA="$DATA_DIR/pg_hba.conf"


is_db_locked() {
    local host_db_volume
    if [ "${HOST_DATASTORE+x}" ]; then
        host_db_volume="$HOST_DATASTORE/${SERVICE_NAME}$DB_DATADIR"
    else
        host_db_volume="$DATASTORE/${SERVICE_NAME}$DB_DATADIR"
    fi

    is_volume_used "$host_db_volume"
}


_set_server_db_params() {
    server_docker_opts+=()
}

_set_db_params() {
    local docker_ip="$1" docker_network="$2"

    if [ "${HOST_DATASTORE+x}" ]; then
        export HOST_DB_PASSFILE="$HOST_DATASTORE/${SERVICE_NAME}$DB_DATADIR/pgpass"
    else
        export HOST_DB_PASSFILE="$CLIENT_DB_PASSFILE"
    fi

    [ -f "$CLIENT_DB_PASSFILE" ] || touch "$CLIENT_DB_PASSFILE"

    db_docker_opts+=("--network" "$docker_network"
                    "-e" PGHOST="$docker_ip"
                    "-e" PGUSER=postgres
                    "-e" prefix_pg_local_command=' ')

    db_cmd_opts+=()
    check_command="SELECT 1;"
}

ddb () { dcmd psql -qAt "$@"; }


##
## Entrypoints
##


db_drop () {
    local dbname="$1"
    dcmd dropdb --if-exists "$1"
}

db_create () {
    local dbname="$1"
    shift
    dcmd createdb "$dbname" "$@" || return 1
    info "Database '$dbname' created."
}

db_install_extensions() {
    local dbname="$1"
    shift
    while [ "$#" != 0 ]; do
        case "$1" in
            postgis)
                if out=$(ddb -d "$dbname" < <(echo "SELECT extname
                                                    FROM pg_extension
                                                    WHERE extname = 'postgis';")); then
                    if [ "$out" ]; then
                        info "PostGIS already installed."
                        shift
                        continue
                    fi
                fi

                ddb -d "$dbname" < <(echo "CREATE EXTENSION IF NOT EXISTS postgis;
                                           CREATE EXTENSION IF NOT EXISTS postgis_topology;") || return 1

                dcmd /bin/bash -c "psql -d '$dbname' -v ON_ERROR_STOP=1 -f /usr/local/share/postgresql/contrib/postgis-*/legacy.sql" || return 1
                info "Installed postgis extensions on database '$dbname'."
                ;;
            *)
                ddb -d "$dbname" < <(echo "CREATE EXTENSION IF NOT EXISTS $1;") || return 1
                info "Installed $1 extension on database '$dbname'."
                ;;
        esac
        shift
    done
}

## XXXvlab: if launched first, it'll fail handling correctly the open/close of docker
db_has_database() {
    local dbname="$1"
    if [ "$(ddb < <(echo "SELECT 1 FROM pg_database WHERE datname = '$dbname'"))" ]; then
        debug "Database $dbname exists."
        return 0
    else
        debug "Database $dbname exists."
        return 1
    fi
}

## XXXvlab: if launched first, it'll fail handling correctly the open/close of docker
db_has_user() {
    local user="$1" users
    users=$(ddb < <(echo "select u.usename from pg_catalog.pg_user u")) || {
        err "Failed to get user list"
        return 1
    }
    echo "$users" | grep "^${user}$" >/dev/null 2>&1
}

db_create_user() {
    local user="$1" password="$2"
    ## Using this instead of pipes is important so that trap works
    ddb < <(echo "CREATE USER \"$user\" WITH PASSWORD '$password' CREATEDB NOCREATEROLE;")
}

db_change_password() {
    local user="$1" password="$2"
    ## Using this instead of pipes is important so that trap works
    ddb < <(echo "ALTER USER \"$user\" WITH PASSWORD '$password';")
}


PGM() {
    ensure_db_docker_running </dev/null || return 1
    echo "${db_docker_opts[@]}"
    dcmd pgm "$@"
}

db_grant_rights () {
    local dbname="$1" user="$2"
    PGM chown -v "$user" "$dbname"
}