#!/bin/sh

# errors shouldn't cause script to exit
set +e

# add upstart profile, or init.d/systemd script and start the server
if test -d /etc/init/
then
   # remove any previously existing init.d based scheme
   service shiny-server stop 2>/dev/null
   rm -f /etc/init.d/shiny-server

   cp ${CMAKE_INSTALL_PREFIX}/shiny-server/config/upstart/shiny-server.conf /etc/init/
   initctl reload-configuration
   initctl stop shiny-server 2>/dev/null
   sleep 1
   initctl start shiny-server
elif [ -d /etc/systemd/system ]
then
   # SLES 12 upgrades from pre-1.5.7 will be running shiny-server using SysV init scripts.
   # Make sure that the process is stopped before we proceed. Really this should be in the
   # postrm scripts too, but too late in this release to add that.
   if [ -f /var/run/shiny-server.pid ]
   then
      pkill -F /var/run/shiny-server.pid
      /usr/bin/env sleep 5
   fi

   cp ${CMAKE_INSTALL_PREFIX}/shiny-server/config/systemd/shiny-server.service /etc/systemd/system/shiny-server.service
   systemctl enable shiny-server
   systemctl restart shiny-server
else
   if test -e /etc/SuSE-release
   then
      cp ${CMAKE_INSTALL_PREFIX}/shiny-server/config/init.d/suse/shiny-server /etc/init.d/
   else
      cp ${CMAKE_INSTALL_PREFIX}/shiny-server/config/init.d/redhat/shiny-server /etc/init.d/
   fi

   chmod +x /etc/init.d/shiny-server
   chkconfig --add shiny-server
   service shiny-server stop 2>/dev/null
   sleep 1
   service shiny-server start
fi

# clear error termination state
set -e
