#!/usr/bin/env bash
set -e

script=$(basename "$0")
version="1.0.1"

help() {
  echo
  echo "$script"
  echo
  echo 'Description: Restore Docker Postgres database.'
  echo "Syntax: $script [-c|-d|-f|-r|-i|help]"
  echo 'Example: $script -d odoo -f /tmp/dump.sql -c postgres01 -r'
  echo 'options:'
  echo '  -c    Docker container name. Defaults to '\''postgres'\''.'
  echo '  -d    Name of database. Defaults to filename'
  echo '  -f    Path to sql dump.'
  echo '  -r    Replace existing database.'
  echo '  -i    Create database.'
  echo "  help  Show $script manual."
  echo
}

if [[ "$1" == 'help' ]]; then
    help
    exit
fi

drop='false'
create='false'
container=postgres

while getopts ':c: :d: :f: :r :i' opt; do
  case $opt in
    c) container="$OPTARG";;
    d) database="$OPTARG";;
    f) file="$OPTARG";;
    r) drop='true'
      create='true'
    ;;
    i) create='true';;
    \?) echo "Invalid option -$OPTARG" >&2
    help
    exit 1;;
  esac
done

filename=$(basename -- "$file")
database=${database:="${filename%%.*}"}

[[ -z "$file" ]] && { echo 'Parameter -f|filename is empty.' ; exit 1; }

postgres_user=$(docker exec $container /bin/bash -c "echo \$POSTGRES_USER")

if $drop; then
  docker-postgres-drop -c $container -d $database
fi

if $create; then
  echo "Create Postgres database $database ..."
  docker exec $container createdb -U $postgres_user $database
fi

echo "Restore Postgres database $database from $file ..."
cat $file | docker exec -i $container psql -U $postgres_user -d $database

echo "Grant all privileges on $database to $postgres_user ..."
docker exec $container psql -U $postgres_user -d template1 -c "GRANT ALL PRIVILEGES ON DATABASE \"$database\" TO $postgres_user;"

echo 'The Docker Postgres restore has finished.'
