#!/bin/bash

## Load action gets a first argument a FILE/DIRECTORY/URL 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] SOURCE"

dbname=
while [ "$1" ]; do
    case "$1" in
        "--help"|"-h")
            print_usage
            exit 0
        ;;
        *)
            [ -z "$SOURCE" ] && { SOURCE=$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

include parse
include pretty

set -e

USER=$(relation-get user)
DBNAME=$(relation-get dbname)
POSTGIS=$(relation-get postgis 2>/dev/null) || true
UNACCENT=$(relation-get unaccent 2>/dev/null) || true

opts=()
if [ "$POSTGIS" ]; then
    opts+=("--with-postgis")
fi

if [ "$UNACCENT" ]; then
    opts+=("--with-unaccent")
fi

run_service_action "$RELATION_TARGET_SERVICE" load "$SOURCE" "$USER@$DBNAME" "${opts[@]}" "$@"