#!/bin/bash
set -e

# Must be run as (a) Postgres super user

SQL_INIT=swh-init.sql
SQL_ENUMS=swh-enums.sql
SQL_SCHEMA=swh-schema.sql
SQL_FUNC=swh-func.sql
SQL_INDEX=swh-indexes.sql
SQL_TRIGGER=swh-triggers.sql
SQL_DATA=swh-data.sql
ROOT_SQLS="$SQL_INIT"
USER_SQLS="$SQL_ENUMS $SQL_SCHEMA $SQL_FUNC $SQL_INDEX $SQL_TRIGGER $SQL_DATA"
SQLS="$ROOT_SQLS $USER_SQLS"

DB_ENCODING="UTF-8"
DB_LOCALE="C.UTF-8"
DB_TEMPLATE="template0"

cd "$( dirname $0 )/.."

if ! [ -f "$SQL_INIT" ] ; then
    echo "Cannot find $SQL_INIT. Abort."
    exit 2
fi

if [ -z "$1" ] ; then
    echo "Usage: bin/db-init DB_NAME [DB_PORT]"
    echo "Example: bin/db-init softwareheritage-dev"
    echo "Note: DB_NAME should not exist and will be created"
    exit 2
fi
db_name="$1"
port=${2:-5432}

conn_flags="--port $port"

echo "I: creating Postgres database ${db_name} ..."
createdb $conn_flags \
         --encoding "$DB_ENCODING" --locale "$DB_LOCALE" \
         --template "$DB_TEMPLATE" "$db_name"

sqls_flags=''
for f in $SQLS ; do
    sqls_flags="${sqls_flags} --file ${f}"
done

echo "I: initializing DB ${db_name} ..."
psql $conn_flags ${sqls_flags} "$db_name"

echo "I: all done."
