#!/usr/bin/env bash
# Use the unofficial bash strict mode: http://redsymbol.net/articles/unofficial-bash-strict-mode/
set -euo pipefail; export FS=$'\n\t'

GDB_HOME=/opt/graphdb/dist/data
GDB_URL=http://localhost:7200
echo "waiting for GraphDB REST API available /protocol"

# this waits until GDB is ready to answer, so we can proceed and set passwords
curl -X GET \
    --silent --retry-all-errors \
    --connect-timeout ${POST_CONFIG_CONNECT_TIMEOUT} \
    --max-time ${POST_CONFIG_MAX_TIME} \
    --retry ${POST_CONFIG_RETRY} \
    --retry-delay ${POST_CONFIG_RETRY_DELAY} \
    --retry-max-time ${POST_CONFIG_RETRY_MAX_TIME} \
    --header 'Accept: application/json' \
    "${GDB_URL}/protocol" && echo " GraphDB REST API ready."

## default
USERPASSWORD="admin:root"

## if a password file exists take this as password
if [ -f ${GDB_HOME}/passwd ]; then
  echo "Will take password from ${GDB_HOME}/passwd"
  USERPASSWORD="admin:$(cat ${GDB_HOME}/passwd)"
  ## if passwordfile differs from env variable,
  if [ ${GRAPHDB_PASSWORD} != $(cat ${GDB_HOME}/passwd) ] ; then
    rm -f ${GDB_HOME}/password_changed
    echo "Password need to change"
  fi
else
  echo "no password found at ${GDB_HOME}/passwd, taking default"
fi 

# change admin password
if [ ! -f ${GDB_HOME}/password_changed ]; then
  echo "Set password to \${GRAPHDB_PASSWORD}"
  curl \
    --silent --retry-all-errors \
    --connect-timeout ${POST_CONFIG_CONNECT_TIMEOUT} \
    --max-time ${POST_CONFIG_MAX_TIME} \
    --retry ${POST_CONFIG_RETRY} \
    --retry-delay ${POST_CONFIG_RETRY_DELAY} \
    --retry-max-time ${POST_CONFIG_RETRY_MAX_TIME} \
    -X PUT -H 'Content-Type: application/json;charset=UTF-8' \
    -H 'Accept: application/json, text/plain, */*' \
    -H "X-GraphDB-Password: ${GRAPHDB_PASSWORD}" \
    -d "{\"appSettings\":{},\"grantedAuthorities\":[\"ROLE_ADMIN\"],\"password\":\"${GRAPHDB_PASSWORD}\",\"username\":\"admin\"} " \
    -u ${USERPASSWORD} \
    "${GDB_URL}/rest/security/users/admin" \
  && echo ${GRAPHDB_PASSWORD} > ${GDB_HOME}/passwd \
  && echo "GraphDB admin password is changed, new password is saved to '${GDB_HOME}/passwd'"
fi

# enable security
if [ ! -f /opt/graphdb/home/security_enabled ]; then
  curl -X POST \
    --silent --retry-all-errors \
    --connect-timeout ${POST_CONFIG_CONNECT_TIMEOUT} \
    --max-time ${POST_CONFIG_MAX_TIME} \
    --retry ${POST_CONFIG_RETRY} \
    --retry-delay ${POST_CONFIG_RETRY_DELAY} \
    --retry-max-time ${POST_CONFIG_RETRY_MAX_TIME} \
    --header 'Content-Type: application/json' \
    --header 'Accept: */*' \
    -d 'true' \
    "${GDB_URL}/rest/security" && \
  echo "GraphDB security has been enabled." && \
  touch ${GDB_HOME}/security_enabled
fi