#!/bin/bash
#
# sailing    Starts sailing services
#
# chkconfig: 2345 95 10
# description: Sailing contains all sailing services
#


# Source function library. This alters the PATH variable.
if [ -f /etc/init.d/functions ]; then
  . /etc/init.d/functions
fi
RETVAL=0

SERVERS_DIR=/home/sailing/servers
cd "${SERVERS_DIR}"
JAVA_START_INSTANCES="$(find * -type d -prune)"
if [ -x /bin/ec2-metadata ]; then
  EC2_METADATA_CMD=/bin/ec2-metadata
elif [ -x /usr/bin/ec2-metadata ]; then
  EC2_METADATA_CMD=/usr/bin/ec2-metadata
else
  EC2_METADATA_CMD=/opt/aws/bin/ec2-metadata
fi
REBOOT_INDICATOR=/var/lib/sailing/is-rebooted
mkdir --parents $( dirname ${REBOOT_INDICATOR} )
SSH_KEY_READER_BEARER_TOKEN=/root/ssh-key-reader.token

echo "Executing with $1 at `date`"

start_servers() {
    /usr/local/bin/update_authorized_keys_for_landscape_managers $( cat ${SSH_KEY_READER_BEARER_TOKEN} ) https://security-service.sapsailing.com /root
    chown root:root /usr/local/bin/cp_root_mail_properties
    chmod 755 /usr/local/bin/cp_root_mail_properties
    if which $EC2_METADATA_CMD && $EC2_METADATA_CMD -d | sed "s/user-data\: //g" | grep "^image-upgrade$"; then
        echo "Found image-upgrade in EC2 user data; not configuring/starting sailing server processes"
    else
        echo "No image-upgrade request found in EC2 user data $($EC2_METADATA_CMD -d); proceeding with regular server launch..."
        echo "Servers to launch: ${JAVA_START_INSTANCES}"
        if [ -f "${REBOOT_INDICATOR}" ]; then
            echo "This is a re-boot. No EC2 user data is evaluated for server configuration; no server configuration is performed. Only configured applications are launched."
            for conf in ${JAVA_START_INSTANCES}; do
                su - sailing -c "cd ${SERVERS_DIR}/${conf} && ./start"
            done
        else
            echo "This is a first-time boot. EC2 user data is evaluated for potential application deployment and configuration, and applications are launched."
            echo "Initializing local MongoDB replica set \"replica\"..."
            while ! mongosh --quiet --eval "rs.initiate()"; do
                echo "MongoDB not ready yet; waiting and trying again..."
                sleep 5
            done
            FIRST_SERVER=$( eval $( ${EC2_METADATA_CMD} -d | sed -e 's/^user-data: //' ); echo $SERVER_NAME )
            if [ "${FIRST_SERVER}" = "" ]; then
                echo "No SERVER_NAME provided; not configuring/starting any application processes"
            else
                echo "Server to configure and start: ${FIRST_SERVER}"
                configure_and_start_server "${FIRST_SERVER}"
            fi
            echo 1 >"${REBOOT_INDICATOR}"
        fi
    fi
}

# Call with the server directory name (not the full path, just a single element from ${JAVA_START_INSTANCE}) as parameter
# Example:        configure_and_start_server server
# This is expected to be called only in case there is only one server to configure; otherwise, the same EC2 user data
# would get applied to all application configurations which would not be a good idea.
configure_and_start_server() {
  conf="$1"
  mkdir -p "${SERVERS_DIR}/${conf}" >/dev/null 2>/dev/null
  chown sailing "${SERVERS_DIR}/${conf}"
  chgrp sailing "${SERVERS_DIR}/${conf}"
  # If there is a secret /root/mail.properties, copy it into the default server's configuration directory:
  /usr/local/bin/cp_root_mail_properties "${conf}"
  su - sailing -c "cd ${SERVERS_DIR}/${conf} && refreshInstance.sh auto-install; ./start"
}

stop_servers() {
    for conf in $JAVA_START_INSTANCES; do
        echo "Stopping Java server $conf"
        su - sailing -c "cd $SERVERS_DIR/$conf && ./stop"
        sync_logs
    done
}

sync_logs() {
    echo "Executing logrotate followed by a sync to ensure that logs are synchronized"
    logrotate -f /etc/logrotate.conf
    sync
}

# See how we were called.
case "$1" in
  start)
    start_servers
    /usr/sbin/update-motd
    touch /var/lock/subsys/sailing
    ;;
  stop)
    stop_servers
    rm -f /var/lock/subsys/sailing
    ;;
  status)
    status java
    RETVAL=$?
    ;;
  *)
    echo $"Usage: $0 {start|status|stop}"
    RETVAL=3
esac

exit $RETVAL
