#!/bin/bash -e
# This is Free Software under GNU Affero General Public License v >= 3.0
# without warranty, see README.md and license for details.
#
# SPDX-License-Identifier: AGPL-3.0-or-later
# License-Filename: LICENSES/AGPL-3.0.txt
#
# Copyright (C) 2018 by via donau
#   – Österreichische Wasserstraßen-Gesellschaft mbH
# Software engineering by Intevation GmbH
#
# Author(s):
#  * Sascha Wilde <wilde@intevation.de>
#  * Tom Gottfried <tom@intevation.de>
#  * Sascha L. Teichmann <sascha.teichmann@intevation.de>

ME=`basename "$0"`
BASEDIR=`dirname "$0"`

usage()
{
  cat <<EOF
$ME [OPTION]...

Options:
  -d, --db=NAME    create the database NAME.  Default: "gemma"
  -p, --port=PORT  connect do the postgresql cluster at PORT.
                   Default is the postgresql standard port 5432
  -D, --demo       also install demo accounts and data
  -G, --geonames   also import geonames data
      --adminpw    set the password to use for the "sysadmin" account.
                   Default is a random password.
      --metapw     set the password to use for the "meta_login" account.
                   Default is a random password.
      --drop       drop database and all roles
      --help       display this help and exit

EOF
}

fatal()
{
  echo >&2 "$1"
  exit 23
}

genpw()
# $1 - length
{
  PW=''
  until [ "$(grep '[^[:alnum:]]' <<<$PW)" -a "$(grep '[[:digit:]]' <<<$PW)" ]
  do
    PW=$(dd count=1 if=/dev/urandom 2>/dev/null \
           | tr -cd '[:alnum:],._!?-' | tail -c "$1")
  done
  echo "$PW"
}

# Defaults:

db=gemma
port=5432
demo=0
geonames=0
drop=0
adminpw=`genpw 15`
metapw=`genpw 15`

# Parse options:

OPTS=`getopt \
      -l help,demo,geonames,db:,port:,drop,adminpw:,metapw: \
      -o DGd:p: -n "$ME" -- "$@"`
[ $? -eq 0 ] || { usage ; exit 1 ; }

eval set -- "$OPTS"

while true ; do
  case "$1" in
    --db|-d)
      db="$2"
      shift 2
      ;;
    --port|-p)
      port="$2"
      shift 2
      ;;
    --adminpw)
      adminpw="$2"
      shift 2
      ;;
    --metapw)
      metapw="$2"
      shift 2
      ;;
    --demo|-D)
      demo=1
      shift 1
      ;;
    --geonames|-G)
      geonames=1
      shift 1
      ;;
    --drop)
      drop=1
      shift 1
      ;;
    --help)
      { usage ; exit 0 ; }
      ;;
    --)
      shift
      break
      ;;
  esac
done


# Main ------------------------------------------------------------

if [[ drop -eq 0 ]] ; then
  # Default operation: create schema
  createdb -p "$port" "$db"
  psql -q -p "$port" -f "$BASEDIR/roles.sql" -d "$db"
  psql -qtv ON_ERROR_STOP= -p "$port" -d "$db" \
       -c "SET client_min_messages TO WARNING;" \
       -f "$BASEDIR/isrs.sql" \
       -f "$BASEDIR/gemma.sql" \
       -f "$BASEDIR/geo_functions.sql" \
       -f "$BASEDIR/search_functions.sql" \
       -f "$BASEDIR/geonames.sql" \
       -f "$BASEDIR/manage_users.sql" \
       -f "$BASEDIR/auth.sql" \
       -f "$BASEDIR/isrs_functions.sql" \
       -f "$BASEDIR/default_sysconfig.sql"


  # setup initial login roles with given passwords:
  psql -qt -P pager=off -p "$port" -d "$db" \
       -v adminpw="$adminpw" -v metapw="$metapw" \
       -f "$BASEDIR/std_login_roles.sql"

  if [[ $demo -eq 1 ]] ; then
    psql -qv ON_ERROR_STOP= -p "$port" -d "$db" \
         -f "$BASEDIR/demo-data/responsibility_areas.sql" \
         -f "$BASEDIR/demo-data/users.sql" \
         -f "$BASEDIR/demo-data/published_services.sql"
    psql -q -p "$port" -f "$BASEDIR/demo-data/roles.sql" \
         -d "$db"
  fi

  if [[ $geonames -eq 1 ]] ; then
    "$BASEDIR/geonames-import/import-geonames.sh" -p "$port" -d "$db"
  fi

else
  # Evil mode: drop everything gemma
  echo "Really drop database '$db' and all gemma roles? [type 'yes']: "
  read a
  if [[ $a == "yes" ]] ; then
    dropdb -p "$port" "$db"
    psql -p $port -A -t -c '\du' | awk -F '|' -v port=$port \
        '$1 "." $3 ~ /waterway_user|waterway_admin|sys_admin|metamorph/ \
	    { system("dropuser -p " port " \"" $1 "\"") }'
  else
    echo "No harm done."
  fi
fi
