#!/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] DBNAME DEST"

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


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

if [ -z "$DEST" ]; then
    err "You must provide a dest file as second argument."
    print_usage
    exit 1
fi

realpath=$(realpath "$DEST") || exit 1
dirname="$(dirname "$realpath")" || exit 1
basename=$(basename "$realpath") || exit 1
host_path="$(get_host_path "$dirname")" || {
    die "Failed to find host path for local directory: $dirname"
}

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

. "$CHARM_PATH"/lib/common

set -e

if ! db_has_database "$dbname"; then
    err "Can't find database '$dbname'."
    exit 1
fi

db_docker_opts+=("-v" "$host_path:/tmp/work")
PGM cp "$dbname" "/tmp/work/$basename" || {
    die "pgm command failed !"
}
info "Saved database '$dbname' into '$DEST'."