#!/bin/bash

# replace environment variables in config files
perl -pi -e 's/\$\{DSPACE_USER\}/$ENV{DSPACE_USER}/; s/\$\{DSPACE_PASSWORD\}/$ENV{DSPACE_PASSWORD}/; s/\$\{MAIL_USER\}/$ENV{MAIL_USER}/; s/\$\{MAIL_PASSWORD\}/$ENV{MAIL_PASSWORD}/; s/\$\{DSPACE_DBNAME\}/$ENV{DSPACE_DBNAME}/; s/\$\{DSPACE_UTILSDBNAME\}/$ENV{DSPACE_UTILSDBNAME}/;' /opt/repository/sources/dspace/local.properties
perl -pi -e 's/\$\{DSPACE_USER\}/$ENV{DSPACE_USER}/; s/\$\{DSPACE_PASSWORD\}/$ENV{DSPACE_PASSWORD}/; s/\$\{MAIL_USER\}/$ENV{MAIL_USER}/; s/\$\{MAIL_PASSWORD\}/$ENV{MAIL_PASSWORD}/; s/\$\{DSPACE_DBNAME\}/$ENV{DSPACE_DBNAME}/; s/\$\{DSPACE_UTILSDBNAME\}/$ENV{DSPACE_UTILSDBNAME}/;' /opt/repository/sources/dspace/target/local.properties
perl -pi -e 's/\$\{DSPACE_USER\}/$ENV{DSPACE_USER}/; s/\$\{DSPACE_PASSWORD\}/$ENV{DSPACE_PASSWORD}/; s/\$\{MAIL_USER\}/$ENV{MAIL_USER}/; s/\$\{MAIL_PASSWORD\}/$ENV{MAIL_PASSWORD}/; s/\$\{DSPACE_DBNAME\}/$ENV{DSPACE_DBNAME}/; s/\$\{DSPACE_UTILSDBNAME\}/$ENV{DSPACE_UTILSDBNAME}/;' /opt/lindat-dspace/installation/config/dspace.cfg
perl -pi -e 's/\$\{DSPACE_USER\}/$ENV{DSPACE_USER}/; s/\$\{DSPACE_PASSWORD\}/$ENV{DSPACE_PASSWORD}/; s/\$\{MAIL_USER\}/$ENV{MAIL_USER}/; s/\$\{MAIL_PASSWORD\}/$ENV{MAIL_PASSWORD}/; s/\$\{DSPACE_DBNAME\}/$ENV{DSPACE_DBNAME}/; s/\$\{DSPACE_UTILSDBNAME\}/$ENV{DSPACE_UTILSDBNAME}/;' /opt/lindat-dspace/installation/config/modules/lr.cfg

# adapt handle config
perl -pi -e 's/\$\{HANDLE_USER\}/$ENV{HANDLE_USER}/; s/\$\{HANDLE_PASSWORD\}/$ENV{HANDLE_PASSWORD}/; s/\$\{HANDLE_DBNAME\}/$ENV{HANDLE_DBNAME}/;' /opt/lindat-dspace/installation/handle-server/config.dct

# start handle server
/etc/init.d/handle-server start

# initialize statistics & co
/opt/tomcat8/bin/startup.sh
cd /opt/repository/workspace/scripts
make init_statistics

# https://ubuntuforums.org/showthread.php?t=979694
# Start process in the background and send its output to file descriptor 3
exec 3< <(while (true); do
    timeout -k 30 300 make update_oai
    timeout -k 30 300 make update_statistics
    timeout -k 30 300 make update_sitemap
    timeout -k 30 300 make lift_embargos
    timeout -k 30 300 make update_openaire_cache
    timeout -k 30 300 make update_discovery
    timeout -k 30 300 make send_info
    echo "INIT DONE."
    sleep 86400
done)

# Read the output of the process line by line until one line contains Ready
while read line; do
   case "$line" in
   "INIT DONE.")
      break
      ;;
   esac
done <&3

# Close the file descriptor
exec <&3 3<&-
/opt/tomcat8/bin/shutdown.sh -force

# start tomcat
/opt/tomcat8/bin/catalina.sh run
