#!/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) 2019 by via donau
#   – Österreichische Wasserstraßen-Gesellschaft mbH
# Software engineering by Intevation GmbH
#
# Author(s):
# * Sascha Wilde <wilde@intevation.de>

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

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

Upload map styles to gemma.

Options:
  -P, --g_port=GPORT  connect to gemma server at GPORT. Default 8000.
  -g, --g_host=GHOST  connect to gemma server on GHOST. Default "localhost".
  -u, --g_user=GUSER  login to gemma as user GUSER. Default "sophie".
      --g_pw=GPW      password for GUSER. Default "so2Phie4".
      --help          display this help and exit

EOF
}

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

# Defaults:

g_port=8000
g_host="localhost"
g_user="sophie"
g_pw="so2Phie4"

# Parse options:

OPTS=`getopt \
      -l help,g_port:,g_host:,g_user:,g_pw: \
      -o P:g:u: -n "$ME" -- "$@"`
[ $? -eq 0 ] || { usage ; exit 1 ; }

eval set -- "$OPTS"

while true ; do
  case "$1" in
    --g_port|-P)
      g_port="$2"
      shift 2
      ;;
    --g_host|-g)
      g_host="$2"
      shift 2
      ;;
    --g_user|-u)
      g_user="$2"
      shift 2
      ;;
    --g_pw)
      g_pw="$2"
      shift 2
      ;;
    --help)
      { usage ; exit 0 ; }
      ;;
    --)
      shift
      break
      ;;
  esac
done

if [ $# != 0 ] ; then
  { usage ; exit 23 ; }
fi

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

# Login to gemma server
login=$(curl -f -s -S -X POST \
             -d "{\"user\":\"${g_user}\",\"password\":\"${g_pw}\"}" \
             "http://${g_host}:${g_port}/api/login")
token=$(jq -r '.token' <<<"$login")
if [ -z "$token" ]
then
  echo "could not login to gemma server" >&2
  exit 1
fi

roles=$(jq -r '.roles' <<<"$login")

basedir=$( dirname $( realpath "${BASH_SOURCE[0]}" ))
datadir="${basedir}/."

if jq -e 'any(. == "sys_admin")' <<<"$roles" > /dev/null
then
  echo "== Configuring geoserver styles" >&2
  for style in $(basename -s .sld-template $(ls $datadir/*.sld-template))
  do
    curl -f -s -S -H "X-Gemma-Auth:${token}" -X POST \
         -F style=@"${datadir}/${style}.sld-template" \
         "http://${g_host}:${g_port}/api/geo/style/${style}"
  done
else
  echo >&2 'Not authorized as sys_admin'
fi
