#!/bin/bash

# Init variables
BASE_DIR="/etc/systemd/system/multi-user.target.wants/"
FILES_LIST="systran-corpus-manager2.service systran-gdict.service systran-routing.service systran-dct-indexer.service systran-tm-indexer.service systran-ses-console.service systran-ses-gateway.service systran-trs-console.service"

# System check
echo "Checking system..." #########################################################

which systemctl > /dev/null
if [ ! $? -eq 0 ]; then
  echo "Systemd seems not installed. Exiting..."
  exit 1
fi

for i in $FILES_LIST; do
  if [ ! -e $BASE_DIR$i ]; then
    echo "File $BASE_DIR$i is missing. Exiting..."
	  exit 1
  fi
done

echo "Checking system... Done" #########################################################

# SYSTRAN services files edition
echo "Editing SYSTRAN services files..." ###########################################

for i in $FILES_LIST; do
  grep -i "Wants" $BASE_DIR$i > /dev/null
  if [ ! $? -eq 0 ]; then
    sed -i --follow-symlinks '/^Description=.*$/a Wants=mongod.service rabbitmq-server.service redis.service' $BASE_DIR$i
  else
    sed -i --follow-symlinks 's/^Wants=.*$/Wants=mongod.service rabbitmq-server.service redis.service/g' $BASE_DIR$i
  fi
  sed -i --follow-symlinks 's/^After=.*$/After=network.target mongod.service rabbitmq-server.service redis.service/g' $BASE_DIR$i
done

echo "Editing SYSTRAN services files... Done" ########################################

# Systemd reload
echo "Reloading systemd configuration..." ###########################################

systemctl daemon-reload
if [ ! $? -eq 0 ]; then
  echo "Systemd reload failed. Exiting..."
  exit 1
fi

echo "Reloading systemd configuration... Done" #######################################################

# SYSTRAN services restart
echo -e "Restarting SYSTRAN services..." ###############################################

for i in $FILES_LIST; do
  systemctl restart $i
  if [ ! $? -eq 0 ]; then
    echo "Restart of service $i failed. Exiting..."
	exit 1
  fi
done

echo "Restarting SYSTRAN services... Done" ################################################

exit 0
