#!/bin/bash

## Load action gets a first argument a DIRECTORY holding the necessary files.
##
##

if [ -z "$SERVICE_DATASTORE" ]; then
    echo "This script is meant to be run through 'compose' to work properly." >&2
    exit 1
fi

usage="$exname [-h|--help] [--with-postgis] [--with-unaccent] SOURCE DBNAME"

dbname=
postgis=
while [ "$1" ]; do
    case "$1" in
        "--help"|"-h")
            print_usage
            exit 0
        ;;
        "--with-postgis")
            postgis=true
        ;;
        "--with-unaccent")
            unaccent=true
        ;;
        *)
            [ -z "$SOURCE" ] && { SOURCE=$1 ; shift ; continue ; }
            [ -z "$dbname" ] && { dbname=$1 ; shift ; continue ; }
            err "Unexpected argument '$1'."
            exit 1
        ;;
    esac
    shift
done

if [ -z "$SOURCE" ]; then
    err "You must provide a source file as first argument."
    print_usage
    exit 1
fi

if [ -z "$dbname" ]; then
    err "You must provide a destination database name as second argument."
    print_usage
    exit 1
fi

if [[ "$dbname" == *"@"* ]]; then
    IFS="@" read user dbname < <(echo "$dbname")
fi

. "$CHARM_PATH/lib/common"

## This can work only if ~/.pgpass is correctly created by init.

set -e


db_drop "$dbname"
POSTGIS=$postgis UNACCENT=$unaccent db_create "$dbname"


ddb "$dbname" > /dev/null < <(get_file "$SOURCE")

[ "$user" ] &&
    db_grant_rights "$dbname" "$user"

info "Loaded '$SOURCE' into database '$dbname'."